Adding WPF Client with Azure Active Directory Authentication and Azure Mobile Service

In today’s post I was going to cover adding Azure AD authentication to my iOS project but I don’t have my Mac build machine handy so there’s a bit of a change of plans. Today I’m going to add a WPF desktop application to my solution and catch it up to where the other client applications are up to. I’ll start by creating the WPF Application.

image

At this point I realised that I missed setting the framework in the Add New Project dialog, so I opened the Properties pane of the application and on the Application tab I set the Target framework to .Net Framework 4.5.

image

Next we need to add references to the following solution projects:

– RealEstateInspector.Core

– RealEstateInspector.Shared.Client

And then add reference to both the ADAL and Mobile Service SqliteStore packages. From the downloads page on sqlite.org you’ll also need to download the “32-bit DLL (x86) for SQLite” which is under the Precompiled Binaries for Windows heading. Unblock and Extract the zip file and add the sqlite3.dll file to the new WPF project, setting the Build Action to Content and setting the Copy to Output Directory to Copy always.

I also need to check the Prefer 32-bit checkbox and define the DESKTOP compilation symbol for All Configurations.

image

I’ll add the following XAML markup to the MainWindow.xaml

<Window x_Class=”RealEstateInspector.Desktop.MainWindow”
        “>
        “>
        Title=”MainWindow” Height=”350″ Width=”525″>
    <Grid>
        <Grid.Resources>
            <DataTemplate
                x_Key=”PropertyItemTemplate”>
                <TextBlock
                    Text=”{Binding Address}”
                    FontSize=”30″
                    Foreground=”WhiteSmoke” />
            </DataTemplate>
        </Grid.Resources>
        <Grid.RowDefinitions>
            <RowDefinition
                Height=”Auto” />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Button
            Content=”Authenticate”
            Click=”AuthenticateClick” />
        <ListView
            ItemTemplate=”{StaticResource PropertyItemTemplate}”
            Grid.Row=”1″
            ItemsSource=”{Binding Properties}” />
    </Grid>
</Window>

And the following code to the MainWindow.xaml.cs

public partial class MainWindow : IWin32Window
{
    public IntPtr Handle
    {
        get
        {
            var interopHelper = new WindowInteropHelper(this);
            return interopHelper.Handle;
        }
    }
    public MainWindow()
    {
        InitializeComponent();

        Loaded += MainWindow_Loaded;
    }
    public MainViewModel CurrentViewModel
    {
        get { return DataContext as MainViewModel; }
    }
    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        var vm = new MainViewModel();
        DataContext = vm;
    }

    private async void AuthenticateClick(object sender, RoutedEventArgs e)
    {
        var token = await AuthenticationHelper.Authenticate(Handle);
        await CurrentViewModel.LoadPropertyData(token);
    }
}

I also had to make some minor changes to the AuthenticationHelper

public static class AuthenticationHelper
{

    public static async Task<string> Authenticate(
#if DROID
    Android.App.Activity callerActivity
#elif DESKTOP
IntPtr callerHandle
#endif
        )
    {
        try
        {
            var authContext = new AuthenticationContext(Constants.ADAuthority);
#if !SILVERLIGHT
            if (authContext.TokenCache.ReadItems().Count() > 0)
                authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
#endif
            var authResult =
                await
                    authContext.AcquireTokenAsync(Constants.MobileServiceAppIdUri,
                    Constants.ADNativeClientApplicationClientId,
                    new Uri(Constants.ADRedirectUri),
#if WINDOWS_PHONE_APP || SILVERLIGHT
                    new AuthorizationParameters()
#elif DROID
                    new AuthorizationParameters(callerActivity)
#elif DESKTOP
                        new AuthorizationParameters(PromptBehavior.Auto, callerHandle)
#else
                        new AuthorizationParameters(PromptBehavior.Auto, false)
#endif
                    );
            Debug.WriteLine(authResult != null);

            return authResult.AccessToken;

        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            return null;
        }
    }
}

And that’s it, the WPF desktop application can be run up, the user can sign in and properties are synchronized before being displayed.

Leave a comment