Tuesday, August 13, 2013

Microsoft Dynamics AX 2012 Apps using Windows Azure Mobile Services

Microsoft Dynamics AX 2012 Apps using Windows Azure Mobile Services
 
Purpose: The purpose of this document is to explain how to develop Microsoft Dynamics AX 2012 Apps using Windows Azure Mobile Services.
 
Challenge: Mobility is one the most important trends nowadays. With the help of Microsoft Dynamics AX Connector for Mobile Apps you can develop mobile client apps to communicate with Microsoft Dynamics AX 2012 from phone or tablet platforms. In this walkthrough we’ll discover a creative way to accelerate development of mobile apps for Microsoft Dynamics AX 2012 using a power of Windows Azure Mobile Services.
 
Solution: Mobile Services allows you to accelerate your mobile app development by providing a turnkey way to structure storage, authenticate users, and send push notifications. With SDKs for Windows, Android, iOS, and HTML as well as a powerful and flexible REST API, Mobile Services lets you to build connected applications for any platform and deliver a consistent experience across devices. Please find more information about Windows Azure Mobile Services here: http://www.windowsazure.com/en-us/services/mobile-services.
 
Scenario
 
In this scenario I want to develop Windows Azure Mobile Service which will be integrated with Microsoft Dynamics AX 2012 by means of Windows Azure Service Bus to track issues that are raised by your employees (internal, sales related, service related, etc.). From the functional perspective these issues/cases tracked by Windows Azure Mobile Service will have to be sent to Microsoft Dynamics AX 2012 for processing and resolution (Case management in Microsoft Dynamics AX 2012).
 
Walkthrough
 
For the purposes of this walkthrough I created Windows Azure Mobile Service for Case management.
 
I assume that you already have Windows Azure Subscription account to complete this walkthrough. In case you don’t you may want to sign up for the free trial here: http://www.windowsazure.com/en-us/pricing/free-trial
 
Now let’s review the process step-by-step!
 
Mobile services
 
 
Currently I don’t have any Mobile service, so I’m going to create one for Case management
 
New Mobile service (1)
 
 
Here I’ll specify a name and the fact that I’ll be using SQL database to store case data in the Cloud
 
New Mobile service (2)
 
 
Here I’ll specify database settings which include name of the database and login credentials
 
Mobile services
 
 
My Windows Azure Mobile Service for Case management has been created. The creation process takes only couple of minutes and your Mobile Services is up and running
 
This mobile service is up and running
 
 
Mobile service (Case management)
 
 
Once my Mobile Service has been created I can now focus on defining a database structure to support cases tracking and also creating a client application using programming language I prefer (C# in my case)
 
Get started
 
 
Get started page allows you to download a sample app which is already pre-configured to work with your mobile service
 
Download
 
 
You can download this sample app as zip archive
 
But before we write a client application we’ll first define the structure of the database to allow us to track cases
 
SQL database (casemanagement_db)
 
 
Please note that casemanagement_db database has been already created as a part of Mobile Service creation
 
Mobile service (casemanagement) - Data
 
 
Currently I don’t have any tables related to casemanagement Mobile Service, so I’m going to create table called “case” to track cases
 
Create new table
 
 
Here I’ll specify table name and appropriate permissions
 
Mobile service (casemanagement) - Data
 
 
Now once I have created a new table “case” I can define necessary columns in order to store case data by switching to the database design experience (Manage). SQL Database Management URL schematically will look like (this URL is not real): https://database.windows.net/?langid=en-us#$database=casemanagement_db
 
SQL Database Management
 
 
SQL Database Management Portal
 
 
In SQL Database Management Portal I’ll switch to Design mode to define the structure of “case” table
 
SQL Database Management Portal - Design
 
 
SQL Database Management Portal - Design
 
 
In “case” table ID field was created automatically and I created one more field called “Description”
Now if I get back to Windows Azure Portal I’ll see the reflection of changes I made in SQL Database Management Portal on Mobile Service page
 
Mobile service - Columns
 
 
We just finished with the database portion and it’s time to get back to the client application
 
I’ve already downloaded zip archive with sample app, then I’ll unzip it and make appropriate code changes
 
casemanagement Client app
 
 
Solution Explorer
 
 
The structure of sample C#.NET project is depicted in Solution Explorer
 
This app is already preconfigured to work with Case management Mobile Service
 
// This MobileServiceClient has been configured to communicate with your Mobile Service's url
        // and application key. You're all set to start working with your Mobile Service!
        public static MobileServiceClient MobileService = new MobileServiceClient(
            "https://casemanagement.azure-mobile.net/",
            ""
        );
 
Please note that Mobile Service Application key is the second parameter in MobileServiceClient class constructor
 
Manage Access Keys
 
 
You can retrieve Mobile Service Application Key from Mobile Service page (Access Keys) in Windows Azure Portal
 
Now we’ll make appropriate changes to the business logic and markup in order to track cases
 
Please see the source code below
 
C# (Business Logic)
 
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
 
namespace casemanagement
{
    public class Case
    {
        public int Id { get; set; }
 
        [JsonProperty(PropertyName = "description")]
        public string Description { get; set; }       
    }
 
    public sealed partial class MainPage : Page
    {
        private MobileServiceCollection<Case, Case> caseItems;
        private IMobileServiceTable<Case> caseTable = App.MobileService.GetTable<Case>();
 
        public MainPage()
        {
            this.InitializeComponent();
        }
 
        private async void InsertCase(Case caseItem)
        {
            // This code inserts a new case into the database. When the operation completes
            // and Mobile Services has assigned an Id, the item is added to the CollectionView
            await caseTable.InsertAsync(caseItem);
            caseItems.Add(caseItem);                       
        }
 
        private async void RefreshCases()
        {
            MobileServiceInvalidOperationException exception = null;
            try
            {
                // This code refreshes the entries in the list view by querying the cases table.            
                caseItems = await caseTable.ToCollectionAsync();
            }
            catch (MobileServiceInvalidOperationException e)
            {
                exception = e;
            }
 
            if (exception != null)
            {
                await new MessageDialog(exception.Message, "Error loading cases").ShowAsync();
            }
            else
            {
                ListItems.ItemsSource = caseItems;
            }
        }
 
        private void ButtonRefresh_Click(object sender, RoutedEventArgs e)
        {
            RefreshCases();
        }
 
        private void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
            var caseItem = new Case { Description = DescriptionInput.Text };
            InsertCase(caseItem);
        }       
 
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            RefreshCases();
        }
    }
}
 
