Build an ASP.NET Core Web App with Adoxio Connect Framework

Microsoft’s ASP.NET team is going through a big transition period right now to an open source redesign of ASP.NET called ASP.NET Core. ASP.NET Core has major changes that are meant to try to make it more accessible to a larger set of developers as well as bringing it to many platforms with incredible performance improvements. If you’re a web developer building ASP.NET sites that connect to Dynamics 365 this will be an important platform to investigate and use in your solutions. In this post we will walk through a sample of a Dynamics 365 Web App that is built on ASP.NET Core and use the Server-to-Server authentication that Adoxio Connect Framework provides.

Previously we have built samples for a Console Application and a standard ASP.NET Web Application. What makes ASP.NET Core different is that is all the new versions of MVC, Web Api, OWIN and the entire framework being built on .NET Standard instead of the .NET Framework. The change of building ASP.NET Core by following .NET Standard is the single largest change and is what makes the framework now cross platform and able to run on Linux. As Dynamics developers we need to continue using the .NET Framework due to the dependencies the Dynamics 365 SDK has to use .NET Framework components. It is not unexpected though, removing .NET Framework is big change and will take considerable time to make a shift (v8.2 shows approximately 75% compatibility with .NET Standard). This however does not mean they we can’t use ASP.NET Core as Dynamics developers because ASP.NET Core can also be run on .Net Framework since it is .NET Standard compatible. This means you can use .NET Framework based libraries like the Dynamics 365 SDK or others like SharePoint, and even Adoxio Connect Framework.

So Why Use ASP.NET Core
Their are huge changes that are great for developers and builders to make use of. There are major benefits in terms of modularization of the request pipeline, dependency injection a core part of the platform, performance (a factor of 10 compared to ASP.NET 4.6), new MVC version, and open source! If you’re build a brand new web app then you should strong consider starting with ASP.NET Core.

As such let’s look at how you can use Adoxio Connect Framework with this version and understand some of the differences from the ASP.NET implementation.


Firstly let’s start by creating a new ASP.NET Core project. You can do this with the latest version of Visual Studio, 2017. Select from the ASP.NET Core Web Application (.NET Framework) template under Visual C# > Web area. It’s important you select the .NET Framework version so we can support the Dynamics 365 SDK, and select .NET Framework 4.6.1 which Adoxio Connect Framework requires.

Next select Web Application while ensuring that ASP.NET Core 1.1 is selected in the version drop down.

With the new web project just like the standard ASP.NET sample we want to include the necessary NuGet packages necessary to connect to Dynamics 365. As we are going to use a Server-to-Server based authentication we are going to use Adoxio Connect Framework to make that implementation easy in the application. Within the project, right click Dependencies in the Solution Explorer and select Manage NuGet Packages… Within the NuGet package manager, select Browse and search for “Adoxio”, then select and install the latest version of Adoxio.Dynamics.Connect.

Adoxio Connect Framework will also bring in the necessary dependencies when it installs including the Dynamics 365 SDK.

This is the only package to install with ASP.NET Core to get started, making it super simple to start. Now with all the dependencies installed to the project the next step is to ensure you have done the necessary setup for server-to-server authentication. This includes creating an Azure AD application with the appropriate API access, and creating an application user with a security role in CRM. To learn more about the server-to-server authentication setup follow the MSDN documentation. Follow the same steps for multi-tenant for building this single tenant web application, other than you don’t need to worry about creating a process to deploy the application user as it will be a one time process per Dynamics instance. Use Multi-Tenant Server-to-server authentication

