<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Michal Chmielus</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/mchmielu/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/mchmielu/feed.xml</link>
    <description>Microsoft Dynamics CRM and Azure</description>
    <lastBuildDate>Wed, 17 Apr 2019 04:05:44 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Authenticate Azure App Service with Azure AD Security Group</title>
      <link>https://docs.microsoft.com/archive/blogs/mchmielu/authenticate-azure-app-service-with-azure-ad-security-group</link>
      <pubDate>Tue, 06 Mar 2018 14:32:34 GMT</pubDate>
      <dc:creator><![CDATA[Michal Chmielus]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mchmielu/?p=225</guid>
      <description><![CDATA[If you're developing Azure App Service i.e. ASP.NET MVC application and there is a requirement to...]]></description>
      <content:encoded><![CDATA[If you're developing Azure App Service i.e. ASP.NET MVC application and there is a requirement to authenticate current user against Azure AD Security Group you need to consider some steps:
In th Startup.cs as the part of UseOpenIdConnectAuthentication add/change Notifications
<code>
                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        RedirectToIdentityProvider = (context) =&gt;
                        {
                            string appBaseUrl = ConvertToSsl(context.Request.Scheme) + "://" + context.Request.Host + context.Request.PathBase;
                            context.ProtocolMessage.RedirectUri = appBaseUrl;
                            context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
                            return Task.FromResult(0);
                        }
                    }
</code>

ConvertToSsl helps ensuring appBaseUrl starts with https protocol.

The Azure AD Application provided as a ClientId in OpenIdConnectAuthenticationOptions should have some adjustement in the manifest. Please refer to manifest <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-application-manifest" target="_blank">guideline</a>.
The change in the manifest is by adding / replacing line:
"groupMembershipClaims" : "SecurityGroup"

This is crutial to have desired authentication working properly.
Obviously, there is one action pending - how to auhtorize user. Let's commit we're going to use a filter approach by creating custom attribute class which inherits from AuthorizeAttribute, i.e.:
<code>
public class AuthorizeBySg: AuthorizeAttribute
</code>

and override AuthorizeCore function, i.e.:
<code>
protected override bool AuthorizeCore(HttpContextBase context)
{
   if (!base.AuthorizeCore(context)) return false;
   return ClaimsPrincipal.Current.Claims.Any(c =&gt; c.Type == "groups" &amp;&amp; mygroupId == c.Value);
}
</code>
mygroupId is an object ID of restricted Azure AD Security Group.

Finally, decorate your Controller or methods in your Controller with newly created AuthorizeBySg attribute class.]]></content:encoded>
    </item>
    <item>
      <title>Bulk load into Dynamics 365</title>
      <link>https://docs.microsoft.com/archive/blogs/mchmielu/bulk-load-into-dynamics-365</link>
      <pubDate>Mon, 15 Jan 2018 14:05:34 GMT</pubDate>
      <dc:creator><![CDATA[Michal Chmielus]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mchmielu/?p=165</guid>
      <description><![CDATA[This is fairly common to massive data load into Dynamics 365. Here you can find useful link  to bulk...]]></description>
      <content:encoded><![CDATA[This is fairly common to massive data load into Dynamics 365. Here you can find useful <a target="_blank" href="https://msdn.microsoft.com/en-us/library/jj863631.aspx" rel="noopener">link </a> to bulk load. As you know there are some <a target="_blank" href="https://msdn.microsoft.com/en-us/library/jj863631.aspx#Anchor_3" rel="noopener">constraints</a> while accessing Dynamics 365 over SDK (<strong><span class="selflink">Microsoft.Xrm.Sdk.Client<span>.</span>OrganizationServiceProxy</span></strong>):
<ul>
 	<li>1000 requests in <strong><span class="selflink">Microsoft.Xrm.Sdk.Messages<span>.</span>ExecuteMultipleRequest</span></strong></li>
 	<li>2 concurrent <span class="selflink">Microsoft.Xrm.Sdk.Messages<span>.</span>ExecuteMultipleRequest</span></li>
</ul>
Firstly, you need to instantiate <strong><span class="selflink">Microsoft.Xrm.Sdk.Client<span>.</span>OrganizationServiceProxy</span></strong> class and open the WCF channel to your CRM Organization. Then within a new Task create a new instance of OrganizationServiceProxy using recent instances of <strong>IServiceManagement</strong> and <strong>SecurityTokenResponse</strong> variables.

Each <strong>OrganizationServiceProxy</strong> instance created within a Task can keep impersonated user.

You would also need to feed variable actionRequest of <strong><span class="selflink">Microsoft.Xrm.Sdk.Messages<span>.</span>ExecuteMultipleRequest</span> </strong>which can be any of <strong>OrganizationRequest</strong> type.

<img width="1024" height="678" class="alignleft size-large wp-image-185" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/01/processBulk1-1024x678.png" />

<img width="1024" height="549" class="alignleft size-large wp-image-205" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/01/processTask1-1024x549.png" />]]></content:encoded>
    </item>
    <item>
      <title>Unit Testing Dynamics 365 plugin code</title>
      <link>https://docs.microsoft.com/archive/blogs/mchmielu/unit-testing-dynamics-365-plugin-code</link>
      <pubDate>Thu, 11 Jan 2018 13:33:35 GMT</pubDate>
      <dc:creator><![CDATA[Michal Chmielus]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mchmielu/?p=115</guid>
      <description><![CDATA[Unit Testing is crutial in software development which helps you proofing your development efforts...]]></description>
      <content:encoded><![CDATA[Unit Testing is crutial in software development which helps you proofing your development efforts and delivery in regards to desired functionality.

I'm not going to explain step by step how to create a Unit Test project in Visual Studio but focus on some remarkable topics.

In Dynamics 365 plugin development I have been using <strong>Moq</strong> and <strong>Microsoft.VisualStudio.TestTools.UnitTesting</strong> namespaces. Let's assume you have already created Test project in Visual Studio. Since you're going to use Moq need to install. Navigate to Nuget Package Manager console and install:

<strong>PM&gt; Install-Package Moq</strong>

In your test class add a namespace :
<code>using Moq;</code>

Ensure your class is public and decorated properly:
<code>[TestClass]</code>

for instance:
<code>[TestClass]
public class TestAddContactToMarketingList</code>

&nbsp;
<p>Implement your TestMethod and setup OrganizationService. Ensure you setup OrganizationService and call your business logic method, i.e: AddContactToMarketingList:</p>

<img width="550" height="180" class="size-medium wp-image-145 alignleft" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/01/AddContactToMArketingList_Success-300x122.png" />

<img width="1078" height="260" class="wp-image-145 alignleft" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/01/AddListMembers-1024x247.png" />]]></content:encoded>
    </item>
    <item>
      <title>Utilize Data Export Service as data replication service in Dynamics 365</title>
      <link>https://docs.microsoft.com/archive/blogs/mchmielu/utilize-data-export-service-as-data-replication-service-in-dynamics-365</link>
      <pubDate>Fri, 03 Nov 2017 14:39:34 GMT</pubDate>
      <dc:creator><![CDATA[Michal Chmielus]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mchmielu/?p=96</guid>
      <description><![CDATA[It is always crutial to do not degradate the performance in CRM and frustrate users by slowly...]]></description>
      <content:encoded><![CDATA[It is always crutial to do not degradate the performance in CRM and frustrate users by slowly loading pages. <a href="https://msdn.microsoft.com/en-us/library/mt788315.aspx">Data Export Service</a> is add-on service as Dynamics 365 (online) solution which replicates data to Azure SQL Database and this is fairly good solution however not perfect.

In case you need to work in nearly real-time and there is a lot of plugins running against CRM online instance you need to consider another scenario described in this post.

Below is the solution design diagram where you can find Azure components:
<img src="https://msdnshared.blob.core.windows.net/media/2017/11/DynamicsCRMIntegration-1024x946.png" alt="Dynamics CRM integration solution design" width="1024" height="946" class="alignnone size-large wp-image-97" />

Obviously Dynamics CRM is the ultimate source system which shares some data across over Data Export Service and signals over Service Endpoint to Azure Service Bus. The logic app picks the message up and proceed which is resulted in Dynamics CRM.]]></content:encoded>
    </item>
    <item>
      <title>Call Dynamics 365 from Azure App Service</title>
      <link>https://docs.microsoft.com/archive/blogs/mchmielu/call-dynamics-crm-from-azure-app-service</link>
      <pubDate>Fri, 06 Oct 2017 12:06:22 GMT</pubDate>
      <dc:creator><![CDATA[Michal Chmielus]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mchmielu/?p=67</guid>
      <description><![CDATA[In case you need to get or modify data in Dynamics 365 while calling from Azure Logic App I would...]]></description>
      <content:encoded><![CDATA[In case you need to get or modify data in Dynamics 365 while calling from Azure Logic App I would recommend to use an action of Http type. This action provides you to request Dynamics 365 endpoint using most of relevant verbs (methods), among each other: GET, POST, PATCH, DELETE along with authentication header.
This is mandatory to bind your 365 user prior to consume Dynamics 365 Web API. Please refer to my previous <a href="https://blogs.msdn.microsoft.com/mchmielu/2017/09/08/how-to-bind-dynamics-crm-with-azure-logic-apps">blog </a>where explained how to do it. 

Dynamics 365 exposes RESTFul Web <a href="https://msdn.microsoft.com/en-us/library/mt593051.aspx">API</a> with a plenty of features even fairly complex.
Dynamics 365 Web API implements OData protocol hence you need to consider it while constructing requests.

Below you can find the example how the Azure Logic App can be implemented. It accepts a CityName as an input parameter and is combined in the query sent to Web API resulted with accounts with a city of specified.

[caption id="attachment_77" align="alignnone" width="820"]<img src="https://msdnshared.blob.core.windows.net/media/2017/10/callCrm1.png" alt="Call Dynamics 365 over Web API" width="820" height="1000" class="size-full wp-image-77" /> Azure Logic App is getting accounts from specified city[/caption]

and a source code:

[caption id="attachment_86" align="alignnone" width="820"]<img src="https://msdnshared.blob.core.windows.net/media/2017/10/logicapp.png" alt="Logic App source code" width="820" height="948" class="size-full wp-image-86" /> Logic App source code[/caption]

Please note the authentication is critical and you must provision Azure AD Application along with the binding prior to implementing the Logic App.
To obtain values retrieved by the Http action you need to use a property named 'value' which is an array. Logic App has a variety of string, conversion functions which would help you in parsing retrieved data. Please refer to the <a href="https://docs.microsoft.com/en-us/azure/logic-apps/logic-apps-workflow-definition-language"> link </a>.

</br>
<h4>Calling Dynamics 365 in custom API</h4>
There is lightweight approach to consume Dynamics 365 over Application User. The instance which you can further leverage is <a href="https://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.webserviceclient.organizationwebproxyclient.aspx" target="_blank">OrganizationWebProxyClient</a>.

Class signature:
<code>
public class OrganizationWebProxyClient : WebProxyClient, IOrganizationService
</code>

First of all you need to aquuire the token from Azure AD using for instance <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-code-samples" target="_blank">ADAL library</a>.

<code>
var authenticationContext = new AuthenticationContext(authority);
var clientCredentials = new ClientCredential(clientId, clientSecret);
AuthenticationResult result = authenticationContext.AcquireTokenAsync(organizationUrl, clientCredentials).Result;
</code>

In case you are going to use early binding you would need to inject your type assembly. It is not enough to set the useStrongTypes argument to True in the constructor but load the assembly:
<code>
public OrganizationWebProxyClient(Uri serviceUrl, Assembly strongTypeAssembly);
</code>

The URL must contain the SDK client version. The client version is set to the version of the SDK assemblies that the client application was linked to. For example:
https://<strong>myorg.crm4.</strong>dynamics.com/XRMServices/2011/Organization.svc/web?SdkClientVersion=8.2

Please refer to organization service <a href="https://msdn.microsoft.com/en-us/library/gg309401.aspx#Anchor_5" target="_blank">endpoint</a>

What you need to provide:
<ul>
<li>clientId = Azure AD Application ID entered to Application ID attribute in your Dynamics Application User</li>
<li>clientSecret = Secret key generated on above Azure AD Application</li>
<li>authority = https://login.microsoftonline.com/{tenantId}/ {TenantId} - DirectoryID of your Azure AD</li>
<li>organizationUrl = Dynamics 365 instance i.e. https://<strong>myorg.crm4.</strong>dynamics.com</li>
<li>organizationEndpoint = Dynamics 365 instance including organization service endpoint, i.e. https://<strong>myorg.crm4.</strong>dynamics.com/XrmServices/2011/Organization.svc/web?SdkClientVersion=8.2</li>

Finaly, you can return an instance:
<code>
return new OrganizationWebProxyClient(organizationEndpoint, Assembly.Load({assembly name}))
</code>]]></content:encoded>
    </item>
    <item>
      <title>How to bind Dynamics 365 with Azure Logic Apps</title>
      <link>https://docs.microsoft.com/archive/blogs/mchmielu/how-to-bind-dynamics-crm-with-azure-logic-apps</link>
      <pubDate>Fri, 08 Sep 2017 12:08:32 GMT</pubDate>
      <dc:creator><![CDATA[Michal Chmielus]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mchmielu/?p=25</guid>
      <description><![CDATA[If you want to call Dynamics 365 over Web API you have to enable binding between Dynamics 365 and...]]></description>
      <content:encoded><![CDATA[If you want to call Dynamics 365 over Web API you have to enable binding between Dynamics 365 and Azure AD Application.
In order to enable Dynamics 365 in Azure Logic App using Azure AD Authentication (OAuth) you need to create Azure AD Application (Application Identity) and grant sufficient permissions.
<!--more-->

There is already great <a target="_blank" href="https://msdn.microsoft.com/en-us/library/mt790170.aspx" rel="noopener">guideline </a>.
<h4>Create Azure AD Application</h4>
How to create Azure AD Application you can find here. Let’s create the Application called <b>MyDynamicsApp</b> for reference.

You need to create a Key (secret). Don’t forget to copy the secret because it will appear only once you have created results you will not be able to obtain the value again regardless permission.

Once you have created Azure AD Application you need to grant permissions to Dynamics 365 API by navigating to your recently created Azure AD Application and Required Permissions then click Add button and select Dynamics 365 from the API list.

<img width="824" height="251" class="alignnone size-large wp-image-35" alt="" src="https://msdnshared.blob.core.windows.net/media/2017/09/blog11-1024x451.png" />

Under DELEGATED PERMISSIONS select permission and Save.

<b>To avoid displaying the consent form while browsing to your Dynamics 365 instance you can click Grant Permissions button which is visible when you navigate to Required Permissions.</b>
<img width="496" height="58" class="alignnone size-full wp-image-45" alt="" src="https://msdnshared.blob.core.windows.net/media/2017/09/blog21.png" />
<h4>Create CRM Application User</h4>
In order to enable systemuser in Dynamics 365 navigate to Settings -&gt; Security -&gt; Users and switch the view to Application Users. Either select already existing user or create a new one. Switch form view to Application User.

<img width="300" height="131" class="alignnone size-medium wp-image-55" alt="" src="https://msdnshared.blob.core.windows.net/media/2017/09/blog3-300x131.png" />

Please be aware there is no need to have Office 365 user and a Dynamics 365 licence applied - you will have Application user with your Azure AD Application threated as an application identity.

Now you are ready to enable application user with Azure Application Identity. Enter an Application ID of your <b>MyDynamicsApp</b> Application ID and save.

Once you entered an Azure <strong>Application ID</strong> to Dynamics 365 SystemUser form you should be able to connect over WebAPI.

In case you are still unauthorized follow these steps:
<ol>
 	<li>enter different valid Application ID</li>
 	<li>save systemuser</li>
 	<li>enter correct one Application ID</li>
 	<li>save systemuser</li>
</ol>
Your systemuser record will be updated with respective values obtained from Azure AD Application:
<ul>
 	<li><span>Application ID URI</span></li>
 	<li><span>Azure AD Object ID</span></li>
</ul>
Please ensure above values exist in Azure AD Application essentially <span><strong>Application ID URI</strong> is equal to <strong>App ID URI</strong>.</span>

<hr />
<p><strong>&lt;&lt; EDIT&gt;&gt; Since November 2017 below comments are no longer valid due to the fix in Dynamics 365 core.</strong></p>

<hr />

Unfortunately, Application ID URI is read-only but is required to complete our goal. There is workaround, so you can update it programmatically.
<ul>
 	<li>Fetch systemUser entry by domainname - technical user email</li>
 	<li>Update applicationIdUri attribute of fetched systemUser entry with the APP ID URI (#2 on picture above) obtained from the Azure AD Application - <b>MyDynamicsApp</b></li>
</ul>
<code>
QueryExpression query = new QueryExpression("systemuser")
{
ColumnSet = new ColumnSet("domainname", "applicationiduri", "systemuserid")
};
query.Criteria.AddCondition(new ConditionExpression("domainname", ConditionOperator.Equal, "[replace with CRM Technical User email adress]"));
OrganizationServiceProxy proxy; //TODO: instantiate the variable
var records = proxy.RetrieveMultiple(query);
if (records.Entities.Count == 1)
{
var entity = records.Entities.ElementAt(0);
entity.Attributes["applicationiduri"] = "[replace with APP ID URI (2) from the picture above]";
proxy.Update(entity);
}
</code>

Now you should be able to call Dynamics CRM over Web API]]></content:encoded>
    </item>
  </channel>
</rss>