XAML (Markup)
 
<Page
    x:Class="casemanagement.MainPage"
    IsTabStop="false"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:casemanagement"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
 
    <Grid Background="White">
 
        <Grid Margin="50,50,10,10">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
 
            <Grid Grid.Row="0" Grid.ColumnSpan="2" Margin="0,0,0,20">
                <StackPanel>
                    <TextBlock Foreground="#0094ff" FontFamily="Segoe UI Light" Margin="0,0,0,6">WINDOWS AZURE MOBILE SERVICES</TextBlock>
                    <TextBlock Foreground="Gray" FontFamily="Segoe UI Light" FontSize="45" >casemanagement</TextBlock>
                </StackPanel>
            </Grid>
 
 
            <Grid Grid.Row="1">
                <StackPanel>
 
                    <local:QuickStartTask Number="1" Title="Insert a case" Description="Enter some description below and click Save to insert a new case into your database" />
 
                    <StackPanel Orientation="Horizontal" Margin="72,0,0,0">
                        <TextBox Name="DescriptionInput" Margin="5" MinWidth="300"></TextBox>
                        <Button Name="ButtonSave" Click="ButtonSave_Click">Save</Button>
                    </StackPanel>
 
                </StackPanel>
            </Grid>
 
            <Grid Grid.Row="1" Grid.Column="1">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <StackPanel>
                    <local:QuickStartTask Number="2" Title="Query and Update Data" Description="Click refresh below to load cases from your database" />
                    <Button Margin="72,0,0,0" Name="ButtonRefresh" Click="ButtonRefresh_Click">Refresh</Button>
                </StackPanel>
 
                <ListView Name="ListItems" Margin="62,10,0,0" Grid.Row="1">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Name="TextBlockDescription" Text="{Binding Description}" Margin="10,0" />
                            </StackPanel>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
 
            </Grid>
 
        </Grid>
    </Grid>
</Page>
 
As the result our client app will look like this
 
Case management Client app
 
 
Case management client app will display the list of cases stored in the database and will allow you to create a new case by providing a description. When I create new case in Case management Client app I can review the data in Windows Azure Portal on Mobile Service page (Browse)
 
Mobile service (case) - Browse
 
 
The next step will be to integrate Case management Mobile Service with Microsoft Dynamics AX 2012. This can be done by means of Windows Azure Service Bus. Please see more details about Developing mobile apps for Microsoft Dynamics AX 2012 here: http://www.microsoft.com/en-us/download/details.aspx?id=38413
 
Service bus
 
 
Currently I don’t have Service bus for integration and I’m going to create one
 
Create a namespace
 
 
  
Here I’ll specify namespace name and preferred data center location
 