Once your have your S2S settings created (you will need a Client Id, Client Secret, the instance or resource – your Dynamics instance URL, and Azure AD tenant ID) then we need to input them into the ASP.NET Core app settings. This differs from the standard ASP.NET application as that configuration was all XML based and heavily used the Configuration Manager. Both in ASP.NET Core are no more. Settings are now stored in JSON and are retrieved via dependency injection in the OWIN App Startup services configuration. First let’s put a structure to read in the appsettings.json file.


  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AdoxioConnect": {
    "dynS2S": {
      "ClientId": "1d8925fd-8cbe-4f07-a83f-f59f7b111350",
      "ClientSecret": "ckrtN4TrckIAF1i5ccEcJw+C4/ESfcyjWGBRBI80a3A=",
      "Resource": "https://connectexampleinstance.crm.dynamics.com",
      "TenantId": "ae83bd39-7849-4089-3965-1e5749dc4dc2"
    }
  }
}

These are just sample values.

With the settings now input we need to have the ASP.NET Core application add them to its dependency injection pipeline so we can then use them when forming the CrmContext constructor so we have a context to communicate with Dynamics 365.

Open the Startup.cs class and navigate to the ConfigureServices method. In this method we are going to use the S2SAppSettings class that comes with Adoxio Connect Framework to register the settings in the appsettings.json as an object that can be accessed in the application.

services.Configure<S2SAppSettings>(Configuration.GetSection("AdoxioConnect:dynS2S"));

We can use S2SAppSettings because the names we used in the appsettings.json match that class definition. This class object will now be available to the entire application through the platform based dependency injection. You can read more about the DI in ASP.NET Core here – Introduction to Dependency Injection in ASP.NET Core

With the settings now available we need to make a small extension class to support the DI in ASP.NET Core in Adoxio Connect Framework. Create a new folder called Extensions if you want, and then a new class which you can call CrmContextCore.cs. In this class we simply just want to add a new constructor to the CrmContext that is part of Adoxio Connect Framework which will allow it to read the S2SAppSettings through the dependency injection.

using Adoxio.Dynamics.Connect;
using Microsoft.Extensions.Options;

namespace Adoxio.Connect.WebCore.Extensions
{
    public class CrmContextCore : CrmContext
    {
        public CrmContextCore(IOptions<S2SAppSettings> s2sAppSettingsOptions) : base(s2sAppSettingsOptions.Value)
        {
        }
    }
}

Why didn’t we just add this to Adoxio Connect? It would require making a library for both ASP.NET Core and standard ASP.NET because of the IOptions dependency so we decided this was such a small simple change as well as a place to start building extensions to the framework in your own project that we would stick with a single library until there were more benefits.

All that is in this class is firstly it inherits and extends the CrmContext class and add a new constructor that reads the S2SAppSettings as an IOptions object that then calls the base constructor with the value of the S2SAppSettings object. If you wanted to use the Xrm Tooling, CrmServiceClient this would be a good class to make those changes as well. This CrmContextCore class is what we will next be adding to the ASP.NET Core application as a singleton so that it is also available to the whole application through dependency injection.

Back in Startup.cs under the ConfigureServices method we can now add our new class as that singleton object.

services.AddSingleton<CrmContextCore>();

Why AddSingleton? You can read more about the different service types for adding objects to the pipeline here with Service Lifetimes and Registration Options, as well there is a good answer on StackOverflow depicting an example of all of them. The reason here is that we really only need 1 connection to the Dynamics 365 instance in the entire application and there is no need to recreate the object on every request. So with a singleton we get a single object created at the startup of the application which makes for great performance on every request.

The ConfigureServices method should now have 2 additional lines as below and that is all the configuration that is actually needed to use the Adoxio Connect Framework and have a context that will allow you to interact with the Dynamics 365 instance through that Server-to-Server connection.

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    services.Configure<S2SAppSettings>(Configuration.GetSection("AdoxioConnect:dynS2S"));
    services.AddSingleton<CrmContextCore>();
}

Now that the application is setup we can now start creating controllers and other functions in the application that can access these objects easily through the dependency injection. Let’s look at a simple controller that implements some simple SDK calls.

using Microsoft.AspNetCore.Mvc;
using WebApplication13.Extensions;

namespace WebApplication13.Controllers
{
    public class CrmSdkController : Controller
    {
        private readonly CrmContextCore _crmContext;

