Uwp - James Montemagno https://staging.montemagno.com/tag/uwp/ https://staging.montemagno.com/content/images/2017/08/MonogramIcon_Orange_NoBuffer.png Uwp - James Montemagno https://staging.montemagno.com/tag/uwp/ Hugo -- gohugo.io Tue, 13 Oct 2026 23:21:57 GMT 60 Code Generation from XAML in Visual Studio is Mind-blowing Awesome https://staging.montemagno.com/code-generation-from-xaml-in-visual-studio/ 605f72ee20df30003b2b3b83 Sat, 27 Mar 2021 18:57:22 GMT

The more and IDE or code editor can do for you the better I say. Visual Studio has been crushing it with new refactorings, IntelliSense, and IntelliCode, one of my favorite features ever. One thing that I have always been hoping for as a XAML developer is deeper connectivity between the XAML and the View-Model. We have seen increased IntelliSense in this area, but with the release of Visual Studio 2019 v16.9 comes code generation from XAML! That is right, you can now have Visual Studio automatically create your properties, commands, and more!

I will walk through this awesome feature for Xamarin.Forms, WPF, and UWP, but if you just want to see it in action, I made an entire video:

Enabling Code Generation

The first thing to do is to create your ViewModel and implement INotifyPropertyChanged (or inherit from something that does). Then just create a control with a Binding associated with it. For example:

<StackLayout>
    <Label Text="{Binding Text}"/>
</StackLayout>

Once you do this, Visual Studio will put little dots under the Text binding and a lightbulb will show up (if you don't see this simply re-compile). The lightbulb will look to assign your x:DataType in Xamarin.Forms or d:DataContext in WPF/UWP.

Lightbulb in Visual studio to set x:DataType

When I selected this option, it auto added the following code:

xmlns:app1="clr-namespace:App1"
x:DataType="app1:MyViewModel"

What is x:DataType you may be asking? Well, it is a compiled binding, which makes your bindings and apps faster! This is an awesome feature of Xamarin.Forms that you should totally use!

With this code in place, you will now see the dots remain and a new lightbulb show up to create a property called Text for you!

Lightbulb and code preview to generate text

Here, it is recommending adding the property and creating a SetProperty method to invoke PropertyChanged, which is AWESOME!!!! Now, at this point you probably want to refactor the code a little bit and create  BaseViewModel that you put this method in and then in future ViewModels it will not attempt to create the code and just add the property. If you are using Mvvm Helpers, you can use this code as your base:

public class ViewModelBase : BaseViewModel
{
	public bool SetProperty<T>(ref T field, T newValue, [CallerMemberName] string propertyName = null) =>
		SetProperty<T>(ref field, newValue, propertyName, null, null);
}

Now, if you add another control with another binding, you will see nice tight code will be generated for you:

Another property being added with only a get/set

Is your mind blown yet?!?!? Mine is! However, it gets even better!

Generating Commands!

Now, let's say we are going to add a Command to a Button we would naturally want that code to be generated as well, correct? Well, you are in luck because it will!

Command and method being created!

This code is really neat because it not only created the command and the method, but it also brought in the correct namespace to use the Xamarin.Forms Command!

Command Generation on UWP/WPF

If you are over on UWP or WPF you will not see this code generation because the core framework does not have an implementation of ICommand. However, if you are using a framework or library such as Mvvm Helpers then it will be smart enough to figure it out and recommend code for you!

Code for a command being generated with Mvvm Helpers

MIND BLOWN!!!! ARE YOU NOT IMPRESSED!?!?!? Amazing!

Cleaner Code with C# 8 & 9!

One of the things you may have noticed is that the code for Xamarin.Forms and WPF/UWP are different in the screenshots. That is because my WPF sample app is using .NET 5, which uses C# 9 by default. The Xamrin.Forms app is using .NET Standard 2.0, which defaults to C# 7. However, you can easily adjust what version of C# is used in your project by adding the LangVersion into your csproj.

<LangVersion>8.0</LangVersion>

Take a look at my previous blog about upgraded a project to C# 9 in a minute.

Once you upgrade to 8.0 or higher the old code:

private ICommand clickCommand;

public ICommand ClickCommand
{
	get
	{
		if (clickCommand == null)
		{
			clickCommand = new Command(Click);
		}

		return clickCommand;
	}
}

private void Click()
{
}

will be upgraded to this lovely clean tight code:

private ICommand clickCommand;
public ICommand ClickCommand => clickCommand ??= new Command(Click);

private void Click()
{
}

Code Generation for Models

So far we have had Visual Studio generate code in our ViewModel classes on our page, but what about our models that are bound to an ItemsSource in a ListView or CollectionView Well no worries, all you need to do is set your x:DataType on your DataTemplate:

<ListView ItemsSource="{Binding Items}">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="app1:Item">
            <ViewCell>
                <Label Text="{Binding Text}"/>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Then you will see lightbulbs on any control inside of the DataTemplate!!

Code being generated inside of the data model

Again, this is pretty mind blowing and amazing! I was able to create all of my ViewModels and Models all without leaving the XAML!

Just the start!

This is all from me just playing around with Visual Studio 2019 v16.9 for a few minutes exploring this awesome new feature. There is for sure much more to come as Marco from the XAML Tooling team tweeted about the new feature and discussed with commentors about extending the templates for code that is being generated. Also, as of right now this is just a feature on Visual Studio on Windows, but since Visual Studio for Mac uses pretty much the same engine, we can imagine it will make its way to VSM soon.

This is just one of the many features that was included in Visual Studio 2019 v16.9 so check the release notes and upgrade today!

]]>
Opt-out of Dark Mode on iOS, Android, UWP, and macOS https://staging.montemagno.com/opt-out-of-dark-mode-on-ios-android-uwp-and-macos/ 5da372290980fc00385d9b78 Mon, 14 Oct 2019 19:17:00 GMT Everyone can't stop talking about dark mode now that iOS 13 and Android 10 are officially released. To my surprise I have actually really been enjoying dark mode on my desktop and mobile devices. I really want to go through all my apps and add proper dark mode support, however I just haven't had the time. When running apps on iOS 13 or macOS and flipping on dark mode can make your app look.... not so great:

