Mobile first, cloud first

We all understand the importance of mobile and cloud strategy and that is why the Microsoft Dynamics CRM development team have released native mobile applications to accommodate all the major mobile platforms today – Windows Store, Windows Phone, Android, iOS, Office Outlook on Windows, and we have CRM Mobile Express for other platforms. However, it is also true that how each customer CRM usage varies depending on industry, work style, and other factors. Being a user of mobile apps ourselves, we know that many successful mobile apps enable specific tasks centered around the user and what they are looking to accomplish. 

For some organizations a successful app may be a simple approval app allowing a user to easily view, annotate, approve, or reject records and for others it could be a more integrated solution using location and other sensors to create and augment data in the field – or a company may want both experiences based on the role of the user.  While the existing Dynamics CRM mobile apps usually work very well for many general CRM purposes your company may need more – for that 3rd parties have CRM mobile applications meeting specific demands but what if you want need to build your own applications to meet specific requirements like the ones mentioned above?  If you’ve asked yourself this question or are curious as to how you can enable new ways to engage your Dynamics CRM users then please read on!  Below we’ll outline some challenges and decision points and we will also show you a new way to help developers build mobile apps for Dynamics CRM.

Development Methods

This is the most exciting time for developers as there are so many choices out there how to develop an application. C# or any .NET Framework languages with Visual Studio? Sure! (and that’s my favorite). HTML5/CSS for Windows Universal App? Of course. Xcode and Objective-C for iOS? or Java and Android Studio for Android OS? Why not! When you see cross platform development, you still have many choices like Xamarin, Cordova, etc – and new ones are coming out all the times it seems. 

Dynamics CRM: SOAP vs. REST endpoint

In addition to selecting programming languages, IDEs and platforms, there are several technology choices to build an application targeting Microsoft Dynamics CRM. A fully featured SOAP (or also referred to as web) endpoint or the lightweight and easy to develop REST endpoint. Most who have developed in Dynamics CRM understand the REST endpoint has some limitations in which only supports CRUD operations though we do have ways to enable Execute actions with some clever configuration and programming (we can cover that in a future blog post). While the REST endpoing covers most of the common operations, you still need Execute method for several operations like “Send” emails, “Book” appointments or “SetState records. Even “Assign” records to other users.

Direct service connection vs. host middleware service

When you build a mobile application, you can write a code to directly consume Microsoft Dynamics CRM Web services, or you can let middleware services to consume CRM web services and your mobile application consumes the middleware services. Microsoft Azure Mobile Service is one of the popular choice, as you can use C# to write business logic, then use Authentication or offline capability which Azure Mobile Service offers without writing your own code.

 

A Solution: Introducing Mobile Development Helper Code for Dynamics CRM

I hear developers won’t consume SOAP endpoint directly, because there was no library for such purpose and constructing and parsing SOAP request/response is not the most enjoyable task for developers. We have good news for developers, the Dynamics CRM SDK content publishing team released a library called “Mobile Development Helper Code for Dynamics CRM”, which you can directly use in your mobile solution to consume SOAP endpoint just like normal Dynamics CRM SDK. You can also use “CRM Service Utility for Mobile Development” for early bound development. Please refer to the library page for overview. 

 

How to use the library

What we will cover in this post:

The easiest way to try the library is to use it in existing SDK sample app, the sample already has a basic setup for obtaining an AccessToken. However, I will explain step by step here how to use the library for you. Following are prerequisites.

- Visual Studio 2013 installed on Windows 8.1+
- Microsoft Dynamics CRM Online instance. (You are able to use trial version)
- Windows Azure Subscription (You are able to use trial version)
- Download the library from here, and extract it.

Create a Visual Studio solution

1. Open Visual Studio 2013.
2. Click FILE | New | Project
image
3. Select Visual C# | Windows Apps | Blank App
*In this example, I use Windows Store app template, but you can use Windows Phone or Universal template if you need to.
4. Give any name. I name it “Sample CRM Mobile App”

Add ADAL NuGet Packages

The easiest way to obtain AccessToken for OAuth2 from Azure AD is to use ADAL (Azure AD Authentication Library). If you have preferred way to obtain AccessToken, you can use your own way – in fact we’d love to hear how you’re doing this today.

1. In Visual Studio, Right click the project folder in Solution Explorer pane, and click  the Manage NuGet Package menu item. 
2. In the manage package window, Select Online from left pane, and type ADAL in the search box and press Search.
3. Selected Active Directory Authentication Library from the results and click Install.
image
4. Complete the installation, then click Close.

