Sample: Windows 8 desktop modern SOAP app

 

Applies To: Dynamics CRM 2015

This sample code is for Microsoft Dynamics CRM 2015 and Microsoft Dynamics CRM Online 2015 Update. It can be found in the following location in the download package:

SampleCode\CS\ModernAndMobileApps\ModernSoapApp

Download the Microsoft Dynamics CRM SDK package.

Requirements

This sample requires the Microsoft.Preview.WindowsAzure.ActiveDirectory.Authentication and Microsoft.IdentityModel.Clients.ActiveDirectory NuGet packages. If you have a working internet connection, the packages are automatically downloaded and installed when you load the project’s solution.

For more information about the requirements for running the sample code provided in this SDK, see Use the sample and helper code.

Demonstrates

Windows 8 sample app main screen

Tiled user interface of the sample app

This sample shows how to write a Windows 8.1 desktop modern application that can send requests to the organization web service without linking to the SDK assemblies. This sample uses the Microsoft Azure Active Directory Authentication Library (ADAL) and the SOAP protocol. The sample also demonstrates obtaining the OAuth endpoint URL at run time.

While there are seven tiles displayed on the main app page, only the Accounts and Tasks tiles are connected to event handler code. The other tiles are just placeholders.

The example code is configured for the Microsoft Dynamics CRM Online server and a fictitious organization, but will work with an IFD server also.

Code snippets showing just the key sections of the full sample are shown later in this topic.

Example

The following code snippet shows how to authenticate the user with the organization web service.

For this code to work, you must first register your app with a supported identity provider (AD FS or Microsoft Azure Active Directory). Next, you must set the variable values for _clientID, and CrmServiceUrl in the code. The value for client ID was defined during app registration. For more information about app registration, see Walkthrough: Register a CRM app with Active Directory.

Example

The following code snippet shows how to retrieve entity records from the organization web service using SOAP code in an HTTP request. The authentication access token is placed in the authorization header.


using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace ModernSoapApp
{
    public static class HttpRequestBuilder
    {
        /// <summary>
        /// Retrieve entity record data from the organization web service. 
        /// </summary>
        /// <param name="accessToken">The web service authentication access token.</param>
        /// <param name="Columns">The entity attributes to retrieve.</param>
        /// <param name="entity">The target entity for which the data should be retreived.</param>
        /// <returns>Response from the web service.</returns>
        /// <remarks>Builds a SOAP HTTP request using passed parameters and sends the request to the server.</remarks>
        public static async Task<string> RetrieveMultiple(string accessToken, string[] Columns, string entity)
        {
            // Build a list of entity attributes to retrieve as a string.
            string columnsSet = string.Empty;
            foreach (string Column in Columns)
            {
                columnsSet += "<b:string>" + Column + "</b:string>";
            }

            // Default SOAP envelope string. This XML code was obtained using the SOAPLogger tool.
            string xmlSOAP =
             @"<s:Envelope xmlns:s='https://schemas.xmlsoap.org/soap/envelope/'>
                <s:Body>
                  <RetrieveMultiple xmlns='https://schemas.microsoft.com/xrm/2011/Contracts/Services' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
                    <query i:type='a:QueryExpression' xmlns:a='https://schemas.microsoft.com/xrm/2011/Contracts'><a:ColumnSet>
                    <a:AllColumns>false</a:AllColumns><a:Columns xmlns:b='https://schemas.microsoft.com/2003/10/Serialization/Arrays'>" + columnsSet +
                   @"</a:Columns></a:ColumnSet><a:Criteria><a:Conditions /><a:FilterOperator>And</a:FilterOperator><a:Filters /></a:Criteria>
                    <a:Distinct>false</a:Distinct><a:EntityName>" + entity + @"</a:EntityName><a:LinkEntities /><a:Orders />
                    <a:PageInfo><a:Count>0</a:Count><a:PageNumber>0</a:PageNumber><a:PagingCookie i:nil='true' />
                    <a:ReturnTotalRecordCount>false</a:ReturnTotalRecordCount>
                    </a:PageInfo><a:NoLock>false</a:NoLock></query>
                  </RetrieveMultiple>
                </s:Body>
              </s:Envelope>";

            // The URL for the SOAP endpoint of the organization web service.
            string url = CurrentEnvironment.CrmServiceUrl + "/XRMServices/2011/Organization.svc/web";

            // Use the RetrieveMultiple CRM message as the SOAP action.
            string SOAPAction = "https://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/RetrieveMultiple";

            // Create a new HTTP request.
            HttpClient httpClient = new HttpClient();

            // Set the HTTP authorization header using the access token.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            // Finish setting up the HTTP request.
            HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, url);
            req.Headers.Add("SOAPAction", SOAPAction);
            req.Method = HttpMethod.Post;
            req.Content = new StringContent(xmlSOAP);
            req.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml; charset=utf-8");

            // Send the request asychronously and wait for the response.
            HttpResponseMessage response;
            response = await httpClient.SendAsync(req);
            var responseBodyAsText = await response.Content.ReadAsStringAsync();

            return responseBodyAsText;
        }
    }
}

You can use the SOAPLogger tool provider in the SDK download to obtain the SOAP code for an organization request. For information about using the SOAPLogger tool, see Walkthrough: Use the Modern app SOAP endpoint with JavaScript.

See Also

Write mobile and modern apps
Authenticate the user with the web services
Sample: Windows 8 desktop modern OData app
Azure Authentication Library (AAL) for Windows Store: a Deep Dive
Securing a Windows Store Application and REST Web Service Using Azure AD (Preview)
Understanding SOAP

© 2016 Microsoft. All rights reserved. Copyright