iOS app in dark mode with a white New Item page and black Text and Description fields that are hard to read

This can depend on the framework you are using, hard coded values, or a bunch of other things. You may be in this situation or perhaps you have a completely custom theme and you don't want the operating system to touch it. Well, you are in luck because you can opt-out!

iOS

You have two options here. The easiest is to update your Info.plist and add a new entry named UIUserInterfaceStyle. You can manually set this to Light or Dark to apply a theme to your entire app.

<key>UIUserInterfaceStyle</key>
<string>Light</string>

If your app is basically ready to go and just a few screens require a specific mode you can set the OverrideUserInterfaceStyle propety. This can be done on any UIView, UIViewController, or UIWindow.

public override void ViewDidLoad()
{
    base.ViewDidLoad();
    if (UIDevice.CurrentDevice.CheckSystemVersion(13, 0))
        OverrideUserInterfaceStyle = UIUserInterfaceStyle.Light;
}

macOS

Similar to iOS you can add a very special key to your Info.plist called NSRequiresAquaSystemAppearance and set it to true:

<key>NSRequiresAquaSystemAppearance</key>
<true/>

Android

Android is actually really easy as you have to opt-in for the dark mode to apply to your application. Traditionally, you have always set a light or dark mode for your app in your app's styles. Every Xamarin app defaults to a light theme:

<style name="MainTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">

You have to opt in by setting the theme to DayNight:

<style name="MainTheme.Base" parent="Theme.AppCompat.DayNight.DarkActionBar">

This also works if you are using MaterialComponents theming:

<style name="MainTheme.Base" parent="Theme.MaterialComponents.DayNight">

