Start a Dynamics 365 Web API project in Visual Studio (C#)
Applies To: Dynamics 365 (online), Dynamics 365 (on-premises), Dynamics CRM 2016, Dynamics CRM Online
This topic demonstrates how to create a new project in Microsoft Visual Studio that builds a console application that uses the Dynamics 365 Web API. It illustrates the common references and project resources that most applications, including the SDK C# samples, use to implement Web API-based solutions.
Prerequisites
The following prerequisites are required to build the console application described in this section.
Microsoft Visual Studio 2015 installed on your development computer. Any edition, including Visual Studio Express, should be sufficient to work with the Dynamics 365 Web API. For more information about which versions of Microsoft Visual Studio are supported, see Visual Studio and the .NET Framework.
A NuGet client must be installed: either the command-line utility or the Visual Studio extension. For more information, see Installing NuGet.
An internet connection is required to download the NuGet package containing the Dynamics 365 Web API Helper Library, and other dependent packages.
Optionally, download the Microsoft Dynamics 365 SDKhere. Although the Microsoft Dynamics 365 SDK is not required to build or run these Web API samples, most Dynamics 365 developers will want to install it because it contains a rich set supplemental resources, and the SDK is required to access other Dynamics 365 interfaces.
Create a project
The following procedure demonstrates how to create a console application project in C# that uses the Microsoft .NET Framework. For more information on supported versions of the .NET Framework, see Supported extensions for Microsoft Dynamics 365.
New Project
In Microsoft Visual Studio, click New Project. The New Project dialog is displayed.
In the left navigation pane under Templates, select Visual C#.
Above the list of available templates, select .NET Framework 4.5.2.
In the list of templates, select Console Application. (Alternately choose the project type suited to your solution.) All of the Web API C# samples are console applications.
In the text boxes near the bottom of the form, supply the project name and location, and then select OK. (For this topic, the solution name “StartWebAPI-CS” was used.) The initial solution files will be generated and the solution loaded into Microsoft Visual Studio.
Under the Project menu, open the project’s properties form and verify the target framework is set to .NET Framework 4.5.2.
Add all required resources to your project
The following procedures explain how to add all required managed references and packages to your project. Consider this a base set of resources that most managed code applications will need for invoking Web API operations.
Add the helper library NuGet package
The Dynamics 365 SDK Web API Helper Library contains classes to assist with supplemental operations, such as application configuration, Dynamics 365 server authentication, exception handling, and Web communication. For more information, see Use the Microsoft Dynamics 365 Web API Helper Library (C#). The use of these classes is optional, although they are used extensively in the Web API samples. The Dynamics 365 SDK Web API Helper Library is distributed in source code form as a NuGet package. Future updates will be distributed as NuGet package updates.
If you have installed the NuGet command line utility or are using the Package Manager Console in Visual Studio:
Issue the following command to install the helper library package.
Install-Package Microsoft.CrmSdk.WebApi.Samples.HelperCode
Several messages are displayed about processing dependency packages. If a License Acceptance dialog is displayed, read the license terms and click Accept.
Skip to step 6 below to confirm the installation of the helper library package.
If you have installed the NuGet Package Manager extension:
From the Project menu, select Manage NuGet Packages. The NuGet Package Manager tab is displayed.
In the upper right-hand corner, set the Package source drop-down to Nuget.org.
In the upper left-hand corner, click on Browse then enter “Dynamics 365 HelperCode” in the search box and press Enter.
Click Install. If the Preview dialog is displayed, click OK.
The License Acceptance dialog is displayed. Review the license terms and click I Accept.
Navigate to the Solution Explorer window. Confirm that a new solution folder named Web API Helper Code was added.
The Dynamics 365 SDK Web API Helper Library package, Microsoft.CrmSdk.WebApi.Samples.HelperCode, depends upon the following other packages, which are automatically downloaded and installed alongside the helper library package:
Newtonsoft.Json – contains Json.NET, a popular, MIT-licensed JSON framework for .NET.
Microsoft.IdentityModel.Clients.ActiveDirectory – contains the binaries for the Active Directory Authentication Library (ADAL), which provides authentication functionality for .NET clients.
Warning
The Dynamics 365 SDK Web API Helper Library package was built against specific versions of these other two supporting packages. Because of this, you should only directly update the helper library NuGet package. This operation will update the proper supporting packages if required. If you separately update one of these supporting packages, a newer version of that package may be incompatible with the helper library.
Verify the required assembly references
In Solution Explorer, expand the References node.
Confirm the at the following references have been added to the project.
If you have additional functionality that you routinely use in your applications, you can add the associated references to the required assemblies now. For more information, see How to: Add or Remove References by Using the Add Reference Dialog Box.
Because the Dynamics 365 Web API is based on REST principles, it does not require client-side assemblies to access. However, other APIs supported by Microsoft Dynamics 365 do require these; for more information, see Assemblies included in the Microsoft Dynamics 365 SDK.
Add typical using statements
In the Solution Explorer, open Program.cs for editing.
At the top of the file, add the following using statements, which reference namespaces commonly used in Dynamics 365 Web API-based solutions.
using Microsoft.Crm.Sdk.Samples.HelperCode; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Net.Http; using System.Net.Http.Headers;
If you added routinely used assemblies or references in the previous sections, you may also want to add corresponding using statements for these resources.
Save the file.
Add connection code
This section explains how to add a basic set of settings and instructions to perform these operations. For more information about the common code used, see Use the Microsoft Dynamics 365 Web API Helper Library (C#)
Edit the application configuration file
In Solution Explorer, open the App.config file for editing. Add the following two sections to it, after the existing <startup> section, then save the file.
<connectionStrings> <clear /> <!-- When providing a password, make sure to set the app.config file's security so that only you can read it. --> <add name="default" connectionString="Url=http://myserver/myorg/; Username=name; Password=password; Domain=domain" /> <add name="CrmOnline" connectionString="Url=https://mydomain.crm.dynamics.com/; Username=someone@mydomain.onmicrosoft.com; Password=password" /> </connectionStrings> <appSettings> <!--For information on how to register an app and obtain the ClientId and RedirectUrl values see https://msdn.microsoft.com/dynamics/crm/mt149065 --> <!--Active Directory application registration. --> <!--These are dummy values and should be replaced with your actual app registration values.--> <add key="ClientId" value="e5cf0024-a66a-4f16-85ce-99ba97a24bb2" /> <add key="RedirectUrl" value="https://localhost/SdkSample" /> <!-- Use an alternate configuration file for connection string and setting values. This optional setting enables use of an app.config file shared among multiple applications. If the specified file does not exist, this setting is ignored.--> <add key="AlternateConfig" value="C:\Temp\crmsample.exe.config"/> </appSettings>
When developing or deploying a solution, the actual connection and application registration values must be substituted for the example placeholder values. For more information, see Web API Helper code: Configuration classes.
Add code to call the helper library
Edit the Program.cs file.
Add the following property to the Program class. This property will be initialized after a successful connection to a Dynamics 365 server.
private HttpClient httpClient;
In the Main method, add the following statements.
Program app = new Program(); try { String[] arguments = Environment.GetCommandLineArgs(); app.ConnectToCRM(arguments); } catch (System.Exception ex) { ; } finally { if (app.httpClient != null) { app.httpClient.Dispose(); } }
Next add the ConnectToCRM method, which uses the helper library Configuration and Authentication classes. The following code demonstrates assigning values to the HttpClient properties so that you can successfully access the release version of the Dynamics 365 Web API.
private void ConnectToCRM(String[] cmdargs) { Configuration config = null; if (cmdargs.Length > 0) config = new FileConfiguration(cmdargs[0]); else config = new FileConfiguration(null); Authentication auth = new Authentication(config); httpClient = new HttpClient(auth.ClientHandler, true); httpClient.BaseAddress = new Uri(config.ServiceUrl + "api/data/v8.1/"); httpClient.Timeout = new TimeSpan(0, 2, 0); httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0"); httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0"); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); }
Add error-handling code
The following changes add code to catch and report exceptions, including Web API errors, to the console. If you are targeting a different environment, then modify the exception-handling code appropriately for that environment.
In Main, add the following statement to the catch block.
DisplayException(ex);
Add the corresponding method to the Program class.
private static void DisplayException(Exception ex) { Console.WriteLine("The application terminated with an error."); Console.WriteLine(ex.Message); while (ex.InnerException != null) { Console.WriteLine("\t* {0}", ex.InnerException.Message); ex = ex.InnerException; } }
Save all the files in the solution.
Next steps
At this point the solution can be built without errors. If you edit the application configuration file to supply values for your Microsoft Dynamics 365 Server, the program should also successfully connect to that server. The solution represents a skeletal frame that is ready to accept custom code, including calls to the Dynamics 365 Web API.
Tip
Before you leave this topic, consider saving your project as a project template. You can then reuse that template for future learning projects and save yourself some time and effort in setting up new projects. To do this, while your project is open in Microsoft Visual Studio, in the File menu select Export template. Follow the Export Template Wizard instructions to create the template.
See Also
Get started with the Microsoft Dynamics 365 Web API (C#)
Use the Microsoft Dynamics 365 Web API Helper Library (C#)
Perform operations using the Web API
Microsoft Dynamics 365
© 2017 Microsoft. All rights reserved. Copyright