Add the Mobile Helper Library

1. Right click the solution folder in the Solution Explorer pane, and click Add | Existing Project.
2. Browser to the mobile helper folder which can be downloaded and extracted from here: https://code.msdn.microsoft.com/Mobile-Development-Helper-3213e2e6.
3. Select Microsoft.Crm.Sdk.Mobile.csproj file, and click Open.
4. In the Solution Explorer pane, under your new project (not the mobile helper), right click References | Add Reference.
5. In the add reference dialog, select Solution | Project | and select Microsoft.Crm.Sdk.Mobile and click OK.
image

Add Json.NET NuGet Packages

Both your project and mobile helper project requires Json.NET.

1. Right click solution folder in the Solution Explorer pane, and click Manage NuGet Packages for Solution menu. 
2. Select Online from left pane, and type Json.net for search box and search.
3. Selected Json.NET from the result and click Install.
image
4. Complete the installation by check all projects.
5. Click Close when install completes.

Add code to acquire AccessToken from Azure AD

1. Open MainPage.xam.cs file.
2. Replace inside MainPage class with following code.

const string aadInstance = "https://login.windows.net/{0}";
const string tenant = "[Enter tenant name, e.g. contoso.onmicrosoft.com]";
const string clientId = "[Enter client ID as obtained from Azure Portal, e.g. 82692da5-a86f-44c9-9d53-2f88d52b478b]";

static string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
private AuthenticationContext authContext = null;
private Uri redirectURI = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
private string ResourceId = "[Your CRM Online Org Address. e.g. https://contoso.crm.dynamics.com]";

public MainPage()
{
    this.InitializeComponent();
    GetAccessToken();
}

private async void GetAccessToken()
{
    authContext = new AuthenticationContext(authority);
    // Use ADAL to get an access token.
    AuthenticationResult result = await authContext.AcquireTokenAsync(ResourceId, clientId, redirectURI);

    if (result.Status == AuthenticationStatus.Success)
    {
        var AccessToken = result.AccessToken;
    }
}

3. Update tenant and ResouceId to match to your environment.

Register your app to Azure AD

You need to register your application to Azure AD.

1. First of all, obtain RedirectUri value which you use to register your application, Run the existing application by setting breakpoint after getting redirectURI.
image
2. Note the redirectURI value and stop debugging.
3. Go to Microsoft Azure portal page. (http://manage.windowsazure.com)
4. Select Active Directory on the left pane.
image
5. Click APPLICATIONS menu on the top, then click ADD button in the bottom.
6. Select “Add an application my organization is developing.
7. Enter any name and select NATIVE CLIENT APPLICATION.
8. Enter RedirectUri you just obtained.
9. Once registration completed, click CONFIGURE menu.
10. Note a CLIENT ID, which you will update the code by it.
11. Navigate to bottom to setup impersonation.
12. Select “Dynamics CRM” from Select application dropdown, and select “Access CRM Online as organization users.”
13. Click Save button.
14. Go back to Visual Studio 2013, then update clientid const string.

Run the app to obtain AccessToken

1. Set breakpoint at line 51 where you obtain AccessToken from result. Run the app. You will see Sign In page soon.
2. Enter username and password by which you can connect to CRM Online.
3. You will see consent screen only if you register your app in Azure Ad for separate instance. In such case, please OK to accept it.
4. Breakpoint will be hit and you can confirm AccessToken is retrieved successfully.
image

Update the code

Finally use mobile helper library to issue SOAP request.

1. Add following as main class member.
private OrganizationDataWebServiceProxy proxy;
2. To resolve the above code, add following at using section.
using Microsoft.Xrm.Sdk.Samples;
3. Add following code at constructor to initialize proxy.
image
4. Assign proxy.AccessToken after obtaining an AccessToken, then call ExecuteWhoAmI method, which you implement next.
image
5. Add ExecuteWhoAmI method as below.
image
6. Add necessary using statement to resolve names.

Try it out

1. Set break point right after Execute method above.
2. Run the application.
3. When the application breaks into break point, confirm the returned value.
image

What’s Next?

I hope you get the idea how to use the library to consume SOAP endpoint. The next step is to use CrmSvcUtil.exe to generate file for Early Bound development. I will explain how to use the tool next time.

Ken
Premier Mission Critical/Premier Field Engineer 
Microsoft Japan