private HttpClient httpClient; // Client to CRM server communication /// <summary> /// Primary method that demonstrates the Data Export Service API. /// </summary> public async Task RunAsync() { //HttpRequestMessage request; //HttpResponseMessage response; string myOrgUrl = "https://crmue.crm.dynamics.com/"; //Dynamics 365 organization URL string myOrgId = "883278f5-07af-45eb-a0bc-3fea67caa544"; //Dynamics 365 organization ID //Call a method just to confirm connection var response = httpClient.GetAsync("WhoAmI", HttpCompletionOption.ResponseHeadersRead).Result; if (response.IsSuccessStatusCode) { //Get the response content and parse it. JObject body = JObject.Parse(response.Content.ReadAsStringAsync().Result); Guid userId = (Guid)body["UserId"]; Console.WriteLine("Your system user ID is: {0}", userId); } else { Console.WriteLine("The WhoAmI request failed with a status of '{0}'", response.ReasonPhrase); } //Use the metadata API to obtain a connector instance to your Dynamics 365 service. DataExportSalesClient discoveryClient = new DataExportSalesClient(); ConnectorDetailResponse connResponse = (ConnectorDetailResponse)discoveryClient. Metadata.GetConnectorDetailsAsync(myOrgUrl, myOrgId).Result; if (connResponse == null) { Console.Write("Failed to obtain a connector instance from the discovery service!"); throw new NullReferenceException("ConnectorDetailResponse is null!"); } //Use the connector to perform profile operations via the profiles API. //First, create another client instance, but now using the discovered connector URL. DataExportSalesClient salesClient = new DataExportSalesClient(new Uri(connResponse.ConnectorUrl)); //Then obtain the collection of sales profiles. Profiles salesProfiles = new Profiles(salesClient); //With this client, can work with an existing Data Export profile. salesProfiles.Activate("SalesExport1"); ProfileDetailsDTO salesProfile1 = (ProfileDetailsDTO)salesProfiles.GetProfileById("SalesExport1"); //Or can create new Data Export profile. ProfileDetailsDTO salesProfile2 = (ProfileDetailsDTO)salesProfiles.CreateProfile(new DataExportSales.Models.ProfileDescriptionBase() { DestinationKeyVaultUri = "https://mykv.vault.azure.net:443/secrets/SampleDataExportSecret/f593bcd8f3b8461584935e0a3e7325dd;", Name = "SalesExport1" //... }); //Test the new profile. object testResult = salesProfiles.GetTestResultById(salesProfile1.Id); //Activate the new profile. salesProfiles.Activate(salesProfile1.Id); }
/// <param name='organizationUrl'> /// Required. Organization URL /// </param> /// <param name='organizationId'> /// Required. Organization Id /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task <HttpOperationResponse <object> > GetConnectorDetailsWithOperationResponseAsync(string organizationUrl, string organizationId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Validate if (organizationUrl == null) { throw new ArgumentNullException("organizationUrl"); } if (organizationId == null) { throw new ArgumentNullException("organizationId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("organizationUrl", organizationUrl); tracingParameters.Add("organizationId", organizationId); ServiceClientTracing.Enter(invocationId, this, "GetConnectorDetailsAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/crm/exporter/metadata/connector"; List <string> queryParameters = new List <string>(); queryParameters.Add("organizationUrl=" + Uri.EscapeDataString(organizationUrl)); queryParameters.Add("organizationId=" + Uri.EscapeDataString(organizationId)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.BadRequest && statusCode != HttpStatusCode.Unauthorized && statusCode != HttpStatusCode.Forbidden && statusCode != HttpStatusCode.InternalServerError) { HttpOperationException <object> ex = new HttpOperationException <object>(); ex.Request = httpRequest; ex.Response = httpResponse; ex.Body = null; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result HttpOperationResponse <object> result = new HttpOperationResponse <object>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == HttpStatusCode.OK) { ConnectorDetailResponse resultModel = new ConnectorDetailResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null) { resultModel.DeserializeJson(responseDoc); } result.Body = resultModel; } if (statusCode == HttpStatusCode.BadRequest || statusCode == HttpStatusCode.InternalServerError) { ErrorResponse resultModel = new ErrorResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null) { resultModel.DeserializeJson(responseDoc); } result.Body = resultModel; } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return(result); }