Last Friday in Bari, DotNetSide has hosted one stop of the Xamarin Dev Days tour in Italy. It was really an amazing day spent with very passionate people talking about Xamarin and how is funny to develop with their tools.

During the day, we talked about Xamarin development with Xamarin.Forms combined with Cognitive Services, Mobile Apps, remote APIs and so on. In the afternoon, a great hands-on lab was made by around 40 people with the intention¬†to share their knowledge (and win a Xamarin monkey! ūüėÄ ).

cygf4_iwgaabjx5

After the announcements made by Microsoft at Connect(); conference last week, we decided to include an extra slot to talk about Visual Studio for Mac, Visual Studio Mobile Center and .NET Standard.

cyghtedxeaafjq5

It was a really great day. I like to see how many people loves their job and try to improve with great passion.

Thanks to all and thanks to the DotNetSiders! You rocks!

Read more

If you are a typical Visual Studio user, you’ll find easy use the menu Debug > Windows > Exception Settings and set your favorite option to break debug when a specific exeption was thrown:

schermata-2016-10-26-alle-21-58-42

But, in Xamarin Studio, that thing is just a little bit different. You need to set a new breakpoint from the men√Ļ Run > New Breakpoint:

schermata-2016-10-26-alle-22-02-54

Then you must select the “When an exception is thrown” options:

schermata-2016-10-26-alle-22-04-36

Finally, you can choose the exception that will cause the debugger’s break, eventually by including their subclasses:

schermata-2016-10-26-alle-22-06-18

That’s all!

Read more

Some days ago I have published a¬†sample¬†Xamarin.Forms control to¬†simply move focus on others controls of the page. I’ve presented just the iOS version but now it’s the time to see¬†also the Android implementation.

TLEntryRenderer in Android

The control is so simple that in just few lines of codes we’ll be able to realize the Android version. Here the renderer code:

[assembly: ExportRenderer(typeof(TLEntry), typeof(TLEntryRenderer))]
namespace TitiusLabs.Forms.Droid.Controls
{
	public class TLEntryRenderer : EntryRenderer
	{
		protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
		{
			base.OnElementChanged(e);

			var element = e.NewElement as TLEntry;
			if (element.ReturnButton == ReturnButtonType.Next)
			{
				Control.ImeOptions = Android.Views.InputMethods.ImeAction.Next;
				Control.EditorAction += (sender, args) =>
				{
					element.OnNext();
				};
			}
		}
	}
}

the code is available, as always, on github.

This is the final result:

movefocus_xamarinforms_android

Nice and simple!

Read more

Spending some time with good friends is always a¬†great way to start ideas. So, while talking with one of them, he asked me the best way to handle focus on entries¬†in a Xamarin.Forms Page. I’ve handled the problem many times in iOS and Android native projects, so I decided to create a new control in my library on github.

Welcome TLEntry: the custom Entry control

First of all, we have to create a custom control because the user needs to set the type of return button on the keyboard:

public class TLEntry : Xamarin.Forms.Entry
{
	public static readonly BindableProperty ReturnButtonProperty = 
		BindableProperty.Create("ReturnButton", typeof(ReturnButtonType), typeof(TLEntry), ReturnButtonType.None);

	public ReturnButtonType ReturnButton
	{
		get { return (ReturnButtonType)GetValue(ReturnButtonProperty); }
		set { SetValue(ReturnButtonProperty, value); }
	}
}

After doing that, we need to handle the tap on the button and move the focus on the next control. One way to do that is by knowing the next control and set the focus to it after the next button was pressed. So now we need to know the next control by settings a specific property:

[assembly:ExportRenderer(typeof(TLEntry), typeof(TLEntryRenderer))]
...
public class TLEntry
{
	public static readonly BindableProperty NextViewProperty = 
		BindableProperty.Create("NextView", typeof(View), typeof(TLEntry));

	public View NextView
	{
		get { return (View)GetValue(NextViewProperty); }
		set { SetValue(NextViewProperty, value); }
	}

	public void OnNext()
	{
		NextView?.Focus();
	}
}

Now is the time to create the platform specific renderers.

TLEntryRenderer: the iOS platform-specific renderer

