Corrado's Blog 2.0

Online thoughts of a technology funatic

UWP: Read German text from a file

I had some hard times figuring out how to properly read a file that contains typical German characters (e.g umlauts) so I want to share my solution in case are in the same situation.

The magic trick is to register a new provider named “windows-1254” using Encoding.RegisterProvider

Genymotion and VirtualBox install issue

I use Genymotion as Android emulator for my Xamarin work, I know that there are better alternatives like Microsoft’s Android emulator but since can’t turn on Hyper-V on my machine this is the solution that works best for me.

Haven’t done any Android development recently so since I need to prepare some demos for my forthcoming session at Future Decoded I checked my system and discovered that Android emulator wasn’t working anymore as happened in the past. Checked the logs but nothing evident was listed apart some in influent login error, I then tried to run VirtualBox alone and noted that it was not starting at all, no error nor messages, just nothing was happening.

Ok, let’s reinstall Genymotion to latest version, maybe recent Windows 10 Anniversay update broke something, did that, no errors but, nothing changed, ok, let’s try installing VirtualBox alone from Oracle site and BOOM! got a weird error message about an adapter not being created because it was not possible to rename it (WHAAAT?)

Fired up a search engine looking for solutions and found thousands of thread starting from 2010, some of them even suggesting to repave the entire machine, luckily among this tons of documentation my attention got catched by a guy that claimed to have solved using this steps:

  1. 1-Go to 
  2. C:\Program Files\Oracle\VirtualBox\drivers\network
    2-Go into each directory contained into network and install the drivers by tight clicking every .inf file and selection Install from popup menu


    3-Go to Network Connections, right click the Ethernet adapter associated with VirtualBox and select Properties


    4-On the network properties panel, click Install and select Services


    5-Now select the Oracle’s VirtualBox driver and select OK


    6-Be sure that VirtualBox NDIS driver is selected.


    7-Complete Genymotion install, if not already done, otherwise, just download a device and runt it, if it is your lucky day, it should work.

    You can read the original answer here, it also worked for me of course.

    …and after this annoying procedure you can go back coding in relax. Smile


    Beware of generated XAML in UWP

    I admit, this is s strange blog post title but that’s what this post is going to talk about.

    I’m working on a UWP app that has different min and target runtimes:


    After doing some UI work with Visual Studio & Blend I’ve discovered that the app was crashing on machines without Anniversary edition installed. At the end of a debuggin session I’ve found the reason: The XAML template generated by the tools contains incompatible elements (resources mainly, but also new properties) that are not present on previous builds.

    To give you an example, this is an extract from a ComboBox default template, generated by Blend when you use the Template->Edit copy feature:


    <Setter Property="Foreground"

    Value="{ThemeResource SystemControlForegroundBaseHighBrush}" />

    14393 (Anniversary)

    <Setter Property="Foreground"

    Value="{ThemeResource ComboBoxForeground}" />

    The reason of this is because the tools generate the template from the Target version SDK and not the Min version SDK that might even not be present.

    The team said that they’re going to give you some warnings in the future when situations like this happen, but in the meantime, at least when you’re doing design work, be sure to selected, the min target version SDK otherwise you might end up in troubles.

    Joining IBV


    Effective June 1st, after nearly 14 years as independent consultant I’ve joined the Swiss based company IBV as Senior Software Development Engineer, decision comes from the great work and career opportunity the company offered me just at a time when I was felting the need for new working stimuli.

    How this is going to change my life? not much indeed I’ll probably have to visit Switzerland more often and enjoy beautiful landscapes like this while driving to work


    and focus more on Natural User Experience (like Surface Hub and Hololens)

    image image

    The initial days I’ve spent in the near Zurich based office were really enjoyable, I’ve smelt the typical ‘startup’ like energy even if the company is now 35 years old.

    Another unexpected surprise was to discover that one of my new colleagues was my good old friend Alessandro Teglia who also joined as Chief Digital Officer.

    It was when the company’s boss, just after signing the contract, gave me this talisman, that I realized I did one of the best decision in my life and I thank fate for this.


    Last but not least, my “boss” (well, sound strange for me to call it “my boss” Smile) Gian Paolo Santopaolo, who is not only a great professional (and MVP like me) but also very great cook, he can do little food masterpieces in minutes.

    Regarding my community commitments, nothing changes, I’ll try to blog more about my new job (BTW: follow our company twitter account and, as usual, I’ll spread my technology passion as I always did in the past.

    I wish you all to work in a lovely place as IBV, it’s just there and fate will certainly let you find it, just don’t give up searching.


    I am a Xamarin MVP!

    Xamarin, like Microsoft has its own MVP (Most Valuable Professional) program that awards people “who have demonstrated an exemplary commitment to helping others get the most out of their experience with Xamarin by sharing their passion, real-world knowledge, and technical expertise with developers all over the world.”

    I am pleased to announce that I’ve been awarded Xamarin MVP, and this makes me extremely proud and happy, being the first Italian in this close group of internationally known Xamarin experts, give me a high level of responsibility and I’ll do my best continuing sharing my technology passion.

    If you haven’t tried Xamarin yet, I encourage you to do it, a lot changed since 2014 when I started approaching it (no Forms yet…) it is now a mature product and if you’re eager to learn more Xamarin University is here to help.

    Thanks Xamarin!

    A Smart RecyclerView Adapter for Xamarin.Android

    RecyclerView is the recommended way to represents a collection of items in Android applications, the good and old ListView is now deprecated since RecyclerView offers a lot of improvements like flexible layout, item recyclying and enforces the ViewHolder pattern.

    If you’re new to RecyclerView in Xamarin Android I recommend this article from Xamarin site, since it is also the origin project I’ve used on this post and this is not a RecyclerView tutorial.
    This post originates since every time I need to use a RecyclerView, even for simple demos like this blog post, I end up rewriting the same boilerplate code, so I decided to create a simple generic adapter that simplifies things for me.

    Source code and demo is available on GitHub here, so get it and have a look if you want to know more about the internals, I’ll just show you how to use it updaing the original Xamarin demo.

    Just create a class that inherits from abstract SmartRecyclerAdapter<T> class

    as you see, you just have to implement two methods OnLookupViewItems and OnUpdateView: OnLookupViewItems is used to extract the view items from inflated layout and save them into provided generic viewholder
    OnUpdateView is used to update the same view items with the fresh values coming from provided Item.

    Let’s see now in action, exploring the code in MainActivity:

    Very simple: I created an instance of the PhotoRecyclerAdapter passing to its constructor: the RecyclerView, an ObservableCollection<T> as item source and the optional id of the layout to inflate to create the items views (more on this later)

    Since we’re using an ObservableCollection<T> the list is smart enough to automatically invoke the several NotifyXYZ methods when you add/remove/move items from the collection as when the “Clear+Add” button of the demo is clicked.

    What if you need to use different layouts depending on items properties? just override base class GetViewIdForType method and return an int that will be passed to the othere method you’ll have to override named OnGetViewId inside this method, depending on passed viewTypeId you’ll return the item id to inflate for such element.

    The adapter automatically raises an ItemSelected event when an item is clicked, passing null as RecyclerView parameter on PhotoRecyclerAdapter constructor, disables this behavior and you can implement your own item selection strategy.

    It’s just a starting point, hope you’ll like it. Smile

    AutoHide FloatingActionButton in Xamarin.Android

    My main phone is an Android and as a news app I use a 3rd party aggregator that, al nearly all Android apps today is based on Material Design.
    Using it everyday I couldn’t ignore a nice UI feature it exposes: it’s share button (a Material Design’s FloatinActionButton) fades out when you scroll the list vertically and it reappears when you scroll the list down.
    Being curious, I wanted to know how to create that effect using Xamarin.Android.

    This is my final result:


    Since there’s a lot of setup involved I won’t go too much into code detail and setup, you can grab the project source code from here

    I’m assuming you have some basic knowledge of Material Design and  related steps to enable it into a Xamarin.Android app so and I’ll go straight to the point: The view you see is made up of a CoordinatorLayout that hosts a NestedScrollView that contains a series of CardViews and in the bottom right corner there is our FloatingActionButton.

    The trick of making it disappear is to add a custom behavior so that CoordinatorLayout knows that it has to invoke a behavior that takes care to hide/show it when something happen, in our case when user scrolls up or down.

    This is the required behavior

    Inside OnNestedStartScroll we inform the CoordinatorLayout that we want to receive scroll events when user scrolls vertically while inside OnNestedScroll we receive a reference to the FloatingActionButton (since we have applied the behavior to it) and depending on scroll direction we show/hide it.

    The hard part of migrating this code to Xamarin was fixing the weird compilation issues I was having, I thank community guy fex for giving me the hint to add the [Register] attribute at the top to the class definition and inheriting from CoordinatorLayout instead of my initial FloatingAction. No idea if this is a bug, I’ve seen someone already filed it on Bugzilla but still without any reply.

    Is now time to associate out behavior to the FloatinActionButton, I’ll do that using the standard approach to define the fully qualified path to the class inside strings.xml for better refactoring.

    and now it’s just a matter of attach it to the button

    If you use material design in your appls you’ll immediately recognize the now stanrdard elements, the only real new is the layout_behavior attribute applied to the FloatingActionButton that points to our custom behavior.

    There are indeed simpler alternatives like James Montemagno component available here but looks like it is now deprecated and I think that, once you know how to fix the ACW compilation issues, knowing how to use material design behaviors wont hurt.

    Enjoy Smile

    Xamarin Forms: CarouselView in action

    Xamarin Forms are getting better with each new release, version 2.2, actually in preview, includes new interesting addition like Effects and CarouselView.

    CarouselView replaces the now deprecated CarouselPage with a more flexible control that can be embedded in any page and can have any size you want, being curious I wanted to see it in action.

    I created a new Xamarin Forms project and updated all projects NuGet Packages to version (you have to select “Include prerelease” option to have it listed since, at the moment, it hasn’t officially released yet.


    I suddenly added a MainView xaml page to the PCL project and set it as MainPage inside App.cs

    public class App : Application { public App() { // The root page of your application MainPage = new MainView(); } }

    CarouselView inherits from ItemView so it requires a collection of items associated to it’s ItemSource property, I then created an array of Persons and associated to CarouselView with this code

    public partial class MainView : ContentPage { public MainView() { this.InitializeComponent(); Person[] persons = { new Person() { Name = "Corrado", ImageUri = "male.png" }, new Person() { Name = "Giulia", ImageUri = "female.png" } }; this.MyCarouselView.ItemsSource = persons; CarouselView v; } } public class Person { public string Name { get; set; } public string ImageUri { get; set; } }

    MyCarouselView is the CarouselView I previously added to MainView.xaml:

    <ContentPage xmlns="" xmlns:x="" xmlns:testCarouselView="clr-namespace:TestCarouselView;assembly=TestCarouselView" x:Class="TestCarouselView.MainView"> <CarouselView x:Name="MyCarouselView" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" /> </ContentPage>

    Great, but we’re missing something: The ItemTemplate. but since I want to use a different template for each page I decided to use another recent addition to Xamarin Forms: the DataTemplateSelector, so I created this class that inherits from abstract DataTemplateSelector.

    public class CarouselTemplateSelector : DataTemplateSelector { public DataTemplate MaleTemplate { get; set; } public DataTemplate FemaleTemplate { get; set; } protected override DataTemplate OnSelectTemplate(object item, BindableObject container) { Person person = (Person)item; switch (person.ImageUri) { case "male.png": return MaleTemplate; case "female.png": return FemaleTemplate; default: throw new ArgumentOutOfRangeException(); } } }

    So simple that don’t think it requires a detailed explanation, it just returns proper DataTemplate depending on the name of ImageUri, ok, not very professional but this is just a demo right? Smile

    I generally like to have TemplateSelectors instantiated via xaml together with their associated template definition in one place, so I added them to MainView xaml resources, here’s complete markup:

    <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="" xmlns:x="" xmlns:testCarouselView="clr-namespace:TestCarouselView;assembly=TestCarouselView" x:Class="TestCarouselView.MainView"> <ContentPage.Resources> <ResourceDictionary> <!--Female template--> <DataTemplate x:Key="FeMaleTemplate"> <StackLayout BackgroundColor="Pink" Orientation="Horizontal"> <Image Source="{Binding ImageUri}" VerticalOptions="Center" Margin="50,0,0,0" WidthRequest="100" HeightRequest="200" /> <Label VerticalOptions="Center" Margin="60,0,0,0" Text="{Binding Name}" TextColor="Black" FontSize="30" /> </StackLayout> </DataTemplate> <!--Male template--> <DataTemplate x:Key="MaleTemplate"> <Grid BackgroundColor="Aqua"> <Image Source="{Binding ImageUri}" VerticalOptions="Start" Margin="00,50,0,0" WidthRequest="100" HeightRequest="200" /> <Label VerticalOptions="Center" HorizontalOptions="Center" Margin="0,500,0,0" Text="{Binding Name}" TextColor="Black" FontSize="30" /> </Grid> </DataTemplate> <!--Template selector--> <testCarouselView:CarouselTemplateSelector x:Key="CarouselTemplateSelector" MaleTemplate="{StaticResource MaleTemplate}" FemaleTemplate="{StaticResource FeMaleTemplate}" /> </ResourceDictionary> </ContentPage.Resources> <!--Carousel View--> <CarouselView PositionSelected="OnPositionSelected" x:Name="MyCarouselView" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" ItemTemplate="{StaticResource CarouselTemplateSelector}" /> </ContentPage>

    From the xaml you’ll immediately recognize the two (simple) DataTemplates, the custom DataTemplateSelector , how it gets associated to CarouselView ItemTemplate but if you look closely you’ll also recognize a nice addition to Forms v2.2: Margin property!

    Yes we can now stop using nested views with Padding to fine tune control position inside a Page, well done Xamarin!

    If you want to be informed when the position of CarouselView changes just subscribe PositionChanged event, in my case I mapped it to this method:

    private void OnPositionSelected(object sender, SelectedPositionChangedEventArgs e) { Debug.WriteLine(e.SelectedPosition.ToString()); }

    We can now run the sample code and we’ll get this outputs (Android/iOS)

    Android       ios

    CarouselView is a great new entry, in special case if you want to create applications based on sliding views (quite common today) there’s just one feature I miss: Orientation, at the moment looks like you can only slide horizontally, hope Xamarin will consider it for final release.

    Using Xamarin Forms Effects

    Version 2.1 of Xamarin Forms introduced Effects, a nice alternative to custom renderers when all you need is to tweak some properties of the platform native control, they should be seen as an alternative to a custom renderer not as a substitute.

    Let’s quickly see how they work, let’s suppose we want to limit the amount of text that a user can type inside an entry, something that’s not natively possible with Xamarin Forms (at the time of this writing…)

    Create a new Xamarin Forms project and upgrade Xamarin.Forms assemblies to latest stable version greater than 2.1 , in my case is


    Effects are a mix of platform specific code and code that resides in application PCL library, let’s start with the PCL and create a class that uses RoutingEffect  as base class:

    public class MyEntryEffect : RoutingEffect { public MyEntryEffect() : base("MyCompanyName.EntryEffect") { } public int MaxLength { get; set; } }

    As you can see the constructor of this class invokes base constructor passing the fully qualified name of the platform specific effect to be created (“MyCompanyName.EntryEffect” more details on this soon)

    It’s time to apply our Effect (or as I prefer ‘extension’) to a Xamain Forms Entry, in my project I’ve added a MainView.xaml page and this is related XAML.

    <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="" xmlns:x="" xmlns:demoEffects2="clr-namespace:DemoEffects2;assembly=DemoEffects2" x:Class="DemoEffects2.MainView"> <StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"> <Entry Placeholder="Try to type more than 5 chars.." > <Entry.Effects> <demoEffects2:MyEntryEffect MaxLength="5" /> </Entry.Effects> </Entry> </StackLayout> </ContentPage>

    Quite easy to understand: We added our custom MyEntryEffect effect to Entry’s Effects collection and set it’s MaxLength property to 5.

    Is now time to switch to platform specific projects and implement the code that reads the value of MaxLength property and applies this limit to platform specific control.

    Let’s start with Android:

    [assembly: ResolutionGroupName("MyCompanyName")] //Note: only one in a project please... [assembly: ExportEffect(typeof(EntryEffect), "EntryEffect")] namespace DemoEffects2.Droid { public class EntryEffect : PlatformEffect { protected override void OnAttached() { try { //We get the effect matching required type, we might have more than one defined on the same entry var pclEffect = (DemoEffects2.MyEntryEffect)this.Element.Effects.FirstOrDefault(e => e is DemoEffects2.MyEntryEffect); TextView editEntry = this.Control as TextView; editEntry?.SetFilters(new Android.Text.IInputFilter[] { new Android.Text.InputFilterLengthFilter(pclEffect.MaxLength) }); } catch (Exception ex) { //Catch any exception } } protected override void OnDetached() { } protected override void OnElementPropertyChanged(PropertyChangedEventArgs args) { base.OnElementPropertyChanged(args); try { if (args.PropertyName == "Your property name") { //Update control here... } } catch (Exception ex) { Console.WriteLine("Cannot set property on attached control. Error: ", ex.Message); } } } }

    Inside the Android project I have created an EntryEffect class that inherits from PlatformEffect and implemented two familiar overrides: OnAttached and OnDetached.

    As you might expect the first is invoked when Effect is applied to the control and can be used to initialize the property of Android’s native control while OnDetached is called when the effect is removed and can be used to perform any cleanup. 

    From inside this methods we have access to three fundamental properties:

    Container: The platform specific control used to implement the layout.

        • Control: The platform specific counterpart of Xamarin Forms control.

    Element: The Xamarin Forms control being rendered.

    Since Effect can be added to Effects collection of any control the code must take this into consideration and degrade gracefully in case actions cannot be completed due to a control type mismatch.

    Inside OnAttached we retrieve the PCL effect so that we can read it’s MaxLenght property and we cast the Control property to a TextView, if casting fails we simply do nothing otherwise we add a filter that limits the number of typed chars inside the TextView.

    Even if not used in this sample, the code includes OnElementPropertyChanged override that can be used when you want to be notified when a property of the control changes (e.g. IsFocused) and do something when this happens.

    Last, but absolutely not least come the two attributes ResolutionGroupName and ExportEffect

    ResolutionGroupName : Allows you to define a custom namespace for you effects to prevent naming collision, it must be used once in the platform specific project.

    ExportEffect: Is the name that’s used by initial effects discovery process and it accepts the type of the effect it is applied to and the name you want to export for discovery.

    The concatenation of ResolutionGroupName and ExportEffect id is used by RoutingEffect class (see it’s base constructor in preceding code) for proper identification.

    As for custom renderers is not necessary to implement the effect for each class, if undefined it simply gets ignored.

    Here’s the iOS effect version:

    [assembly: ResolutionGroupName("MyCompanyName")] //Note: only one in a project please... [assembly: ExportEffect(typeof(EntryEffect), "EntryEffect")] namespace DemoEffects2.iOS { public class EntryEffect : PlatformEffect { protected override void OnAttached() { try { //We get the effect matching required type, we might have more than one defined on the same entry var pclEffect = (DemoEffects2.MyEntryEffect)this.Element.Effects.FirstOrDefault(e => e is DemoEffects2.MyEntryEffect); UITextField editEntry = this.Control as UITextField; if (editEntry != null) { editEntry.ShouldChangeCharacters = (UITextField textField, NSRange range, string replacementString) => { // Calculate new length var length = textField.Text.Length - range.Length + replacementString.Length; return length <= pclEffect.MaxLength; }; } } catch (Exception ex) { //Catch any exception } } protected override void OnDetached() { } } }

    Simpler, but more flexible, Xamain Forms effects represent a valid alternative to Renderers, I’m pretty sure that we’ll see many open source effects coming from th Xamarin community.

    If you want to know more about Effects, this is the link to follow.

    Happy Effecting.

    Add a SnackBar to you Xamarin.Android app

    Material design introduced a new lightweight way to provide feedback to a user, something that sits between the AlertDialog and Toast alternatiives with a funny name: SnackBar.
    A Snackbar appears at the bottom of the view and can optionally display an additional custom button.

    Here are the basic steps to show a SnackBar:

    -Open Visual Studio and create a new blank Android app

    -Using Nuget add the Xamarin.Android.Support.Design library, this will let you target Android releases older than v21


    • -Using the code generated by the template, lets make the SnackBar appear when the default button is pressed.

    -Add this code inside MainActivity’s OnCreate method

    protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button>(Resource.Id.MyButton); button.Click += (s, e) => { //Creates the Snackbar Snackbar snackBar = Snackbar.Make(button, "Text", Snackbar.LengthIndefinite); //Show the snackbar snackBar.Show(); }; } }

    • -Compile the project and wait until build succeeds, be patient if operation takes more than than usual since this delay is due to the fact that the missing packages are downloading and their size is quite huge. If you stop compilation download will fail and you’ll start having a lot of “…invalid zip” error. in this case delete the zip folder mentioned on error message and try again.
    • -You’ll now see this error message:
    • image
    • -Let’s fix it adding the required theme (you can create your own deriving from Theme.AppCompat of course)
      [Activity(Label = "TestSnackBar2", MainLauncher = true, Icon = "@drawable/icon", Theme = "@style/Theme.AppCompat")]

    • -Run the project again and you’ll see this bar appear at the bottom of the view
    • image
    • -Quite sad indeed, luckily the SnackBar can be customized, so let’s add more code:
    button.Click += (s, e) => { //Creates the Snackbar and subscribes the button press event Snackbar snackBar = Snackbar.Make(button, "Text", Snackbar.LengthIndefinite).SetAction("Ok", (v) => { Console.WriteLine("Done"); }); //set action button text color snackBar.SetActionTextColor(Android.Graphics.Color.Green); //Set action button text size TextView txtAction = snackBar.View.FindViewById<TextView>(Resource.Id.snackbar_action); txtAction.SetTextSize(Android.Util.ComplexUnitType.Dip, 18); //Set message text size and color TextView txtMessage = snackBar.View.FindViewById<TextView>(Resource.Id.snackbar_text); txtMessage.SetTextColor(Android.Graphics.Color.Red); txtMessage.SetTextSize(Android.Util.ComplexUnitType.Dip, 12); //Show the snackbar snackBar.Show(); };

    • -And there you go, a custom SnackBar Smile
    • image

    If you’re wondering why you need to pass a reference to a view (Button in our case) as SnackBar first parameter is because internally it walks up the visual tree so that can properly position itself at bottom position.


    « Newer PostsOlder Posts »