        public CrmSdkController(CrmContextCore crmContext)
        {
            _crmContext = crmContext;
        }

        public IActionResult Index()
        {
            return View();
        }
    }
}

The addition we make to our class to make use of our context is just simply adding a constructor to the class that calls to singleton object we added to the application and then stores it in a private object that is accessible throughout the class. ASP.NET Core’s dependency injection makes it all this easy.

Now you can build methods that use the context to call Dynamics 365 using your normal SDK calls. Below is the same method as both a MVC view and an API JSON return within the exact same controller which is all now combined in ASP.NET Core MVC.

public IActionResult Index()
{
    var contacts = _crmContext.ServiceContext.CreateQuery("contact").ToList();
    return View(model: string.Join(",", contacts.Select(a => a.GetAttributeValue<string>("fullname"))));
}

[Produces("application/json")]
[Route("api/CrmSdk")]
public IEnumerable<Entity> GetContacts()
{
    var contacts = _crmContext.ServiceContext.CreateQuery("contact").ToList();
    return contacts;
}

All of this new ASP.NET Core sample code is now part of the samples on the Adoxio Connect Framework GitHub repo.

Again if your starting a new web development project for Dynamics 365 definitely consider ASP.NET Core even though your still using .NET Framework. There is still significant benefit to mixing the 2 together.

If your interested to know more about the Adoxio Connect Framework and Dynamics 365 Server-to-Server authentication I will be giving a webinar with the Xrm Virtual User Group this Tuesday July 11th at 12pm EST / 9am PST.

Building a Dynamics 365 ASP.NET Web App with Adoxio Connect Framework

The primary purpose behind the Adoxio Connect Framework was to help facilitate an easy server-to-server connection for a Web App. By using the Adoxio Connect Framework it helps by providing an implementation of OrganizationWebProxyClient and Active Directory Authentication Library so that you can easily interact through the Dynamics 365 SDK within your web application. This guide will walk you through starting an ASP.NET MVC and Web API project with the Adoxio Connect Framework to build your own forms, and APIs. If you’re looking to build a companion app to the Dynamics 365 portal or any CMS that can access a Dynamics instance and interact with it, then this is the guide to help you get that process started. This will also include the option of using the XRM Tooling API so you can utilize the CrmServiceClient extensions in your web application.

For this guide I am using Visual Studio 2017, but it should also be the same with Visual Studio 2015 provided you have the latest updates.

To start we need to create an an ASP.NET Web Application and this should be done using .NET Framework 4.6.1.

After creating, you should be prompted to select the template for the project. Here its up to the requirements you have and your preferred application templates, all templates are supported to implement the Connect Framework. For this guide I will be selecting the MVC template but also enabling Web API.

When you create a new ASP.NET Web Application depending on your template and references selected it will download a certain set of NuGet packages. Optionally you can update all the packages to the latest version. To update all the packages and install the additional NuGet packages I suggest using the Package Manager Console (View > Other Windows > Package Manager Console).

To update all packages run the following command in the Package Manager Console:

Update-Package

Next we need to install OWIN host for IIS (System.Web) as well OWIN for ASP.NET Identity. We are going to be using the OWIN framework to add the CrmContext object from the Adoxio Connect Framework so that it will make the context easily available from all controllers, API controllers, classes, and other application components.

Run the following 2 package install commands to get the necessary OWIN NuGet packages:

Install-Package Microsoft.Owin.Host.SystemWeb -Version 3.0.1
Install-Package Microsoft.AspNet.Identity.Owin

Finally we will run the install package command for the Adoxio Connect Framework which will also install the Dynamics 365 SDK.

Install-Package Adoxio.Dynamics.Connect

With all the dependencies installed to the project the next step is to ensure you have done the necessary setup for server-to-server authentication. This includes creating an Azure AD application with the appropriate API access, and creating an application user with a security role in CRM. To learn more about the server-to-server authentication setup follow the MSDN documentation. Follow the same steps for multi-tenant for building this single tenant web application, other than you don’t need to worry about creating a process to deploy the application user as it will be a one time process per Dynamics instance. Use Multi-Tenant Server-to-server authentication

