Collapsing Code (Folding) in Xamarin Studio

In my opinion, this is one of the most useful and hidden feature. In Xamarin Studio you are able to fold or unfold your code by simply enabling this feature in Preferences:

Schermata 2016-06-19 alle 12.01.39

And this is the final result:

Schermata 2016-06-19 alle 11.59.59

I really like it!

My ViewModel base class implementation for Xamarin.Forms

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 _Something_ExecuteCommand:

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 _Save_CanExecuteCommand. 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!

Benvenuto Xamarin Studio 6.0

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/

Welcome Xamarin Studio 6.0

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/

 

Cognitive Services: Intelligenza Artificiale nelle tue App

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, etc…
  • 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

NuvolaRosa: un evento italiano dedicato alle tech-girls!

Lunedì 9 maggio ho avuto il grandissimo onore di partecipare come speaker ad un evento di portata nazionale come #NuvolaRosa, un evento organizzato con l’obiettivo di coinvolgere le ragazze in quelle che sono le evoluzioni, o rivoluzioni, in atto nel mondo del lavoro, soprattutto in ambito tecnologico.

L’evento ha visto la partecipazione di oltre 800 ragazze, studentesse di scuola superiore e universitarie, coinvolte tra corsi, talk e hackaton in una due giorni senza sosta presso il Politecnico di Bari.

nuvola_rosa_4

E’ stata un’esperienza particolare e davvero unica, soprattutto nel vedere così tante ragazze appassionate di tecnologia ed incuriosite sui possibili risvolti che può avere nel mondo lavorativo. Io ho avuto il piacere di tenere due seminari in cui si è parlato di Microsoft Azure e del Cloud Computing che, mentre per alcune di loro era gi ben noto, per altre è stata una piacevole sorpresa. E’ stato inoltre molto piacevole raccogliere interessanti feedback dopo aver tenuto le sessioni e sapere che quanto detto è stato recepito e soprattutto è andato a riempire un bagaglio di conoscenze prezioso per il loro futuro.

Un ringraziamento particolare va a tutto lo staff di NuvolaRosa per l’organizzazione e la passione in una manifestazione così ampia ed importante. Non è mai semplice, gli ostacoli sono tanti, ma credo che l’ottimo risultato ripaga ampiamente l’impegno profuso.

Al prossimo anno!

nuvola_rosa_3 nuvola_rosa_2 nuvola_rosa_1

MVP Award 2016!

MVP_Logo_Preferred_Cyan300_RGB_300ppiI’m very excited to be awarded as MVP for the seventh year in a row! Great! I would like to say thanks to all my friends and members of the DotNetSide user group that support me with great passion and enthusiasm!

Also thanks to Microsoft, in the person of Christina and Marjorie, and to all MVPs, a big family that loves share its passion for technology.

So, I’m now ready for a great new year. Microsoft made a big step forward embracing the open source world. We’ll see what happens!

 

Animation in Xamarin.Forms

Xamarin.Forms provides the ability to create easy and wonderful views animations with few lines of code. For example, if you need to rotate a View, you can simple set the Rotation property, like this:

Device.StartTimer (TimeSpan.FromMilliseconds (100), () => {
    this.Ball.Rotation+=1;
    return true;
});

So, you can get this effect:

RotatingImage

Enjoy!

A little and simple Bindable (Horizontal) Scroll View

In one project I was working on, a page needs to show a short horizontal and scrollable list of items (something like the Apple App Store app). Xamarin.Forms offers the ability to use a ScrollView control to show a list of items horizontally but, in my case, the items I must to show comes from a dinamically populated list. In that case I’ve extended the ScrollView control and added the ItemsSource and ItemTemplate property.

public class TLScrollView : ScrollView
{
	public static readonly BindableProperty ItemsSourceProperty =
		BindableProperty.Create("ItemsSource", typeof(IEnumerable), typeof(TLScrollView), default(IEnumerable));

	public IEnumerable ItemsSource
	{
		get { return (IEnumerable)GetValue(ItemsSourceProperty); }
		set { SetValue(ItemsSourceProperty, value); }
	}

	public static readonly BindableProperty ItemTemplateProperty =
		BindableProperty.Create("ItemTemplate", typeof(DataTemplate), typeof(TLScrollView), default(DataTemplate));

	public DataTemplate ItemTemplate
	{
		get { return (DataTemplate)GetValue(ItemTemplateProperty); }
		set { SetValue(ItemTemplateProperty, value); }
	}
}

After that, I’ve added a simple method, Render, to populate the ScrollView:

public void Render ()
{
	if (this.ItemTemplate == null || this.ItemsSource == null)
		return;
	
	var layout = new StackLayout ();
	layout.Orientation = this.Orientation == ScrollOrientation.Vertical 
		? StackOrientation.Vertical : StackOrientation.Horizontal;

	foreach (var item in this.ItemsSource) {
		var viewCell = this.ItemTemplate.CreateContent () as ViewCell;
		viewCell.View.BindingContext = item;
		layout.Children.Add (viewCell.View);
	}

	this.Content = layout;
}

That method will be called from the TLScrollViewRenderer (iOS and Android are pretty similar). The renderer is a special class that adapts the Xamarin.Forms control into a native control:

[assembly: ExportRenderer(typeof(TLScrollView), typeof(TLScrollViewRenderer))]

namespace TitiusLabs.Forms.iOS.Controls
{
	public class TLScrollViewRenderer : ScrollViewRenderer
	{
		protected override void OnElementChanged(VisualElementChangedEventArgs e)
		{
			base.OnElementChanged(e);

			var element = e.NewElement as TLScrollView;
			element?.Render();
		}
	}
}

Now you can use the TLScrollView in your xaml and create your custom template in this way:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:controls="clr-namespace:TitiusLabs.Forms.Controls;assembly=TitiusLabs.Forms" xmlns:local="clr-namespace:FormSamples" x:Class="FormSamples.Core.Views.FormSamplesPage">
	<StackLayout Padding="20">
		<controls:TLScrollView Orientation="Horizontal" ItemsSource="{Binding Items}" HeightRequest="100">
			<controls:TLScrollView.ItemTemplate>
				<DataTemplate>
					<ViewCell>
						<StackLayout Padding="5">
							<controls:TLImageCircle Source="{Binding Image}" HeightRequest="80" WidthRequest="80" />
						</StackLayout>
					</ViewCell>
				</DataTemplate>
			</controls:TLScrollView.ItemTemplate>
		</controls:TLScrollView>
	</StackLayout>
</ContentPage>

This is the final result:

Amazing!

**UPDATE 12.04.2016: some small refactoring to the custom horizontal ScrollView control

**

Full code is available here


Why developers call it “bug”!

Why software error or anomaly is called “bug”?

One of the first big calculator, the Mark II, suddenly stopped to work during one night. Engineers, as they tried the problem, they found a moth (bug) trapped in a relay.

This was the “first case of bug being found”.

Starting from that event, the act of looking for a bug was called “debugging”, that means “pest control”.

Nice story 🙂