UWP

UWP is also similar to Android as you have to opt-in for the system wide defaults. Traditionally in your App.xaml file you would set a requested theme:

<Application
    RequestedTheme="Light">

</Application>

This means your app will always use light theme no matter what. To opt-in you will need to remove this property completely.

Checking Requested Theme

It is actually pretty simple to check theme of the app. It has been blogged abotu a lot, and I have even submitted a pull request to Xamarin.Essentials that hightlights it, so take a look. There are also great docs for iOS, Android, and UWP to help guide you.

]]>
Unique Device & App Installation Identifiers for Mobile Apps https://staging.montemagno.com/unique-device-id-for-mobile-apps/ 5c0ec14158056200bf4c259f Fri, 14 Dec 2018 20:00:00 GMT One common query I get all the time from developers is how to get a unique device or application identifier for their mobile app. After deciding to not include an API for this in Xamarin.Essentials we heard a lot of different use cases for it including:

  • Client/Server Communication
  • Login Validation
  • In-App Purchase Verification
  • Licensing Purposes

The next obvious question that you may have is why didn't we include it in Xamarin.Essentials if everyone seemed to want it? The answer is actually pretty straight forward: There is truly no consistent API across every platform to deliver an identifier that is unique to the device or application. On top of that developers all wanted to use the API a bit differently and in some cases make it a core part of processing transactions and that is something we don't want to get in the middle of.

So what can you do if you need this identifier? I would first stop and ask yourself if you can use some sort of User Identifier based on login information as this will ensure uniqueness that you control. If not then there are a few options to go down then trying to implement this.

Platform APIs Available

Each platform offers up something a bit different:

iOS: IdentifierForDevice

This API is pretty interesting as it will give you an alphanumeric string that uniquely identifies a device to the app's vendor. Based on your Bundle ID that you set Apple will return back the same identifier. The issue that I always found is that this can be spoofed by someone else setting a similar Bundle ID, but it is in general a decent API:

public string Id => UIDevice.CurrentDevice.IdentifierForVendor.AsString();

Android: Serial, getSerial & AndroidId

What a mess Android is as there are now three APIs that do similar things and even Google's documentation is all over the place on which to use!

A recommended route would be to attempt to grab the Serial number when available. In the world of Xamarin we will automatically figure out whether to use the static property or the new getSerial() method introduced in Android 9.0 (which requires the READ_PHONE_STATE). The issue here is that this can be modified via rooted devices and sometimes is not available on all hardware. This means that you need to attempt to figure out something else to use, which would be the ANDROID_ID. This is a unique number that is randomly generated when the device is setup, unless you are on API 26+ which is a number that is unique for each combination of app-signing key, user, and device.... As you can see now we have like 4 different identifiers here that all mean different things. If you went this route then your code would look like this:

string id = string.Empty;
public string Id
{
    get
    {
        if (!string.IsNullOrWhiteSpace(id))
            return id;

        id = Android.OS.Build.Serial;
        if(string.IsNullOrWhiteSpace(id) || id == Build.Unknown || id == "0")
        {
            try
            {
                var context = Android.App.Application.Context;
                id = Secure.GetString(context.ContentResolver, Secure.AndroidId);
            }
            catch(Exception ex)
            {
                Android.Util.Log.Warn("DeviceInfo", "Unable to get id: " + ex.ToString());
            }
        }

        return id;
    }
}

Before going down this route think about the implications here of your code and what you are trying to accomplish.

UWP: GetPackageSpecificToken or GetSystemIdForPublisher

We are in a tricky place for UWP as well depending on what we are trying to do. GetSystemIdForPublisher is very similar to what iOS does, but it may not be available in all versions of Windows. The next level is trying to grab a unique hardware identifier for the specific app with GetPackageSpecificToken. So in this case your code may look like:

string id = null;
public string Id
{
    get
    {

        if (id != null)
            return id;

        try
        {
            if (ApiInformation.IsTypePresent("Windows.System.Profile.SystemIdentification"))
            {
                var systemId = SystemIdentification.GetSystemIdForPublisher();

                // Make sure this device can generate the IDs
                if (systemId.Source != SystemIdentificationSource.None)
                {
                    // The Id property has a buffer with the unique ID
                    var hardwareId = systemId.Id;
                    var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId);

                    var bytes = new byte[hardwareId.Length];
                    dataReader.ReadBytes(bytes);

                    id = Convert.ToBase64String(bytes);
                }
            }

            if (id == null && ApiInformation.IsTypePresent("Windows.System.Profile.HardwareIdentification"))
            {
                var token = HardwareIdentification.GetPackageSpecificToken(null);
                var hardwareId = token.Id;
                var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId);

                var bytes = new byte[hardwareId.Length];
                dataReader.ReadBytes(bytes);

                id = Convert.ToBase64String(bytes);
            }

            if(id == null)
            {
                id = "unsupported";
            }

        }
        catch (Exception)
        {
            id = "unsupported";
        }

        return id;
    }
}

Just like Android you may get different results based on what you are looking for.

A True Cross-Platform Identifier

Now that we have seen each of the platforms and how inconsistent they are, let's talk about a better way of doing this. What most developers are attempting to do is ensure that when an application is installed they can get some unique identifier for that installation. If the app is transfered to a new phone then the identifier is the same, but if it is un-installed then a new identifier is generated. This can easily be accomplished by using Xamarin.Essentials Preferences API to save a Guid when your app starts if it doesn't exist yet. The code is super simple:

var id = Preferences.Get("my_id", string.Empty);
if(string.IsNullOrWhitespace(id))
{
   id = System.Guid.NewGuid().ToString();
   Preferences.Set("my_id", id);
}

This will ensure a unique identifier for the installed application and it is actually the same mechanism that App Center uses for their SDK across each platform! You should of course be aware that this Guid will sync across the user in some instances based on their device and account setup, which is probably what you want to have happen.

There you have it a full break down of each platform with the complexity that each offer. However, my recommendation remains that you should just generate a Guid and go from there :)

]]>
Xamarin Evolve 2016 App Development Retrospective https://staging.montemagno.com/xamarin-evolve-2016-app-development-retrospective/ 598df8f2c121b60019bf2ff2 Fri, 29 Apr 2016 21:23:06 GMT Just yesterday we made the Evolve 2016 conference app completely open source on GitHub, and feedback has been fantastic with 57 stars, 26 forks, and tons of buzz on Twitter. While you are probably already digging through the code I wanted to take a moment to reflect on the development of the mobile application and some fun statistics of the application when it finally went live.

Development

The Xamarin Evolve conference application is packed full of everything you need for a mobile conference including:

  • Session & Speaker details
  • Latest announcements and social feed
  • Ability to hand curate your favorite sessions
  • Push Notifications
  • Floor & Venue Maps
  • Wi-Fi configuration
  • Tons of other awesome stuff

From the start it was clear that Xamarin.Forms was perfect for the app being able to present loads of data while still integrating with native features. Each platform was spiced up with platform specific colors, styles, paddings, and navigation, which was all crafted in shared code. This lead to a beautifully crafted application (sketched & designed by the amazing Antonio from the Xamarin design team) that I implemented on all platforms that looked and felt native… because it is native!

What you may not have known is that the entire application was built by just two people. Pierce Boggan, our amazing engineer on the evangeist team, wrote the backend, and I buit the entire front end! What is really awesome is that it only took us about 5 week total to build it out.

The Backend

We chose Azure App Service’s Mobile Apps as our backend service. Being familure with C# and .NET enable Pierce and I were able to get a backend for the app up and running in under a day. More importantly this enabled us to implement a custom authentication so attendees could log in with their Xamarin account, online/offline data syncronization, push notifications with Azure Notification Hub, and a flurry of other awesome features. The entire backend source code can be found on that Github link.

