public void Test_CreateOrganization() { const string organizationName = "TestIntegration"; using (var eventStream = new Subject <BuildEvent>()) using (var client = ProxyClientHelper.CreateClient(new Uri(DeploymentServiceUrl))) { eventStream.Subscribe(e => TestContext.WriteLine($"[{e.Type.ToString()}] [{e.Importance.ToString()}] {e.Message}")); if (client.ClientCredentials != null) { client.ClientCredentials.Windows.ClientCredential = _credential; } client.CreateOrganizationAsync( new Organization { BaseCurrencyCode = "GBP", BaseCurrencyName = "Pound Sterling", BaseCurrencyPrecision = 2, BaseCurrencySymbol = "£", BaseLanguageCode = 1033, FriendlyName = organizationName, UniqueName = organizationName, SqlCollation = "Latin1_General_CI_AI", SqlServerName = "fct-ci-crm-01", SrsUrl = "http://fct-ci-crm-01/reportserver", SqmIsEnabled = false }, eventStream).Wait(); var exists = client.OrganizationExists(organizationName).Result; Assert.IsTrue(exists); } }
private static void GetOrganizationInfo(string organizationName, string organizationServiceUrl) { var crmUrl = ConfigurationManager.AppSettings["CrmUrl"]; var uri = new Uri(crmUrl + "/XRMDeployment/2011/Deployment.svc"); var deploymentService = ProxyClientHelper.CreateClient(uri); deploymentService.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials; var orgRetRequest = new RetrieveRequest(); orgRetRequest.EntityType = DeploymentEntityType.Organization; orgRetRequest.InstanceTag = new EntityInstanceId(); orgRetRequest.InstanceTag.Name = organizationName; try { var response = (RetrieveResponse)deploymentService.Execute(orgRetRequest); Console.WriteLine("---------------" + organizationName + "---------------"); Console.WriteLine("State: " + ((Organization)response.Entity).State.ToString()); Console.WriteLine("Version: " + ((Organization)response.Entity).Version); GetSolutionsInfo(organizationServiceUrl); } catch (Exception ex) { Console.WriteLine("Unable to get organization solutions info." + Environment.NewLine + ex.ToString()); } }
public void Test_DisableOrganization_And_DeleteOrganization() { const string organizationName = "TestIntegration"; using (var eventStream = new Subject <BuildEvent>()) using (var client = ProxyClientHelper.CreateClient(new Uri(DeploymentServiceUrl))) { eventStream.Subscribe(e => TestContext.WriteLine($"[{e.Type.ToString()}] [{e.Importance.ToString()}] {e.Message}")); if (client.ClientCredentials != null) { client.ClientCredentials.Windows.ClientCredential = _credential; } client.DisableOrganizationAsync(organizationName, eventStream).Wait(); client.DeleteOrganizationAsync(organizationName, eventStream).Wait(); var exists = client.OrganizationExists(organizationName).Result; Assert.IsFalse(exists); } }
protected virtual DeploymentServiceClient ToDeploymentServiceClient(CrmConnection connection) { var uri = connection.ServiceUri; var fullServiceUri = uri.AbsolutePath.EndsWith(_servicePath, StringComparison.OrdinalIgnoreCase) ? uri : new Uri(uri, uri.AbsolutePath.TrimEnd('/') + _servicePath); var service = connection.Timeout != null ? ProxyClientHelper.CreateClient(fullServiceUri, connection.Timeout.Value) : ProxyClientHelper.CreateClient(fullServiceUri); var clientCredentials = connection.ClientCredentials; if (clientCredentials != null) { service.ClientCredentials.Windows.ClientCredential = clientCredentials.Windows.ClientCredential; service.ClientCredentials.UserName.UserName = clientCredentials.UserName.UserName; service.ClientCredentials.UserName.Password = clientCredentials.UserName.Password; } return(service); }
/// <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> /// This method first connects to the Deployment service. Then, /// uses RetrieveRequest, UpdateRequest and UpdateAdvancedSettingsRequest. /// </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)) { // Instantiate DeploymentServiceClient for calling the service. DeploymentServiceClient serviceClient = ProxyClientHelper.CreateClient( new Uri(serverConfig.DiscoveryUri.ToString() .Replace("Services", "Deployment") .Replace("Discovery", "Deployment"))); // Setting credentials from the current security context. if (serverConfig.Credentials != null) { serviceClient.ClientCredentials.Windows.ClientCredential = serverConfig.Credentials.Windows.ClientCredential; } else { serviceClient.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials; } #region RetrieveRequest // Retrieve all servers available in the deployment Console.WriteLine("\nRetrieving list of servers...\n"); var servers = serviceClient.RetrieveAll(DeploymentEntityType.Server); // Print list of all retrieved servers. Console.WriteLine("Servers in your deployment"); Console.WriteLine("================================"); foreach (var server in servers) { Console.WriteLine(server.Name); } Console.WriteLine("<End of Listing>"); Console.WriteLine(); // Retrieve details of first (other than current server) or default server from previous call. var serverId = servers.FirstOrDefault(x => x.Name.ToLowerInvariant() != serverConfig.ServerAddress.ToLowerInvariant()); // If no other server exists then default to existing one. if (serverId == null) { serverId = servers.FirstOrDefault(); } Console.WriteLine("\nRetrieving details of one server...\n"); RetrieveRequest retrieveReqServer = new RetrieveRequest(); retrieveReqServer.EntityType = DeploymentEntityType.Server; retrieveReqServer.InstanceTag = serverId; RetrieveResponse retrieveRespServer = (RetrieveResponse)serviceClient.Execute(retrieveReqServer); Server serverToUpdate = (Server)retrieveRespServer.Entity; Console.WriteLine("================================"); Console.WriteLine("Name: " + serverToUpdate.Name); Console.WriteLine("State: " + serverToUpdate.State); Console.WriteLine(); #endregion RetrieveRequest #region UpdateRequest // Avoid updating current server as it would disrupt the further sample execution. if (servers.Count > 1) { // Modified the property we want to update serverToUpdate.State = ServerState.Disabled; // Update the deployment record Console.WriteLine("\nUpdating server...\n"); UpdateRequest updateReq = new UpdateRequest(); updateReq.Entity = serverToUpdate; UpdateResponse uptRes = (UpdateResponse)serviceClient.Execute(updateReq); // Retrieve server details again to check if it is updated RetrieveResponse retrieveRespServerUpdated = (RetrieveResponse)serviceClient.Execute(retrieveReqServer); Server serverUpdated = (Server)retrieveRespServerUpdated.Entity; Console.WriteLine("Server Updated"); Console.WriteLine("================================"); Console.WriteLine("Name: " + serverUpdated.Name); Console.WriteLine("State: " + serverUpdated.State); Console.WriteLine(); // Revert change serverUpdated.State = ServerState.Enabled; Console.WriteLine("\nReverting change made in server...\n"); UpdateRequest updateReqRevert = new UpdateRequest(); updateReqRevert.Entity = serverUpdated; UpdateResponse uptResRev = (UpdateResponse)serviceClient.Execute(updateReqRevert); RetrieveResponse retrieveRespServerReverted = (RetrieveResponse)serviceClient.Execute(retrieveReqServer); Server serverReverted = (Server)retrieveRespServerReverted.Entity; Console.WriteLine("Server Reverted"); Console.WriteLine("================================"); Console.WriteLine("Name: " + serverReverted.Name); Console.WriteLine("State: " + serverReverted.State); Console.WriteLine(); } else { Console.WriteLine("\nMulti-server environment missing." + "\nSkipping server update request to avoid disruption in the sample execution."); } #endregion UpdateRequest #region UpdateAdvanceRequest // Retrieve Advanced Settings for your organization. Console.WriteLine("\nRetrieving Advanced Settings...\n"); RetrieveAdvancedSettingsRequest requestAdvSettings = new RetrieveAdvancedSettingsRequest { ConfigurationEntityName = "Deployment", ColumnSet = new ColumnSet("Id") }; ConfigurationEntity configuration = ((RetrieveAdvancedSettingsResponse) serviceClient.Execute(requestAdvSettings)).Entity; // Print out all advanced settings where IsWritable==true. Console.WriteLine("Advanced deployment settings that can be updated"); Console.WriteLine("================================================"); foreach (var setting in configuration.Attributes) { if (setting.Key != "Id") { Console.WriteLine( String.Format("{0}: {1}", setting.Key, setting.Value)); } } Console.WriteLine(); // Create the Configuration Entity with the values to update ConfigurationEntity configEntity = new ConfigurationEntity(); configEntity.LogicalName = "Deployment"; configEntity.Attributes = new AttributeCollection(); configEntity.Attributes.Add (new KeyValuePair <string, object> ("AutomaticallyInstallDatabaseUpdates", true)); // Update Advanced Settings Console.WriteLine("\nUpdating Advanced Settings...\n"); UpdateAdvancedSettingsRequest updateAdvanceReq = new UpdateAdvancedSettingsRequest(); updateAdvanceReq.Entity = configEntity; serviceClient.Execute(updateAdvanceReq); // Retrieve Advanced Settings to check if they have been updated ConfigurationEntity configurationUpdated = ((RetrieveAdvancedSettingsResponse) serviceClient.Execute(requestAdvSettings)).Entity; Console.WriteLine("Advanced deployment settings updated"); Console.WriteLine("================================================"); foreach (var setting in configurationUpdated.Attributes) { if (setting.Key != "Id") { Console.WriteLine( String.Format("{0}: {1}", setting.Key, setting.Value)); } } Console.WriteLine(); // Revert change ConfigurationEntity entityRevert = new ConfigurationEntity(); entityRevert.LogicalName = "Deployment"; entityRevert.Attributes = new AttributeCollection(); entityRevert.Attributes.Add (new KeyValuePair <string, object> ("AutomaticallyInstallDatabaseUpdates", false)); Console.WriteLine("\nReverting Advanced Settings...\n"); UpdateAdvancedSettingsRequest requestRevert = new UpdateAdvancedSettingsRequest(); requestRevert.Entity = entityRevert; serviceClient.Execute(requestRevert); ConfigurationEntity configurationReverted = ((RetrieveAdvancedSettingsResponse) serviceClient.Execute(requestAdvSettings)).Entity; Console.WriteLine("Advanced deployment settings reverted"); Console.WriteLine("================================================"); foreach (var setting in configurationReverted.Attributes) { if (setting.Key != "Id") { Console.WriteLine( String.Format("{0}: {1}", setting.Key, setting.Value)); } } Console.WriteLine(); #endregion UpdateAdvanceRequest } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <DeploymentServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Reprovisions the Xrm Organisation by dropping the database and re-creating the organisation /// </summary> /// <param name="eventStream">The Build Event stream</param> /// <param name="crmDb">An object representing the CRM Database</param> /// <param name="credential">The Network Credential to use on the CRM deployment client.</param> /// <returns>The async <see cref="Task"/> unit of work.</returns> private async Task Reprovision(IObserver <BuildEvent> eventStream, CrmDatabase crmDb, NetworkCredential credential) { using (var client = ProxyClientHelper.CreateClient(new Uri(DeploymentServiceUrl))) { if (client.ClientCredentials != null) { client.ClientCredentials.Windows.ClientCredential = credential; } var crmDatabaseName = OrganizationUniqueName + "_MSCRM"; try { if (await client.OrganizationExists(OrganizationUniqueName)) { await client.DisableOrganizationAsync(OrganizationUniqueName, eventStream); await client.DeleteOrganizationAsync(OrganizationUniqueName, eventStream); } else { eventStream.OnNext(new BuildEvent(BuildEventType.Warning, BuildEventImportance.Medium, $"The Organization {OrganizationUniqueName} doesn't exist in the CRM server. Is this intentional?")); } if (await crmDb.DatabaseExists(crmDatabaseName)) { await crmDb.DropDatabaseAsync(crmDatabaseName, eventStream); } else { eventStream.OnNext(new BuildEvent(BuildEventType.Warning, BuildEventImportance.Medium, $"The Organization Database {crmDatabaseName} doesn't exist in the SQL Server. Is this intentional?")); } await client.CreateOrganizationAsync( new Organization { BaseCurrencyCode = OrganizationBaseCurrencyCode, BaseCurrencyName = OrganizationBaseCurrencyName, BaseCurrencyPrecision = OrganizationBaseCurrencyPrecision, BaseCurrencySymbol = OrganizationBaseCurrencySymbol, BaseLanguageCode = OrganizationBaseLanguageCode, UniqueName = OrganizationUniqueName, FriendlyName = OrganizationFriendlyName, SqlCollation = SqlCollation, SqlServerName = SqlServerName.Replace(".cloudapp.net", ""), SrsUrl = SsrsUrl, SqmIsEnabled = SqmIsEnabled }, eventStream); } catch (AggregateException ex) { var fault = ex.InnerExceptions.First() as FaultException <DeploymentServiceFault>; if (fault == null) { throw ex.InnerExceptions.First(); } dynamic clunkyCast = fault.Detail.ErrorDetails; foreach (KeyValuePair <string, object> p in clunkyCast) { eventStream.OnNext(new BuildEvent(BuildEventType.Error, BuildEventImportance.High, $"{p.Key} : {p.Value}")); } } } }
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)); } } }