A renderer is a special class with the role of transform a Xamarin Forms control in a native control. So now we needs to transform the TLEntry in a UITextField for the iOS platform. Since we already have renderers for standard control, handle the new ReturnButton and NextView properties simply means to extend the base renderer and create a new one like this:

public class TLEntryRenderer : EntryRenderer
{
	protected override void OnElementChanged(ElementChangedEventArgs&amp;amp;amp;amp;amp;amp;amp;amp;lt;Entry&amp;amp;amp;amp;amp;amp;amp;amp;gt; e)
	{
		base.OnElementChanged(e);

		var element = e.NewElement as TLEntry;
		if (element.ReturnButton == ReturnButtonType.Next)
		{
			Control.ReturnKeyType = UIKit.UIReturnKeyType.Next;
			Control.ShouldReturn += (textField) =&amp;amp;amp;amp;amp;amp;amp;amp;gt;
			{
				element.OnNext();
				return false;
			};
		}
	}
}

With this code, we set the ReturnKeyType on UITextView and add an handler that capture the pressure on the return button and go to the next item.

Now, in your Page, you can do something similar:

public partial class FormSamplesPage : ContentPage
{
	TLEntry Entry1 = new TLEntry();
	TLEntry Entry2 = new TLEntry();
	TLEntry Entry3 = new TLEntry();

	protected override void OnAppearing()
	{
		base.OnAppearing();

		Entry1.NextView = Entry2;
		Entry1.ReturnButton = ReturnButtonType.Next;

		Entry2.NextView = Entry3;
		Entry2.ReturnButton = ReturnButtonType.Next;

		Entry3.NextView = Entry1;
		Entry3.ReturnButton = ReturnButtonType.Next;

		this.Body.Children.Add(Entry1);
		this.Body.Children.Add(Entry2);
		this.Body.Children.Add(Entry3);
	}
}

this is the final result:

ezgif-2133599902

Nice!

You can find all code on my github space: https://github.com/fabiocozzolino/TitiusLabs.Xamarin

The Android version will be available soon!

Read more

The MVVM is one of the most used¬†architectural pattern to easily separate the UI development from the business logic.¬†When you choose that pattern, you know that the ViewModel class implements many things: property change notifications, commands to execute code based on user interaction, data loading, etc…, and, every time, you need to write the same code to complete those actions.

In this post we will see how to¬†simplify the writing of the ViewModel classes by using some tricks and put them in a ViewModelBase class. If you don’t know nothing about the MVVM pattern, you can read more at the following page:¬†https://msdn.microsoft.com/en-us/library/hh848246.aspx.

Data Binding

Bind data to your view is one of the principles on which MVVM is based. Data bindings is a mechanism that allows to tie any property of a visual element to a property of a backend class. That kind of tie can be bidirectional: from the view to the class and from the class to the view. While the first way is the simplest one, the second way needs just some code to be completed: you need to implement the INotifyPropertyChanged interface to notify the view that a property value has changed.

Implements the INotifyPropertyChanged interface requires some code that can be factored in the ViewModelBase class:

public abstract class ViewModelBase : INotifyPropertyChanged
{
	public event PropertyChangedEventHandler PropertyChanged;

	protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
	{
		var handler = PropertyChanged;
		if (handler != null)
			handler (this, new PropertyChangedEventArgs(propertyName));
	}
}

With this base class, now you can write our bindable properties in the ViewModel implementation without reimplement the INotifyPropertyChanged every time:

public class MyViewModel : ViewModelBase
{
	private string _title;
	public string Title
	{
		get 
		{
			return _title;
		}
		set
		{
			if (value != _title)
			{
				_title = value;
				OnPropertyChanged();
			}
		{
	}		
}

As said before, you need to notify to the View that something has changed. A lot of code, right? A step over could helps us to write a smaller code, like this:

public class MyViewModel : ViewModelBase
{
	public string Title
	{
		get { return GetValue<string>(); }
		set { SetValue(value); }
	}		
}

Better and simplest. To accomplish this, you can implement the GetValue and SetValue methods in the ViewModelBase class and stores the properties values in a Dictionary:

private Dictionary<string, object> properties = new Dictionary<string, object>();

protected void SetValue<T>(T value, [CallerMemberName] string propertyName = null)
{
	if (!properties.ContainsKey (propertyName)) {
		properties.Add (propertyName, default(T));
	}

	var oldValue = GetValue<T>(propertyName);
	if (!EqualityComparer<T>.Default.Equals(oldValue, value)) {
		properties [propertyName] = value;
		OnPropertyChanged (propertyName);
	}
}

protected T GetValue<T>([CallerMemberName] string propertyName = null)
{
	if (!properties.ContainsKey (propertyName)) {
		return default(T);
	} else {
		return (T)properties [propertyName];
	}
}

That piece of code simplifies writing a derived ViewModelBase class. Now the MyViewModel class, with the smaller code, is much more maintenable.

Automatic Relay Command implementation

A further step forward in your ViewModelBase consists in develop an automatic and simple way to delegate the execution of commands. In MVVM, a command is a piece of code executed in response of a view interaction. To create a command, you must implement the ICommand interface and put your code in it. The power of this approach helps you to create a code that can be used in multiple views, but sometimes you need to use that command only one time.

So, to simplify writing commands implementation, we can create a delegate at ViewModelBase level for each required command. Check this code:

private Dictionary<string, ICommand> commands = new Dictionary<string, ICommand>();

private const string EXECUTECOMMAND_SUFFIX = "_ExecuteCommand";
private const string CANEXECUTECOMMAND_SUFFIX = "_CanExecuteCommand";

public ViewModelBase()
{
	this.commands = 
		this.GetType ().GetTypeInfo ().DeclaredMethods
		.Where (dm => dm.Name.EndsWith (EXECUTECOMMAND_SUFFIX))
		.ToDictionary (k => GetCommandName (k), v => GetCommand (v));
}

private string GetCommandName(MethodInfo mi)
{
	return mi.Name.Replace (EXECUTECOMMAND_SUFFIX, "");
}

private ICommand GetCommand (MethodInfo mi)
{
	var canExecute = this.GetType().GetTypeInfo().GetDeclaredMethod (GetCommandName(mi) + CANEXECUTECOMMAND_SUFFIX);
	var executeAction = (Action<object>)mi.CreateDelegate (typeof(Action<object>), this);
	var canExecuteAction = canExecute != null ? (Func<object, bool>)canExecute.CreateDelegate (typeof(Func<object, bool>), this) : state => true;
	return new Command (executeAction, canExecuteAction);
}

public ICommand this[string name] {
	get{
		return commands [name];
	}
}

When the ViewModel instance is created, we collect any method with the suffix “ExecuteCommand” (you can decide to use any kind of suffix), so in the derived class we can write methods with the name¬†SomethingExecuteCommand:

public class MyViewModel : ViewModelBase
{
	public void Save_ExecuteCommand(object state)
	{
	}

	public bool Save_CanExecuteCommand(object state)
	{
	}
}

In this example you see also a method called SaveCanExecuteCommand. This is optional, since the base class creates a delegate at runtime with return value equals to true if no one has been found.

Finally, in the view, you can write something like this:

<Button Command="{Binding [Save]}" CommandParameter="{Binding MyProperty}" />

Really simple!

Conclusion

The ViewModelBase is only a way to simplify ViewModel class development and avoid a lot of code duplication. Obviously this is not the answer for everything.

Let me know what do you think about it!

Read more

Ieri¬†Miguel, durante il suo¬†talk alla dotNetConf, ha annunciato la disponibilit√† di Xamarin Studio 6.0. Con questa versione noi sviluppatori possiamo godere di diverse nuove feature, molte delle quali non direttamente visibili, come il miglioramento della funzionalit√† di completamento del codice, il completo supporto a C# 6.0 e un nuovo motore di formattazione. Il tutto grazie all’integrazione del nuovo type system portato da Roslyn, il compilatore .NET open source di Microsoft.

Ma, devo ammettere, che la feature che mi piace di pi√Ļ √® il tema dark in Xamarin Studio 6!

La ragione √® forse la pi√Ļ semplice: mi piace ed uso il tema dark in Visual Studio 2015 e, dal momento che lavoro con entrambi, passare continuamente da uno sfondo scuro ad un bianco non √® proprio una buona idea per i miei occhi. Inoltre, il tema dark √® decisamente pi√Ļ rilassante per me.

Ben fatto !

Source:
https://blog.xamarin.com/live-from-dotnetconf-cycle-7-xamarin-studio-6-and-more/

Ps.: ovviamente c’√® molto altri, come il supporto alla code completition di C# 6.0 e alle operazioni di refactoring! Ah, e non dimentichiamoci della possibilit√† di spostare le finestre di codice al di fuori di Xamarin Studio!

Potete trovare qui l’intera lista delle novit√†:
https://developer.xamarin.com/releases/studio/xamarin.studio_6.0/xamarin.studio_6.0/

Read more

Yesterday Miguel, during its talk at dotNetConf, has announced the¬†release of Xamarin Studio 6.0.¬†With this¬†version you got a lot of benefits “including enhanced code completion, full C# 6.0 support, and a new formatting engine” thanks to the new¬†type system, now powered by Roslyn, the Microsoft‚Äôs open source .NET compiler platform.

But, you know, the feature that I really like in this cycle 7 is the dark theme in Xamarin Studio 6!

the reason is the simplest one : I like the Visual Studio 2015 Dark Theme and, since I work with both, switch from a white background to a black background, and viceversa, is not a good idea for my eyes . Furthermore , the dark theme is more relaxing for me.

Well done guys !

Source:
https://blog.xamarin.com/live-from-dotnetconf-cycle-7-xamarin-studio-6-and-more/

Ps.: obviously there is much more, like¬†the¬†full support of¬†C# 6.0 for code completion and refactoring operations! Ah, don’t forget also the ability to move windows outside!

Check here the entire list of changes:
https://developer.xamarin.com/releases/studio/xamarin.studio_6.0/xamarin.studio_6.0/

 

Read more

Durante¬†la BUILD 2016 di Microsoft tenuta a San Francisco lo scorso aprile, sono state annunciate diverse¬†novit√†¬†in grado di portare all’interno delle nostre applicazioni¬†evoluzioni importanti. Una di queste, probabilmente la pi√Ļ rilevante, √® senza dubbio l’Intelligenza Artificiale.

Due gli annunci principali:

  • Microsoft BOT Framework
  • Cognitive Services

Cosa sono i BOT Frameworks? Immaginate di voler integrare in applicazioni come Facebook Messenger, Skype o Slack un’assistente virtuale in grado di¬†rispondere alle domande¬†ed eseguire azioni come se si trattasse di una persona reale. Ecco, il BOT Framework fornisce tutti gli strumenti necessari per creare applicazioni in grado di fare tutto questo. Mi riprometto di parlarne in uno dei prossimi post.

Parallelamente ai BOT Framework, Microsoft ha presentato al pubblico anche i Cognitive Services, un set di API in grado di fornire alle applicazioni la capacità di vedere, ascoltare, interpretare ed interagire in modi molto simili a come farebbe una comune persone. Una soluzione assolutamente interessante che porta ad un livello superiore le possibilità di sviluppo delle nostre applicazioni. Ma vediamo come funzionano.

I Cognitive Services si dividono in 5 macro aree, ognuna con un set di servizi:

CognitiveServices

Cose da sapere

Il punto di partenza è senza dubbio il sito web https://www.microsoft.com/cognitive-services. Qui potete trovare tutte le informazioni utili per attivare la vostra subscription. Sì, è ovviamente necessaria una sottoscrizione per poter utilizzare i Cognitive Services. Ogni servizio, fortunatamente, ha un limite di utilizzo gratuito. Ad esempio è possibile effettuare fino a 20 invocazioni al minuto per un massimo di 30000 al mese per il servizio di riconoscimento facciale (Face API).

Una volta attivata la sottoscrizione, potete visualizzare l’elenco dei servizi e ottenere le chiavi¬†di autenticazione.

Schermata 2016-06-04 alle 11.52.51

Potete utilizzare indifferentemente sia la Key 1 che la Key 2. Le chiavi devono essere poi utilizzate dal nostro client per invocare il servizio richiesto. E’ possibile utilizzare i servizi in¬†due diverse modalit√†:

  • REST API
  • Client SDK

Face REST API

In questo post¬†vedremo come utilizzare¬†una delle funzionalit√†¬†dei Cognitive Services: le Face API.¬†Il servizio √® raggiungibile all’indirizzo¬†https://api.projectoxford.ai/face/v1.0/detect. Il parametro obbligatorio √® proprio la chiave che abbiamo visto in precedenza,¬†che¬†deve necessariamente essere indicata¬†nell’header HTTP¬†Ocp-Apim-Subscription-Key.

public async HttpResponseMessage DetectAsync(Stream stream)
{
	var url = "https://api.projectoxford.ai/face/v1.0/detect";

	var requestContent = new StreamContent (stream);
	requestContent.Headers.Add ("Ocp-Apim-Subscription-Key", your-subscription-key);
	requestContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue ("application/octet-stream");
	var client = new HttpClient ();
	return await client.PostAsync (url, requestContent);
}

Con questo codice inviamo un’immagine, contenente volti, al servizio di face detection, impostando la chiave nell’header. La risposta √® un json simile a questo:

[
    {
        "faceId": "4a97f6af-bc7d-4c0c-be41-dca3eea0937f",
        "faceRectangle": {
            "top": 127,
            "left": 306,
            "width": 75,
            "height": 75
        },
        "faceLandmarks": {
            "pupilLeft": {
                "x": 330.3,
                "y": 143.7
            },
            "pupilRight": {
                "x": 357.8,
                "y": 149.0
            },
            ...
        },
        "faceAttributes": {
            "smile": 0.573,
            "headPose": {
                "pitch": 0.0,
                "roll": 6.0,
                "yaw": 20.7
            },
            "gender": "male",
            "age": 39.4,
            "facialHair": {
                "moustache": 0.7,
                "beard": 0.8,
                "sideburns": 0.5
            },
            "glasses": "ReadingGlasses"
        }
    }
]

Il json riporta informazioni sulla posizione e dimensione del viso nell’immagine, la posizione di caratteristiche somatiche come le pupile, il naso, la bocca, etc… Infine, vengono riportate informazioni¬†sul viso rilevato: ha la barba, i baffi o le basette, porta gli occhiali, l’et√†, il sesso, se sta sorridendo e l’eventuale¬†inclinazione del viso.

Il json può essere trasformato in un set di classi C#. Ne riporto una parte per brevità:

public class FaceRectangle
{
	public int top { get; set; }
	public int left { get; set; }
	public int width { get; set; }
	public int height { get; set; }
}

public class Face
{
	public string faceId { get; set; }
	public FaceRectangle faceRectangle { get; set; }
}

Infine, modifichiamo il nostro metodo DetectAsync per recuperare il JSON dalla risposta HTTP e deserializzarlo in un array di oggetti di tipo Face:

public async Task<Face[]> DetectAsync(Stream stream)
{
	...
	var client = new HttpClient ();
	var response = await client.PostAsync (url, requestContent);

	var responseContent = response.Content as StreamContent;
	var jsonResponse = await responseContent.ReadAsStringAsync ();

	return JsonConvert.DeserializeObject<Face[]> (jsonResponse);
}

E voilà. Ora possiamo utilizzare la classe Face per recuperare le informazioni e tracciare un rettangolo intorno al viso.

var client = new FaceClient ();
var faces = await client.DetectAsync (inputImage);
foreach (var item in faces) {

	var layout = new StackLayout ();

	var box = new ShapeView ();
	box.ShapeType = ShapeType.Box;
	box.WidthRequest = (item.faceRectangle.width + 20) / 2;
	box.HeightRequest = (item.faceRectangle.height + 20) / 2;
	box.Color = Color.Transparent;
	box.BackgroundColor = Color.Transparent;
	box.StrokeColor = Color.White;
	box.StrokeWidth = 4;
	box.Padding = new Thickness (0);

	layout.Children.Add (box);

	bodyLayout.Children.Add (layout, new Point ((item.faceRectangle.left - 10) / 2, ((item.faceRectangle.top - 10) / 2) - 20));
}

Il codice mostra come¬†ciclare nel set di classi Face restituite dal servizio per costruire dei rettangoli intorno ai volti identificati nell’immagine. Il tutto all’interno di un’app sviluppata con Xamarin.Forms.

Microsoft Face API Client Library

Alternativamente, e pi√Ļ semplicemente, possiamo utilizzare l’SDK¬†disponibile come pacchetto¬†Nuget per¬†usufruire delle Face API. Come primo passo aggiungiamo al nostro progetto¬†il Microsoft Face API Client Library:

Schermata 2016-06-05 alle 12.29.23

Ora possiamo sostituire all’invocazione via REST API, l’utilizzo diretto della classe FaceServiceClient.

var client = new Microsoft.ProjectOxford.Face.FaceServiceClient (your-subscription-key);
var faces = await client.DetectAsync (inputImage);
foreach (var item in faces) {
    ...
}

il resto del codice non cambia rispetto a quanto abbiamo fatto con le REST API.

Informazioni aggiuntive sui volti

Ma le Face API sono in grado di restituire molte pi√Ļ informazioni rispetto al semplice “rettangolo” che racchiude il volto. Per ottenerle √® sufficiente specificare nella querystring i parametri:

  • returnFaceId
    restituisce l’identificativo del volto
  • returnFaceLandmarks
    restituisce informazioni sulle caratteristiche del volto, come la posizione degli occhi, della bocca, del naso, ecc…
  • returnFaceAttributes
    restituisce gli attributi del viso, come la barba, i baffi, il sorriso,¬†l’et√†, il sesso, etc…

Utilizzando le Face API possiamo¬†modificare l’URL utilizzato con questo:

var returnFaceId = true;
var returnFaceLandmarks = true;
var returnFaceAttributes = "age,gender,smile,facialHair,headPose,glasses";
var url = $"https://api.projectoxford.ai/face/v1.0/detect?returnFaceId={returnFaceId}&amp;returnFaceLandmarks={returnFaceLandmarks}&amp;returnFaceAttributes={returnFaceAttributes}";

Per recuperare le informazioni dal JSON, infine, aggiungiamo le seguenti classi e la proprietà faceAttributes a quanto già scritto:

public class HeadPose
{
	public double pitch { get; set; }
	public double roll { get; set; }
	public double yaw { get; set; }
}

public class FacialHair
{
	public double moustache { get; set; }
	public double beard { get; set; }
	public double sideburns { get; set; }
}

public class FaceAttributes
{
	public double smile { get; set; }
	public HeadPose headPose { get; set; }
	public string gender { get; set; }
	public double age { get; set; }
	public FacialHair facialHair { get; set; }
	public string glasses { get; set; }
}

public class Face
{
	...
	public FaceAttributes faceAttributes { get; set; }
}

Ora siamo in grado di¬†ottenere le informazioni aggiuntive sui volti identificati. L’utilizzo con la Client Library √® altrettanto semplice:

var client = new Microsoft.ProjectOxford.Face.FaceServiceClient (SubscriptionKeys.FaceId);
var faces = await client.DetectAsync(imageStream, 
	returnFaceId:true, 
	returnFaceLandmarks:true, 
	returnFaceAttributes: new [] { 
	Microsoft.ProjectOxford.Face.FaceAttributeType.Age,
	Microsoft.ProjectOxford.Face.FaceAttributeType.Gender});

Risultato

Il risultato finale, che in un’app¬†visualizza i volti trovati in un rettangolo, √® il seguente:

CjdK25dUgAQ5rdb

Conclusioni

La scelta delle REST API o delle Client Library dipende dalla propria architettura. Tendenzialmente è preferibile utilizzare le Client Library, quando queste sono disponibili per la piattaforma utilizzata ma è utile avere anche a disposizione le REST API per tutte quelle piattaforme che non hanno un client SDK già disponibile.

Nei prossimi post, non so ancora quando, continueremo a sperimentare altre modalità di utilizzo dei Cognitive Services.

Potete scaricare il codice completo dell’esempio da qui:¬†https://github.com/fabiocozzolino/samples/tree/master/CloudFace

Read more