How to do it...

To import and export data using the Data Import/Export Framework, follow these steps:

  1. Create a new project but, this time, choose Visual C# from the Templates node and then Console Application from the right. Name the project ConODataTest and place it in the project folder that we set up for source control. Ensure that the name space is also ConODataTest.
    1. We will now need to install some NuGet packages. Within Visual Studio, navigate to Tools | Nuget Package Manager | Package Manager Console.
    "NuGet is the package manager for the Microsoft development platform including .NET. The NuGet client tools provide the ability to produce and consume packages. The NuGet Gallery is the central package repository used by all package authors and consumers."      - (https://www.nuget.org/)
    1. In the Package Manager console, type the following commands:
      • Install-Package Microsoft.Bcl.Build
      • Install-Package Microsoft.Bcl
      • Install-Package Microsoft.Net.Http
      • Install-Package Microsoft.OData.Core -Version 6.15.0
      • Install-Package Simple.OData.Client -Version 4.24.0.1
      • Install-Package Microsoft.Data.OData
      • Install-Package Microsoft.OData.Client
      • Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory
    Simple.OData.Client is added as an alternative and is not used in this example. This is why the specific 6.15.0 version of Microsoft.OData.Core was used. If Simple.OData.Client is not being used, the version need not be specified.
    1. Restart Visual Studio, otherwise, the build will fail without any message as to why.
      1. Next, we will need an add-in for Visual Studio in order to read the metadata and generate types for us. Navigate to Tools | Extensions and Updates.
        1. Click on Online on the left and type OData Client Code in the Search Visual Studio Gallery text box.
          1. Select OData v4 Client Code Generator from the list and click on Download.
            1. Once installed, you will be asked to restart Visual Studio.
              1. Once restarted, choose to add a new item to the project. Select OData Client from the list. Name it OdataClient.tt and click on Add.
              A tt file is a transformation file, and its purpose will become more apparent as we progress.
              1. Toward the top of this file, you will see the following line:
              public const string MetadataDocumentUri = ""; 
              
              1. Change it so that it reads as follows:
              public const string MetadataDocumentUri = "https://usnconeboxax1aos.cloud.onebox.dynamics.com/data/$metadata"; 
              
              1. Check that you have access to https://usnconeboxax1aos.cloud.onebox.dynamics.com/ in the browser and that you can log in. Minimize (do not close) the browser and go back to Visual Studio.
                1. With the ODataClient.tt file open in the code window, click on Save or press Ctrl + S. You will receive a security warning, click on OK to proceed. This will take a few minutes to proceed, as it is a generated client and type code for all public entities.
                Once complete, you will see a new ODataClient.cs file nested under the ODataClient.tt file with many methods. The file is around 40 MB, so opening it will take a while and is best avoided.
                Should you find that Visual Studio starts to perform slowly, ensure that you have closed ODataClient.tt and ODataCilent.cs and then restart Visual Studio.
                1. We can now start writing the code for our test; add a new class to the project named ODataTest.
                  1. Add the following using statements to the top of the file:
                  using System; 
                  using System.Threading.Tasks;
                  using Microsoft.IdentityModel.Clients.ActiveDirectory;
                  using Microsoft.OData.Client;
                  using ConODataTest.Microsoft.Dynamics.DataEntities;
                  1. To simplify the process, create the follow data contract classes in order to aid passing parameters. Add them just below the using statements, and above the ODataTest class definition:
                  class ODataUserContract 
                  {
                  public string userName;
                  public string password;
                  public string domain;
                  }
                  class ODataApplicationContract
                  {
                  public string applicationId;
                  public string resource;
                  public string result;
                  }
                  public class ODataRequestContract
                  {
                  public string company;
                  }
                  We would usually use get/set methods here, but I used public variables to save space for this test.
                  1. In the class body, declare the following class variables:
                      class ODataTest 
                  {
                  public const string OAuthHeader = "Authorization";
                  public ODataUserContract userContract;
                  public ODataApplicationContract appContract;
                  public ODataRequestContract request;

                  string authenticationHeader;
                  public string response;
                  The OAuthHeader and authenticationHeader variables are key to the process of authentication with Dynamics 365 for Operations.
                  1. The code to authenticate with Azure AD is as follows:
                  private AuthenticationResult GetAuthorization() 
                  {
                  UriBuilder uri = new UriBuilder("https://login.windows.net/" + userContract.domain);

                  AuthenticationContext authenticationContext
                  = new AuthenticationContext(uri.ToString());
                  UserPasswordCredential credential = new
                  UserPasswordCredential(
                  userContract.userName, userContract.password);

                  Task<AuthenticationResult> task = authenticationContext.AcquireTokenAsync(
                  appContract.resource,
                  appContract.applicationId, credential);

                  task.Wait();
                  AuthenticationResult
                  authenticationResult = task.Result;
                  return authenticationResult;
                  }
                  1. Now, create a public method that will be called in order to log on:
                  public Boolean Authenticate() 
                  {
                  AuthenticationResult authenticationResult;
                  try
                  {
                  authenticationResult = GetAuthorization();
                  //this gets the authorization token, this
                  // must be set on the Http header for all requests
                  authenticationHeader =
                  authenticationResult.CreateAuthorizationHeader();
                  }
                  catch (Exception e)
                  {
                  response = "Authentication failed: " + e.Message;
                  return false;
                  }
                  response = "OK";
                  return true;
                  }
                  1. Each method that makes a call to Operations must set up a resources instance, which has an event handler in order to set the authentication key. This method should be written as follows:
                  private Resources MakeResources() 
                  {
                  string entityRootPath = appContract.resource + "/data";
                  Uri oDataUri = new Uri(entityRootPath,
                  UriKind.Absolute);
                  var resources = new Resources(oDataUri);
                  resources.SendingRequest2 += new
                  EventHandler<SendingRequest2EventArgs>(
                  delegate (object sender,
                  SendingRequest2EventArgs e)
                  {
                  // This event handler is needed to set
                  // the authentication code we got when
                  // we logged on.
                  e.RequestMessage.SetHeader(OAuthHeader,
                  authenticationHeader);
                  });
                  return resources;
                  }
                  1. The next three methods are to demonstrate reading, updating, and creating records through OData:
                  public System.Collections.ArrayList GetVehicleNameList() 
                  {
                  System.Collections.ArrayList vehicleNames;
                  vehicleNames = new System.Collections.ArrayList();

                  var resources = this.MakeResources();
                  resources.ConWHSVehicleTables.AddQueryOption(
                  "DataAreaId", request.company);
                  foreach (var vehicle in resources.ConWHSVehicleTables)
                  {
                  vehicleNames.Add(vehicle.Description);
                  }
                  return vehicleNames;
                  }
                  public Boolean UpdateVehicleNames()
                  {
                  var resources = this.MakeResources();
                  resources.ConWHSVehicleTables.AddQueryOption(
                  "DataAreaId", request.company);
                  foreach (var vehicle in resources.ConWHSVehicleTables)
                  {
                  vehicle.Description = vehicle.VehicleId
                  + " : OData did it";
                  resources.UpdateObject(vehicle);
                  }
                  try
                  {
                  resources.SaveChanges();
                  }
                  catch (Exception e)
                  {
                  response = e.InnerException.Message;
                  return false;
                  }
                  return true;
                  }
                  public Boolean CreateNewVehicle(
                  ConWHSVehicleTable _newVehicle)
                  {
                  var resources = this.MakeResources();
                  _newVehicle.DataAreaId = request.company;
                  resources.AddToConWHSVehicleTables(_newVehicle);
                  try
                  {
                  resources.SaveChanges();
                  }
                  catch (Exception e)
                  {
                  response = e.InnerException.Message;
                  return false;
                  }
                  return true;
                  }
                  1. Finally, we can write our main method. Open the Program.cs file and ensure that we have the following using statements at the top:
                  using System; 
                  using ConODataTest.Microsoft.Dynamics.DataEntities;
                  1. Write the main method as follows (use the application ID you generated from your Azure AD application):
                  static void Main(string[] args) 
                  {
                  ODataApplicationContract appContract;
                  appContract = new ODataApplicationContract();
                  appContract.resource = "https://usnconeboxax1aos.cloud.onebox.dynamics.com";
                  appContract.applicationId = "<your application Id>";

                  ODataUserContract userContract = new
                  ODataUserContract();
                  Console.WriteLine("Use the O365 account that you use to log in to Dynamics 365 for Operations");
                  Console.Write("O365 Username: ");
                  userContract.userName = Console.ReadLine();
                  Console.Write("O365 Password: ");
                  userContract.password = Console.ReadLine();
                  Console.WriteLine("This is your tenant, such as yourdomain.com or <yourtenant>.onmicrosoft.com");
                  Console.Write("O365 Domain: ");
                  userContract.domain = Console.ReadLine();
                  ODataTest test = new ConODataTest.ODataTest();
                  test.userContract = userContract;
                  test.appContract = appContract;
                  if (!test.Authenticate())
                  {
                  Console.WriteLine(test.response);
                  }
                  test.request = new ConODataTest.ODataRequestContract();
                  test.request.company = "USMF";
                  System.Collections.ArrayList vehicleNames = test.GetVehicleNameList();
                  foreach (var vehicleName in vehicleNames)
                  {
                  Console.WriteLine(vehicleName);
                  }

                  Console.WriteLine("Changing vehicle descriptions");
                  test.UpdateVehicleNames();

                  ConWHSVehicleTable vehicle = new ConWHSVehicleTable();

                  Console.WriteLine("Create a new Vehicle");
                  Console.Write("Vehicle Id: ");
                  vehicle.VehicleId = Console.ReadLine();
                  Console.Write("Vehicle group: ");
                  vehicle.VehicleGroupId = Console.ReadLine();
                  Console.Write("Description: ");
                  vehicle.Description = Console.ReadLine();
                  test.CreateNewVehicle(vehicle);
                  Console.WriteLine("Press enter to continue.");
                  Console.ReadLine();
                  }
                  1. To see what is going on, add some breakpoints and use the debugger and run it (press F5); don't step into code that would open ODataClient.cs; this can take a long time to open.
                  ..................Content has been hidden....................

                  You can't read the all page of ebook, please click here login for view all page.
                  Reset
                  18.116.40.177