/// <summary> /// Demonstrates how to use the Deployment Web Service to create an organization /// and poll the status of the job. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete /// all created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(serverConfig, promptforDelete); //<snippetUseAsyncDeploymentServiceMessages1> // Instantiate DeploymentServiceClient for calling the service. client = ProxyClientHelper.CreateClient( new Uri(serverConfig.DiscoveryUri.ToString() .Replace("Services", "Deployment") .Replace("Discovery", "Deployment"))); // Setting credentials from the current security context. if (serverConfig.Credentials == null) { client.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials; } else { client.ClientCredentials.Windows.ClientCredential = serverConfig.Credentials.Windows.ClientCredential; } using (client) { // Set properties for the new organization Microsoft.Xrm.Sdk.Deployment.Organization organization = new Microsoft.Xrm.Sdk.Deployment.Organization { BaseCurrencyCode = "USD", BaseCurrencyName = "US Dollar", BaseCurrencyPrecision = 2, BaseCurrencySymbol = "$", BaseLanguageCode = 1033, FriendlyName = _friendlyName, UniqueName = _uniqueName, SqlCollation = "Latin1_General_CI_AI", SqlServerName = _sqlServerName, SrsUrl = _srsUrl, SqmIsEnabled = false }; // Create a request for the deployment web service // CRM server app pool must have permissions on SQL server BeginCreateOrganizationRequest request = new BeginCreateOrganizationRequest { Organization = organization, SysAdminName = _sysAdminName }; // Execute the request BeginCreateOrganizationResponse response = (BeginCreateOrganizationResponse)client.Execute(request); // The operation is asynchronous, so the response object contains // a unique identifier for the operation Guid operationId = response.OperationId; // Retrieve the Operation using the OperationId RetrieveRequest retrieveOperationStatus = new RetrieveRequest(); retrieveOperationStatus.EntityType = DeploymentEntityType.DeferredOperationStatus; retrieveOperationStatus.InstanceTag = new EntityInstanceId { Id = operationId }; RetrieveResponse retrieveResponse; DeferredOperationStatus deferredOperationStatus; Console.WriteLine("Retrieving state of the job..."); // Retrieve the Operation State until Organization is created do { // Wait 3 secs to not overload server Thread.Sleep(3000); retrieveResponse = (RetrieveResponse)client.Execute(retrieveOperationStatus); deferredOperationStatus = ((DeferredOperationStatus)retrieveResponse.Entity); } while (deferredOperationStatus.State != DeferredOperationState.Processing && deferredOperationStatus.State != DeferredOperationState.Completed); // Poll OrganizationStatusRequest RetrieveRequest retrieveReqServer = new RetrieveRequest(); retrieveReqServer.EntityType = DeploymentEntityType.Organization; retrieveReqServer.InstanceTag = new EntityInstanceId(); retrieveReqServer.InstanceTag.Name = organization.UniqueName; RetrieveResponse retrieveRespServer; OrganizationState orgState; Console.WriteLine("Retrieving state of the organization..."); // Retrieve and check the Organization State until is enabled do { retrieveRespServer = (RetrieveResponse)client.Execute(retrieveReqServer); _organizationID = ((Microsoft.Xrm.Sdk.Deployment.Organization)retrieveRespServer.Entity).Id; orgState = ((Microsoft.Xrm.Sdk.Deployment.Organization)retrieveRespServer.Entity).State; // Wait 5 secs to not overload server Thread.Sleep(5000); } while (orgState != OrganizationState.Enabled); Console.WriteLine("Organization has been created!"); //</snippetUseAsyncDeploymentServiceMessages1> DeleteRequiredRecords(promptforDelete); } } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Demonstrates how to use the Deployment Web Service to create an organization /// and poll the status of the job. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete /// all created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(serverConfig, promptforDelete); // Instantiate DeploymentServiceClient for calling the service. client = ProxyClientHelper.CreateClient( new Uri(serverConfig.DiscoveryUri.ToString() .Replace("Services", "Deployment") .Replace("Discovery", "Deployment"))); // Setting credentials from the current security context. if (serverConfig.Credentials == null) { client.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials; } else { client.ClientCredentials.Windows.ClientCredential = serverConfig.Credentials.Windows.ClientCredential; } using (client) { // Set properties for the new organization Microsoft.Xrm.Sdk.Deployment.Organization organization = new Microsoft.Xrm.Sdk.Deployment.Organization { BaseCurrencyCode = "USD", BaseCurrencyName = "US Dollar", BaseCurrencyPrecision = 2, BaseCurrencySymbol = "$", BaseLanguageCode = 1033, FriendlyName = _friendlyName, UniqueName = _uniqueName, SqlCollation = "Latin1_General_CI_AI", SqlServerName = _sqlServerName, SrsUrl = _srsUrl, SqmIsEnabled = false }; // Create a request for the deployment web service // CRM server app pool must have permissions on SQL server BeginCreateOrganizationRequest request = new BeginCreateOrganizationRequest { Organization = organization, SysAdminName = _sysAdminName }; // Execute the request BeginCreateOrganizationResponse response = (BeginCreateOrganizationResponse)client.Execute(request); // The operation is asynchronous, so the response object contains // a unique identifier for the operation Guid operationId = response.OperationId; // Retrieve the Operation using the OperationId RetrieveRequest retrieveOperationStatus = new RetrieveRequest(); retrieveOperationStatus.EntityType = DeploymentEntityType.DeferredOperationStatus; retrieveOperationStatus.InstanceTag = new EntityInstanceId { Id = operationId }; RetrieveResponse retrieveResponse; DeferredOperationStatus deferredOperationStatus; Console.WriteLine("Retrieving state of the job..."); // Retrieve the Operation State until Organization is created do { // Wait 3 secs to not overload server Thread.Sleep(3000); retrieveResponse = (RetrieveResponse)client.Execute(retrieveOperationStatus); deferredOperationStatus = ((DeferredOperationStatus)retrieveResponse.Entity); }while (deferredOperationStatus.State != DeferredOperationState.Processing && deferredOperationStatus.State != DeferredOperationState.Completed); // Poll OrganizationStatusRequest RetrieveRequest retrieveReqServer = new RetrieveRequest(); retrieveReqServer.EntityType = DeploymentEntityType.Organization; retrieveReqServer.InstanceTag = new EntityInstanceId(); retrieveReqServer.InstanceTag.Name = organization.UniqueName; RetrieveResponse retrieveRespServer; OrganizationState orgState; Console.WriteLine("Retrieving state of the organization..."); // Retrieve and check the Organization State until is enabled do { retrieveRespServer = (RetrieveResponse)client.Execute(retrieveReqServer); _organizationID = ((Microsoft.Xrm.Sdk.Deployment.Organization)retrieveRespServer.Entity).Id; orgState = ((Microsoft.Xrm.Sdk.Deployment.Organization)retrieveRespServer.Entity).State; // Wait 5 secs to not overload server Thread.Sleep(5000); }while (orgState != OrganizationState.Enabled); Console.WriteLine("Organization has been created!"); DeleteRequiredRecords(promptforDelete); } } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// /// </summary> /// <param name="org"></param> /// <param name="sysAdminName">domain\\user</param> public void CreateOrganization(Organization org, string sysAdminName) { try { var service = _crmServiceProvider.GetDeploymentService(); using (service as IDisposable) { // var request = new BeginCreateOrganizationRequest { Organization = org, SysAdminName = sysAdminName }; // Execute the request // upgradeLog.WriteInformation("Creating new Crm Organisation: {0}", org.UniqueName); var response = (BeginCreateOrganizationResponse)service.Execute(request); // The operation is asynchronous, so the response object contains // a unique identifier for the operation Guid operationId = response.OperationId; // Retrieve the Operation using the OperationId var retrieveOperationStatus = new RetrieveRequest(); retrieveOperationStatus.EntityType = DeploymentEntityType.DeferredOperationStatus; retrieveOperationStatus.InstanceTag = new EntityInstanceId { Id = operationId }; DeferredOperationStatus deferredOperationStatus; // _upgradeLog.WriteInformation("Retrieving state of the create organisation job..."); // Retrieve the Operation State until Organization is created do { // Wait 3 secs to not overload server Thread.Sleep(3000); var retrieveResponse = (RetrieveResponse)service.Execute(retrieveOperationStatus); deferredOperationStatus = ((DeferredOperationStatus)retrieveResponse.Entity); } while (deferredOperationStatus.State != DeferredOperationState.Processing && deferredOperationStatus.State != DeferredOperationState.Completed); // Poll OrganizationStatusRequest var retrieveReqServer = new RetrieveRequest(); retrieveReqServer.EntityType = DeploymentEntityType.Organization; retrieveReqServer.InstanceTag = new EntityInstanceId(); retrieveReqServer.InstanceTag.Name = org.UniqueName; Microsoft.Xrm.Sdk.Deployment.OrganizationState orgState; // upgradeLog.WriteInformation("Retrieving state of the organization..."); // Retrieve and check the Organization State until is enabled RetrieveResponse resp = null; do { resp = (RetrieveResponse)service.Execute(retrieveReqServer); // orgId = ((Microsoft.Xrm.Sdk.Deployment.Organization)retrieveRespServer.Entity).Id; orgState = ((Organization)resp.Entity).State; // Wait 5 secs to not overload server Thread.Sleep(5000); } while (orgState != OrganizationState.Enabled && orgState != OrganizationState.Failed); if (orgState == OrganizationState.Enabled) { // upgradeLog.WriteInformation("Organization has been created!"); } else { // upgradeLog.WriteInformation("The organization create operation failed.!"); throw new Exception("The organization create operation failed.!"); } } } catch (FaultException<OrganizationServiceFault> ex) { Debug.WriteLine(ex.Message); //upgradeLog.WriteError("The application encountered an error."); //upgradeLog.WriteError("Timestamp: {0}", ex.Detail.Timestamp); //upgradeLog.WriteError("Code: {0}", ex.Detail.ErrorCode); //upgradeLog.WriteError("Message: {0}", ex.Detail.Message); //upgradeLog.WriteError("Plugin Trace: {0}", ex.Detail.TraceText); //upgradeLog.WriteError("Inner Fault: {0}", // null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"); throw; } catch (TimeoutException ex) { Debug.WriteLine(ex.Message); //upgradeLog.WriteError("The application encountered an error.."); //upgradeLog.WriteError("Message: {0}", ex.Message); //upgradeLog.WriteError("Stack Trace: {0}", ex.StackTrace); //upgradeLog.WriteError("Inner Fault: {0}", string.IsNullOrEmpty(ex.InnerException.Message) ? "No Inner Fault" : ex.InnerException.Message); throw; } catch (Exception ex) { //upgradeLog.WriteError("The application encountered an error."); //upgradeLog.WriteError(ex.Message); // Display the details of the inner exception. if (ex.InnerException != null) { // upgradeLog.WriteError(ex.InnerException.Message); var fe = ex.InnerException as FaultException<OrganizationServiceFault>; if (fe != null) { // upgradeLog.WriteError("Timestamp: {0}", fe.Detail.Timestamp); // upgradeLog.WriteError("Code: {0}", fe.Detail.ErrorCode); // upgradeLog.WriteError("Message: {0}", fe.Detail.Message); // upgradeLog.WriteError("Plugin Trace: {0}", fe.Detail.TraceText); // upgradeLog.WriteError("Inner Fault: {0}", // null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"); } } throw; } // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException, // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException. }
private void CreateOrganization() { if (string.IsNullOrWhiteSpace(this.DeploymentUrl) || !Uri.IsWellFormedUriString(this.DeploymentUrl, UriKind.Absolute)) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "The Deployment service URL is not valid. {0}", this.DeploymentUrl)); return; } if (string.IsNullOrWhiteSpace(this.Name)) { Log.LogError("Missing required parameter: Name"); return; } if (string.IsNullOrWhiteSpace(this.DisplayName)) { Log.LogError("Missing required parameter: Display Name"); return; } if (string.IsNullOrWhiteSpace(this.SqlServerInstance)) { Log.LogError("Missing required parameter: Sql Server Instance"); return; } if (string.IsNullOrWhiteSpace(this.SsrsUrl) || !Uri.IsWellFormedUriString(this.SsrsUrl, UriKind.Absolute)) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "The Sql Server Reporting Service URL is not valid. {0}", this.SsrsUrl)); return; } Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Connecting to the deployment service {0}.", this.DeploymentUrl)); using (var service = ProxyClientHelper.CreateClient(new Uri(this.DeploymentUrl))) { var newOrganization = new Microsoft.Xrm.Sdk.Deployment.Organization { FriendlyName = this.DisplayName, UniqueName = this.Name, SqlServerName = this.SqlServerInstance, SrsUrl = this.SsrsUrl }; try { var request = new BeginCreateOrganizationRequest { Organization = newOrganization }; var response = service.Execute(request) as BeginCreateOrganizationResponse; if (response == null) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "No response was received while creating Organization {0}", this.Name)); return; } var operationId = new EntityInstanceId { Id = response.OperationId }; int waitCount = 0; var organizationCreationStatus = service.Retrieve(DeploymentEntityType.DeferredOperationStatus, operationId) as DeferredOperationStatus; // Wait for the organization to be created. Checking the stauts repeatedly while (organizationCreationStatus != null && (organizationCreationStatus.State == DeferredOperationState.Processing || organizationCreationStatus.State == DeferredOperationState.Queued)) { Thread.Sleep(WaitIntervalInMilliseconds); Log.LogMessage(MessageImportance.High, "Processing..."); organizationCreationStatus = service.Retrieve(DeploymentEntityType.DeferredOperationStatus, operationId) as DeferredOperationStatus; if (++waitCount > this.Timeout) { break; } } if (waitCount >= this.Timeout) { Log.LogMessage(MessageImportance.High, string.Format(CultureInfo.CurrentCulture, "Your request for creation of Organization {0} is still being processed but the task has exceeded its timeout value of {1} minutes.", this.Name, this.Timeout)); } else { Log.LogMessage(MessageImportance.High, string.Format(CultureInfo.CurrentCulture, "The Organization {0} was created successfully.", this.Name)); } } catch (Exception exception) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "An error occurred while creating Organization {0}. [{1}]", this.Name, exception.Message)); } } }
/// <summary> /// /// </summary> /// <param name="org"></param> /// <param name="sysAdminName">domain\\user</param> public void CreateOrganization(Organization org, string sysAdminName) { try { var service = _crmServiceProvider.GetDeploymentService(); using (service as IDisposable) { // var request = new BeginCreateOrganizationRequest { Organization = org, SysAdminName = sysAdminName }; // Execute the request // upgradeLog.WriteInformation("Creating new Crm Organisation: {0}", org.UniqueName); var response = (BeginCreateOrganizationResponse)service.Execute(request); // The operation is asynchronous, so the response object contains // a unique identifier for the operation Guid operationId = response.OperationId; // Retrieve the Operation using the OperationId var retrieveOperationStatus = new RetrieveRequest(); retrieveOperationStatus.EntityType = DeploymentEntityType.DeferredOperationStatus; retrieveOperationStatus.InstanceTag = new EntityInstanceId { Id = operationId }; DeferredOperationStatus deferredOperationStatus; // _upgradeLog.WriteInformation("Retrieving state of the create organisation job..."); // Retrieve the Operation State until Organization is created do { // Wait 3 secs to not overload server Thread.Sleep(3000); var retrieveResponse = (RetrieveResponse)service.Execute(retrieveOperationStatus); deferredOperationStatus = ((DeferredOperationStatus)retrieveResponse.Entity); }while (deferredOperationStatus.State != DeferredOperationState.Processing && deferredOperationStatus.State != DeferredOperationState.Completed); // Poll OrganizationStatusRequest var retrieveReqServer = new RetrieveRequest(); retrieveReqServer.EntityType = DeploymentEntityType.Organization; retrieveReqServer.InstanceTag = new EntityInstanceId(); retrieveReqServer.InstanceTag.Name = org.UniqueName; Microsoft.Xrm.Sdk.Deployment.OrganizationState orgState; // upgradeLog.WriteInformation("Retrieving state of the organization..."); // Retrieve and check the Organization State until is enabled RetrieveResponse resp = null; do { resp = (RetrieveResponse)service.Execute(retrieveReqServer); // orgId = ((Microsoft.Xrm.Sdk.Deployment.Organization)retrieveRespServer.Entity).Id; orgState = ((Organization)resp.Entity).State; // Wait 5 secs to not overload server Thread.Sleep(5000); }while (orgState != OrganizationState.Enabled && orgState != OrganizationState.Failed); if (orgState == OrganizationState.Enabled) { // upgradeLog.WriteInformation("Organization has been created!"); } else { // upgradeLog.WriteInformation("The organization create operation failed.!"); throw new Exception("The organization create operation failed.!"); } } } catch (FaultException <OrganizationServiceFault> ex) { Debug.WriteLine(ex.Message); //upgradeLog.WriteError("The application encountered an error."); //upgradeLog.WriteError("Timestamp: {0}", ex.Detail.Timestamp); //upgradeLog.WriteError("Code: {0}", ex.Detail.ErrorCode); //upgradeLog.WriteError("Message: {0}", ex.Detail.Message); //upgradeLog.WriteError("Plugin Trace: {0}", ex.Detail.TraceText); //upgradeLog.WriteError("Inner Fault: {0}", // null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"); throw; } catch (TimeoutException ex) { Debug.WriteLine(ex.Message); //upgradeLog.WriteError("The application encountered an error.."); //upgradeLog.WriteError("Message: {0}", ex.Message); //upgradeLog.WriteError("Stack Trace: {0}", ex.StackTrace); //upgradeLog.WriteError("Inner Fault: {0}", string.IsNullOrEmpty(ex.InnerException.Message) ? "No Inner Fault" : ex.InnerException.Message); throw; } catch (Exception ex) { //upgradeLog.WriteError("The application encountered an error."); //upgradeLog.WriteError(ex.Message); // Display the details of the inner exception. if (ex.InnerException != null) { // upgradeLog.WriteError(ex.InnerException.Message); var fe = ex.InnerException as FaultException <OrganizationServiceFault>; if (fe != null) { // upgradeLog.WriteError("Timestamp: {0}", fe.Detail.Timestamp); // upgradeLog.WriteError("Code: {0}", fe.Detail.ErrorCode); // upgradeLog.WriteError("Message: {0}", fe.Detail.Message); // upgradeLog.WriteError("Plugin Trace: {0}", fe.Detail.TraceText); // upgradeLog.WriteError("Inner Fault: {0}", // null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"); } } throw; } // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException, // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException. }