Service bus
 
 
As the result in couple of minutes my Service bus will be ready to go
 
Service bus - Queues
 
 
Case management Mobile Service will send messages to Microsoft Dynamics AX 2012 by means of Service bus Queue, that’s why I’ll need to create a queue for the integration
 
Create queue
 
 
Here I’ll specify queue name and preferred data center location
 
Service bus - Queue
 
 
Finally Cases queue has been created. And now I can review Service bus Connection information
 
Access connection information
 
 
Now we can write a script which will be executed every time we insert a record into “case” table
 
Mobile service - Script
 
 
Please note that I use Default Key in the code that connects to the Service bus queue. In particular, Default Key is a second parameter in createServiceBusService method
 
Source code:
 
function insert(item, user, request) {
    var insertInQueue = function() {
        var azure = require('azure');
        var serviceBusService = azure.createServiceBusService('casemanagement', ' ');
 
        serviceBusService.createQueueIfNotExists('cases', function(error) {
            if (!error) {
                serviceBusService.sendQueueMessage('cases', JSON.stringify(item), function(error) {
                    if (!error) {
                        console.log('sent message: ' + item.id);
                    }
                });
            }
        });
    };
 
    request.execute({
        success: function () {
            insertInQueue();
            request.respond();
        }
    });
}
 
In the code I also check if there’s a queue called “cases” and create this queue programmatically if necessary
 
If I create new case in Case management Client app now, the new record will be written into Service bus Queue
 
Case management Client app
 
 
Mobile service - Browse
 
 
New record is create in “case” table
 
Service bus - Queue
 
 
As well as new record has been written into Service bus queue. You can see that Queue length is 1 now. You may also ask Can I manipulate Service bus queue in Visual Studio 2012? Yes, you can. In order to do that I’ll first install Windows Azure SDL for .NET (Visual Studio 2012)
 
Windows Azure SDK for .NET (VS 2012)
 
 
Windows Azure SDK for Visual Studio 2012 gives you an ability to access Windows Azure Subscription details from within Visual Studio 2012
 
Server Explorer
 
 
In order to connect to your Windows Azure Subscription account you will need to import Subscription settings file in Import Windows Azure Subscriptions dialog 
 
Import Windows Azure Subscriptions
 
 
You can initially download Subscription settings file from Windows Azure Portal
When connected you will be able to see the details about your Windows Azure Service bus Queues
 
Server Explorer
 
 
After case record has been written to Service bus Queue it will be synchronized to Microsoft Dynamics AX 2012 by means of Microsoft Dynamics AX Connector for Mobile Apps. Details about configuration of Microsoft Dynamics AX Connector for Mobile Apps will be provided in a separate article for the sake of clarity. Please find more information about Configuring Microsoft Dynamics AX 2012 Connector for Mobile Apps here: http://www.microsoft.com/en-us/download/details.aspx?id=36776
 
As the result information about case will be synchronized to Microsoft Dynamics AX 2012
 
Microsoft Dynamics AX 2012
 
Please note that Windows Azure Mobile Services also support custom APIs
 
As you can see Windows Azure Mobile Services provides a modern development experience for developing mobile apps which may be integrated with Line of Business (LOB) applications.
 
Summary: This document describes how to develop Microsoft Dynamics AX 2012 Apps using Windows Azure Mobile Services. In this example simple Case management App was developed. The information about cases is stored in Mobile Service SQL Server database and then by means of Windows Azure Service Bus and Microsoft Dynamics AX for Mobile Apps is synchronized into Microsoft Dynamics AX 2012 for further processing and resolution. Please learn more about Windows Azure here: http://www.windowsazure.com
 
Tags: Microsoft Dynamics AX 2012, Windows Azure, Windows Azure Mobile Services, Windows Azure Service Bus, Microsoft Dynamics AX Connector for Mobile Apps, Microsoft Cloud, Mobile Apps.
 
Note: This document is intended for information purposes only, presented as it is with no warranties from the author. This document may be updated with more content to better outline the issues and describe the solutions.
 
Author: Alex Anikiev, PhD, MCP

5 comments:

  1. This is just the information I am finding everywhere. Thanks for your blog, I just subscribe your blog. This is a nice blog..
    Mobile-Universe

    ReplyDelete
  2. It’s great to come across a blog every once in a while that isn’t the same out of date rehashed material. Fantastic read.
    Microsoft Azure Online Training

    ReplyDelete
  3. thank you for this information..
    Azure offers the reliability that’s needed for high-availability applications, even including failover between different regions. The Azure portal lets you easily manage all your Azure services. You can also manage your services programmatically by using service-specific APIs and templates.


    ReplyDelete