With the server-to-server settings created you will need to add the following settings to the web.config, completing the settings with your values (this are not working values only for sample purposes):

<appSettings>
  <add key="dyn:ClientId" value="1d8925fd-8cbe-4f07-a83f-f59f7b111350" />
  <add key="dyn:ClientSecret" value="ckrtN4TrckIAF1i5ccEcJw+C4/ESfcyjWGBRBI80a3A=" />
  <add key="dyn:Resource" value="https://connectexampleinstance.crm.dynamics.com" />
  <add key="dyn:TenantId" value="ae83bd39-7849-4089-3965-1e5749dc4dc2" />
</appSettings>

With these settings present you can use the default constructor of the CrmContext object, alternatively you can use the other constructors to have your settings loaded from another location like an Azure Key Vault. The Connect Framework also includes a setting manager if you want to save the application settings to a file on disk. The setting manager contains methods both to save and load the 4 application settings from a settings.json file in the App_Data folder.

However you choose to instantiate the CrmContext object we can use OWIN to make it easy to access this object throughout the application. By adding a OWIN Startup class to the application and loading the CrmContext into the OwinContext it becomes available everywhere in the application that the OwinContext can be accessed. To create an OWIN Startup class, right click in the solution explorer on your project name and select Add > OWIN Startup Class.

Within the startup class we want to ensure that the CrmContext object using the default constructor is going to load properly so there is a method in the SettingManager called InitAppSettings that will check it can properly load the settings first. This would allow you to insert other logic here if the settings don’t exist to potentially gather them from the user or throw/route the exception based on your desired application output. Below is a small sample of this check as well as if it succeeds how you can use the OWIN framework to register the CrmContext through dependency injection.

public void Configuration(IAppBuilder app)
{
    if (SettingManager.InitAppSettings())
    {
        app.CreatePerOwinContext<CrmContext>(CrmContext.Create);
    }
    else
    {
        throw new Exception("Adoxio Connect Framework app settings not found.");
    }
}

CreatePerOwinContext will register a callback of CrmContext.Create on the OwinContext and this callback called once per request so that you can access it easily throughout the application. To match the CrmContext constructors there are also CrmContext.Create methods to support you injecting server-to-server application settings easily in this callback format.

Once you have registered the CrmContext on the OwinContext you can easily access it in MVC controllers with the following code:

var context = Request.GetOwinContext().Get<CrmContext>();

For a Web API controller:

var context = HttpContext.Current.GetOwinContext().Get<CrmContext>();

Within both you will need to add using statements for Adoxio.Dynamics.Connect as well as Microsoft.AspNet.Identity.Owin. For the API controller to access HttpContext add a using statement for System.Web.

Both of these statements are using the Get method on the OwinContext, which is initiating the callback that was registered for type CrmContext and making the result available within your controller. Once you have this object returned it will already be set based on the logic within your OWIN startup class. If using the default constructor of CrmContext it will use the app settings to build the connection including the token so you can easily make requests using either the OrganizationWebProxyClient or an OrganizationServiceContext.

With this CrmContext now easily available you can now just build your ASP.NET Web Application as you would build any web application for your requirements. The CrmContext acts as your persistent application database context that is available on every request. To see a full MVC and API controller read examples check out the Git repo for Adoxio.Dynamics.Connect in the samples\Adoxio.Connect.WebApp folder.

Based on how you build applications with the Dynamics 365 SDK you may want to use the XRM Tooling API as well. You can easily add the CrmServiceClient as another type registered on the OwinContext or have this as your only type registered. The CrmServiceClient actual provides a constructor for OrganizationWebProxyClient and because the CrmContext object contains a property of this type it is very easy to use both together.

The rest of this guide is optional if you want to use the XRM Tooling API / CrmServiceClient Continue reading “Building a Dynamics 365 ASP.NET Web App with Adoxio Connect Framework”