What really impressed us was how fast and resilent the backed was (not to mention a superb value as we were blown away at how low the total cost was.). The mobile app has only been out for 2 weeks and it has handled the traffic spectacularly. I was surprised how chatty I made the backend becasue in those 2 weeks there were nearly 1 MILLION requests processed!

What I love about this graph is the peaks and valleys of network traffic and the workload of the server, which all had auto scale turned on. As we can see 1 MILLION network calls and ALL of the rest of the services including push notifications, SQL Server, and more only cost a little over $30!

Shared Code

Everyone loves sharing code across platforms and all of libraries we included helped drive the app sharing anywhere from 90% all the way up to 99% of code on Windows Mobile and Desktop! We came up with a pretty great architecture of abstracting our business logic from our presentation layer, but also abstracted all of our code data models that were shared across our mobile apps and our Azure backend.

Components and Plugins

The conference could not have been completed with out Xamarin Components and Plugins, many of which are now open source. We immediatelly installed tons of awesome plugins, but also integrated some great .NET libraries such as Humanizr and NodaTime.

Testing

I can’t take credit for this one as our amazing automotion expert Ethan Dennis wrote an amazing suite of Test Cloud tests to enusre the app was regression free throughout development.

Continous Integration & Deployment

For me, 2016 is the year of CI and CD. I ahve been talking about it for a while now during sessions, live coding, and I am sure to have told you if you saw me at Evovle. I LOVE CI and CD! I can’t help myself. The tools are just so good now.

With EVERY single push of code to GitHub the Evolve conference app was automatically compiled, packaged, shipped to Test Cloud, and then deployed to HockeyApp. This enabled me to deliver the application for testing to 350+ Xamarins within 20 minutes of pushing code. What is really cool is that I even setup feature branches that had special builds for test cloud testing, and regression runs each night.

This was done for Windows with Visual Studio Team Services, and then I leveraged one of my favorite services Bitrise for all of my iOS and Android builds:

Fun with Numbers

Development is fun, but once the app is out someone is sure to ask you to analyze numbers and data from the mobile applications. This is where Power BI, a technology I knew nothing about, comes in and enabled me to analyze favorite sessions and feedback within a few minutes. I wrote a few SQL views and pointed Power BI and my Azure SQL database and BOOM done! Charts and graphs that every manager is sure to love. Checking out the numbers we had over 11,570 sessions favorited inside of the application.

I then took it a step further and analyzed in real time all of the session feedback from attendees, which I thought was pretty awesome.

Retrospective

Before posting this I was asked on Twitter what I would change in the app if I could go back in time. This is a great question and I spent some time thinking about what went right with the app and what could be improved and here is my short list:

What went right:

  • Xamarin.Forms: This was absolutely the right call for the UI and it looks beautiful
  • Different navigation for each platform: Took a bit more time to hand curate and implement, but worth it<
  • CI/CD: This saved my behind so many times I can’t even tell you. There is nothing like clicking commit and 20 minute later shipping an app update.

What went wrong:

  • I love Xamarin.Forms Dependency Service… but I think for testability I shoud have decoupled it and used a custom implementation or Unity for the container.
  • Unit Tests: If you know me I have a rough relationship with unit testing in mobile apps. I know I should do it, but my apps never have much. Right before Evolve started I found a very strange Time Zone issue that forced me to have to push out new versions of the app in a hurry. (This was all due because I sat next to my mancrush Greg Shackles)
  • .NET Native for UWP: Not really a development problem, but this caused TONS of problems since I didnt’ fully understand what it was doing and removing. Now that I know what it is trying to do and how to make it work nicely with Xamarin.Forms it wont be an issue.
  • Background Refresh… WHY WONT IT WORK IN RELEASE?!?!? As it does in debug.

What’s next?

With Evolve 2016 now coming to a close you can get your hands on the source code, but also leave feedback and create issues on the GitHub page. I can’t wait to see what you build with this awesome open source app!

]]>