Exemplo n.º 1
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                ConfigurationEntity entity = new ConfigurationEntity();
                entity.LogicalName = "Deployment";
                entity.Attributes  = new Microsoft.Xrm.Sdk.Deployment.AttributeCollection();
                entity.Attributes.Add(new KeyValuePair <string, object>("AggregateQueryRecordLimit", numericUpDownAggregateQueryRecordLimit.Text));
                entity.Attributes.Add(new KeyValuePair <string, object>("AutomaticallyInstallDatabaseUpdates", checkBoxAutomaticallyInstallDatabaseUpdates.Checked));
                entity.Attributes.Add(new KeyValuePair <string, object>("AutomaticallyReprovisionLanguagePacks", checkBoxAutomaticallyReprovisionLanguagePacks.Checked));

                UpdateAdvancedSettingsRequest request2 = new UpdateAdvancedSettingsRequest();
                request2.Entity = entity;
                serviceClient.Execute(request2);
                toolStripStatusLabel1.Text = "Deployment Properties were successfully saved.";
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                //string url = connection.ServerAddress + "main.aspx?pagetype=entityrecord&etn=eaf_contrat_client&id=" + entity.Id.ToString();
                LogManager.WriteLog("Error: " + ex.Detail.Message + "\n" + ex.Detail.TraceText);
                MessageBox.Show("Error: " + ex.Detail.Message + "\n" + ex.Detail.TraceText);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                    MessageBox.Show("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                }
                else
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                    MessageBox.Show("Error:" + ex.Message);
                }
            }
        }
        /// <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;
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Creates a new Organization in CRM.
        /// </summary>
        /// <param name="client">The <see cref="DeploymentServiceClient"/> that we are using to call CRM.</param>
        /// <param name="organization">The <see cref="Organization"/> model object containing all the information about the new organization.</param>
        /// <param name="eventStream">The Rx event stream used to push build events onto.</param>
        public static async Task CreateOrganizationAsync(this DeploymentServiceClient client, Organization organization, IObserver <BuildEvent> eventStream)
        {
            var operationId = await Task.Factory.StartNew(() =>
                                                          ((BeginCreateOrganizationResponse)client.Execute(new BeginCreateOrganizationRequest {
                Organization = organization
            })).OperationId);

            eventStream.OnNext(new BuildEvent(BuildEventType.Information, BuildEventImportance.Low, $"Started the Request for Creating the Organisation : {organization.FriendlyName}"));

            var retrieveOperationStatus =
                new RetrieveRequest
            {
                EntityType  = DeploymentEntityType.DeferredOperationStatus,
                InstanceTag = new EntityInstanceId {
                    Id = operationId
                }
            };

            DeferredOperationStatus deferredOperationStatus = null;

            eventStream.OnNext(new BuildEvent(BuildEventType.Information, BuildEventImportance.Low, $"Trying to Create the Organisation {organization.FriendlyName} [In Progress]"));

            do
            {
                await Task.Factory.StartNew(() => deferredOperationStatus = (DeferredOperationStatus)((RetrieveResponse)client.Execute(retrieveOperationStatus)).Entity);

                await Task.Delay(CrmPoolingInterval);

                eventStream.OnNext(new BuildEvent(BuildEventType.Information, BuildEventImportance.Low, $"Waiting for {organization.FriendlyName} to be created."));
            } while (deferredOperationStatus.State != DeferredOperationState.Processing &&
                     deferredOperationStatus.State != DeferredOperationState.Completed);

            var retrieveReqServer =
                new RetrieveRequest
            {
                EntityType  = DeploymentEntityType.Organization,
                InstanceTag = new EntityInstanceId {
                    Name = organization.UniqueName
                }
            };

            var orgState = OrganizationState.Pending;

            eventStream.OnNext(new BuildEvent(BuildEventType.Information, BuildEventImportance.Low, $"Checking that the Organisation {organization.FriendlyName} is Enabled [In Progress]"));

            do
            {
                await Task.Factory.StartNew(() => orgState = ((Organization)((RetrieveResponse)client.Execute(retrieveReqServer)).Entity).State);

                await Task.Delay(CrmPoolingInterval);

                eventStream.OnNext(new BuildEvent(BuildEventType.Information, BuildEventImportance.Low, $"Waiting for {organization.FriendlyName} to be enabled."));
            } while (orgState != OrganizationState.Enabled);
        }
        /// <summary>
        /// This method first connects to the Deployment service. Then,
        /// a variety of messages are used to retrieve deployment information.
        /// </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
            {
                //<snippetUseDeploymentServiceMessages1>
                // 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();

                    // Instantiate DeploymentServiceClient for calling the service.
                    DeploymentServiceClient serviceClient =
                        Deployment.Proxy.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 =
                            CredentialCache.DefaultNetworkCredentials;
                    }
                    else
                    {
                        serviceClient.ClientCredentials.Windows.ClientCredential =
                            serverConfig.Credentials.Windows.ClientCredential;
                    }

                    // Retrieve all deployed instances of Microsoft Dynamics CRM.
                    var organizations =
                        serviceClient.RetrieveAll(DeploymentEntityType.Organization);

                    // Print list of all retrieved organizations.
                    Console.WriteLine("Organizations in your deployment");
                    Console.WriteLine("================================");
                    foreach (var organization in organizations)
                    {
                        Console.WriteLine(organization.Name);
                    }
                    Console.WriteLine("<End of Listing>");
                    Console.WriteLine();


                    // Retrieve details of first organization from previous call.
                    Deployment.Organization deployment =
                        (Deployment.Organization)serviceClient.Retrieve(
                            DeploymentEntityType.Organization,
                            organizations[0]);

                    // Print out retrieved details about your organization.
                    Console.WriteLine(String.Format(
                                          "Selected deployment details for {0}",
                                          serverConfig.OrganizationName));
                    Console.WriteLine("=========================================");
                    Console.Write("Friendly Name: ");
                    Console.WriteLine(deployment.FriendlyName);
                    Console.Write("Unique Name: ");
                    Console.WriteLine(deployment.UniqueName);
                    Console.Write("Organization Version: ");
                    Console.WriteLine(deployment.Version);
                    Console.Write("SQL Server Name: ");
                    Console.WriteLine(deployment.SqlServerName);
                    Console.Write("SRS URL: ");
                    Console.WriteLine(deployment.SrsUrl);
                    Console.WriteLine("<End of Listing>");
                    Console.WriteLine();

                    // Retrieve license and user information for your organization.
                    TrackLicenseRequest  licenseRequest  = new TrackLicenseRequest();
                    TrackLicenseResponse licenseResponse =
                        (TrackLicenseResponse)serviceClient.Execute(licenseRequest);

                    // Print out the number of servers and the user list.
                    Console.WriteLine(String.Format(
                                          "License and user information for {0}",
                                          serverConfig.OrganizationName));
                    Console.WriteLine("=========================================");
                    Console.Write("Number of servers: ");
                    Console.WriteLine(licenseResponse.Servers != null
                        ? licenseResponse.Servers.Count.ToString()
                        : "null");
                    Console.WriteLine("Users:");
                    foreach (OrganizationUserInfo user in licenseResponse.Users.ToArray())
                    {
                        Console.WriteLine(user.FullName);
                    }
                    Console.WriteLine("<End of Listing>");
                    Console.WriteLine();

                    // Retrieve advanced settings for your organization.
                    // Note that the columnset must contain at least one column. Setting
                    // AllColumns to true results in an error.
                    RetrieveAdvancedSettingsRequest request =
                        new RetrieveAdvancedSettingsRequest
                    {
                        ConfigurationEntityName = "Server",
                        ColumnSet = new ColumnSet(
                            new string[] { "Id", "FullName", "Name", "Roles", "State", "Version" })
                    };
                    ConfigurationEntity configuration =
                        ((RetrieveAdvancedSettingsResponse)serviceClient.Execute(request)).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("<End of Listing>");
                    Console.WriteLine();
                }
                //</snippetUseDeploymentServiceMessages1>
            }

            // 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;
            }
        }
Exemplo n.º 5
0
        /// <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;
            }
        }
Exemplo n.º 6
0
        /// <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;
            }
        }
Exemplo n.º 7
0
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            connection = cm.MSCRMConnections[comboBoxSource.SelectedIndex];
            LogManager.WriteLog("Loading Server Settings.");
            toolStripStatusLabel1.Text = "";
            try
            {
                string deploymentURI = connection.ServerAddress.Replace(connection.OrganizationName + "/", "") + "XRMDeployment/2011/Deployment.svc";
                serviceClient = Microsoft.Xrm.Sdk.Deployment.Proxy.ProxyClientHelper.CreateClient(new Uri(deploymentURI));
                serviceClient.ClientCredentials.Windows.ClientCredential.UserName = connection.UserName;
                serviceClient.ClientCredentials.Windows.ClientCredential.Password = connection.Password;

                // Retrieve all deployed instances of Microsoft Dynamics CRM.
                var organizations = serviceClient.RetrieveAll(DeploymentEntityType.Organization);

                Microsoft.Xrm.Sdk.Deployment.EntityInstanceId currentOrganization = null;
                foreach (var organization in organizations)
                {
                    if (organization.Name.ToLower() == connection.OrganizationName.ToLower())
                    {
                        currentOrganization = organization;
                    }
                }

                RetrieveAdvancedSettingsRequest request = new RetrieveAdvancedSettingsRequest()
                {
                    ConfigurationEntityName = "Deployment",
                    ColumnSet = new ColumnSet()
                };

                ConfigurationEntity ce = ((RetrieveAdvancedSettingsResponse)serviceClient.Execute(request)).Entity;

                foreach (var setting in ce.Attributes)
                {
                    if (setting.Key == "AggregateQueryRecordLimit")
                    {
                        numericUpDownAggregateQueryRecordLimit.Text = setting.Value.ToString();
                    }
                    else if (setting.Key == "AutomaticallyInstallDatabaseUpdates")
                    {
                        checkBoxAutomaticallyInstallDatabaseUpdates.Checked = (bool)setting.Value;
                    }
                    else if (setting.Key == "AutomaticallyReprovisionLanguagePacks")
                    {
                        checkBoxAutomaticallyReprovisionLanguagePacks.Checked = (bool)setting.Value;
                    }
                }

                // Retrieve details of first organization from previous call.
                Microsoft.Xrm.Sdk.Deployment.Organization deployment =
                    (Microsoft.Xrm.Sdk.Deployment.Organization)serviceClient.Retrieve(
                        DeploymentEntityType.Organization,
                        currentOrganization);

                // Print out retrieved details about your organization.
                string organizationProperties = "";
                organizationProperties += "Friendly Name: " + deployment.FriendlyName + "\r\n";
                organizationProperties += "Unique Name: " + deployment.UniqueName + "\r\n";
                organizationProperties += "Organization Version: " + deployment.Version + "\r\n";
                organizationProperties += "SQL Server Name: " + deployment.SqlServerName + "\r\n";
                organizationProperties += "SRS URL: " + deployment.SrsUrl + "\r\n";
                organizationProperties += "Base Currency Code: " + deployment.BaseCurrencyCode + "\r\n";
                organizationProperties += "Base Currency Name: " + deployment.BaseCurrencyName + "\r\n";
                organizationProperties += "Base Currency Precision: " + deployment.BaseCurrencyPrecision + "\r\n";
                organizationProperties += "Base Currency Symbol: " + deployment.BaseCurrencySymbol + "\r\n";
                organizationProperties += "Base Language Code: " + deployment.BaseLanguageCode + "\r\n";
                organizationProperties += "Database Name: " + deployment.DatabaseName + "\r\n";
                organizationProperties += "Sql Collation: " + deployment.SqlCollation + "\r\n";
                organizationProperties += "Sqm Is Enabled: " + deployment.SqmIsEnabled + "\r\n";
                organizationProperties += "State: " + deployment.State + "\r\n";

                textBoxOrganizationProperties.Text = organizationProperties;

                // Retrieve license and user information for your organization.
                TrackLicenseRequest  licenseRequest  = new TrackLicenseRequest();
                TrackLicenseResponse licenseResponse = (TrackLicenseResponse)serviceClient.Execute(licenseRequest);

                // Print out the number of servers and the user list.
                string licenseanduserinformation = "Number of servers: ";
                licenseanduserinformation += licenseResponse.NumberOfServers.HasValue ? licenseResponse.NumberOfServers.Value.ToString() : "null";
                licenseanduserinformation += "\r\n";
                licenseanduserinformation += "Users:\r\n";
                foreach (String user in licenseResponse.UsersList)
                {
                    licenseanduserinformation += user + "\r\n";
                }
                textBoxLicenceanduserinformation.Text = licenseanduserinformation;

                // Retrieve server settings for your organization.
                RetrieveAdvancedSettingsRequest requestServerSettings =
                    new RetrieveAdvancedSettingsRequest
                {
                    ConfigurationEntityName = "ServerSettings",
                    ColumnSet = new ColumnSet(false)
                };
                ConfigurationEntity configuration = ((RetrieveAdvancedSettingsResponse)serviceClient.Execute(requestServerSettings)).Entity;

                // Print out all advanced settings where IsWritable==true.
                foreach (var setting in configuration.Attributes)
                {
                    if (setting.Key != "Id")
                    {
                        if (setting.Key == "DisableUserInfoClaim")
                        {
                            checkBoxDisableUserInfoClaim.Checked = (bool)setting.Value;
                        }
                        else if (setting.Key == "MaxExpandCount")
                        {
                            numericUpDownMaxExpandCount.Text = setting.Value.ToString();
                        }
                        else if (setting.Key == "MaxResultsPerCollection")
                        {
                            numericUpDownMaxResultsPerCollection.Text = setting.Value.ToString();
                        }
                        else if (setting.Key == "NlbEnabled")
                        {
                            checkBoxNlbEnabled.Checked = (bool)setting.Value;
                        }
                        else if (setting.Key == "PostponeAppFabricRequestsInMinutes")
                        {
                            numericUpDownPostponeAppFabricRequestsInMinutes.Text = setting.Value.ToString();
                        }
                        else if (setting.Key == "PostViaExternalRouter")
                        {
                            checkBoxPostViaExternalRouter.Checked = (bool)setting.Value;
                        }
                        else if (setting.Key == "SslHeader")
                        {
                            textBoxSslHeader.Text = setting.Value.ToString();
                        }
                    }
                }

                toolStripStatusLabel1.Text = connection.OrganizationName + " deployment properties were successfully loaded.";
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                //string url = connection.ServerAddress + "main.aspx?pagetype=entityrecord&etn=eaf_contrat_client&id=" + entity.Id.ToString();
                LogManager.WriteLog("Error: " + ex.Detail.Message + "\n" + ex.Detail.TraceText);
                MessageBox.Show("Error: " + ex.Detail.Message + "\n" + ex.Detail.TraceText);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                    MessageBox.Show("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                }
                else
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                    MessageBox.Show("Error:" + ex.Message);
                }
            }
        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            connection = cm.MSCRMConnections[comboBoxSource.SelectedIndex];
            LogManager.WriteLog("Loading Server Settings.");
            toolStripStatusLabel1.Text = "";
            try
            {
                string deploymentURI = connection.ServerAddress.Replace(connection.OrganizationName + "/", "") + "XRMDeployment/2011/Deployment.svc";
                serviceClient = Microsoft.Xrm.Sdk.Deployment.Proxy.ProxyClientHelper.CreateClient(new Uri(deploymentURI));
                serviceClient.ClientCredentials.Windows.ClientCredential.UserName = connection.UserName;
                serviceClient.ClientCredentials.Windows.ClientCredential.Password = connection.Password;

                // Retrieve all deployed instances of Microsoft Dynamics CRM.
                var organizations = serviceClient.RetrieveAll(DeploymentEntityType.Organization);

                Microsoft.Xrm.Sdk.Deployment.EntityInstanceId currentOrganization = null;
                foreach (var organization in organizations)
                {
                    if (organization.Name.ToLower() == connection.OrganizationName.ToLower())
                        currentOrganization = organization;
                }

                RetrieveAdvancedSettingsRequest request = new RetrieveAdvancedSettingsRequest()
                {
                    ConfigurationEntityName = "Deployment",
                    ColumnSet = new ColumnSet()
                };

                ConfigurationEntity ce = ((RetrieveAdvancedSettingsResponse)serviceClient.Execute(request)).Entity;

                foreach (var setting in ce.Attributes)
                {
                    if (setting.Key == "AggregateQueryRecordLimit")
                        numericUpDownAggregateQueryRecordLimit.Text = setting.Value.ToString();
                    else if (setting.Key == "AutomaticallyInstallDatabaseUpdates")
                        checkBoxAutomaticallyInstallDatabaseUpdates.Checked = (bool)setting.Value;
                    else if (setting.Key == "AutomaticallyReprovisionLanguagePacks")
                        checkBoxAutomaticallyReprovisionLanguagePacks.Checked = (bool)setting.Value;
                }

                // Retrieve details of first organization from previous call.
                Microsoft.Xrm.Sdk.Deployment.Organization deployment =
                    (Microsoft.Xrm.Sdk.Deployment.Organization)serviceClient.Retrieve(
                        DeploymentEntityType.Organization,
                        currentOrganization);

                // Print out retrieved details about your organization.
                string organizationProperties = "";
                organizationProperties += "Friendly Name: " + deployment.FriendlyName + "\r\n";
                organizationProperties += "Unique Name: " + deployment.UniqueName + "\r\n";
                organizationProperties += "Organization Version: " + deployment.Version + "\r\n";
                organizationProperties += "SQL Server Name: " + deployment.SqlServerName + "\r\n";
                organizationProperties += "SRS URL: " + deployment.SrsUrl + "\r\n";
                organizationProperties += "Base Currency Code: " + deployment.BaseCurrencyCode + "\r\n";
                organizationProperties += "Base Currency Name: " + deployment.BaseCurrencyName + "\r\n";
                organizationProperties += "Base Currency Precision: " + deployment.BaseCurrencyPrecision + "\r\n";
                organizationProperties += "Base Currency Symbol: " + deployment.BaseCurrencySymbol + "\r\n";
                organizationProperties += "Base Language Code: " + deployment.BaseLanguageCode + "\r\n";
                organizationProperties += "Database Name: " + deployment.DatabaseName + "\r\n";
                organizationProperties += "Sql Collation: " + deployment.SqlCollation + "\r\n";
                organizationProperties += "Sqm Is Enabled: " + deployment.SqmIsEnabled + "\r\n";
                organizationProperties += "State: " + deployment.State + "\r\n";

                textBoxOrganizationProperties.Text = organizationProperties;

                // Retrieve license and user information for your organization.
                TrackLicenseRequest licenseRequest = new TrackLicenseRequest();
                TrackLicenseResponse licenseResponse = (TrackLicenseResponse)serviceClient.Execute(licenseRequest);

                // Print out the number of servers and the user list.
                string licenseanduserinformation = "Number of servers: ";
                licenseanduserinformation += licenseResponse.NumberOfServers.HasValue ? licenseResponse.NumberOfServers.Value.ToString() : "null";
                licenseanduserinformation += "\r\n";
                licenseanduserinformation += "Users:\r\n";
                foreach (String user in licenseResponse.UsersList)
                {
                    licenseanduserinformation += user + "\r\n";
                }
                textBoxLicenceanduserinformation.Text = licenseanduserinformation;

                // Retrieve server settings for your organization.
                RetrieveAdvancedSettingsRequest requestServerSettings =
                    new RetrieveAdvancedSettingsRequest
                    {
                        ConfigurationEntityName = "ServerSettings",
                        ColumnSet = new ColumnSet(false)
                    };
                ConfigurationEntity configuration = ((RetrieveAdvancedSettingsResponse)serviceClient.Execute(requestServerSettings)).Entity;

                // Print out all advanced settings where IsWritable==true.
                foreach (var setting in configuration.Attributes)
                {
                    if (setting.Key != "Id")
                    {
                        if (setting.Key == "DisableUserInfoClaim")
                            checkBoxDisableUserInfoClaim.Checked = (bool)setting.Value;
                        else if (setting.Key == "MaxExpandCount")
                            numericUpDownMaxExpandCount.Text = setting.Value.ToString();
                        else if (setting.Key == "MaxResultsPerCollection")
                            numericUpDownMaxResultsPerCollection.Text = setting.Value.ToString();
                        else if (setting.Key == "NlbEnabled")
                            checkBoxNlbEnabled.Checked = (bool)setting.Value;
                        else if (setting.Key == "PostponeAppFabricRequestsInMinutes")
                            numericUpDownPostponeAppFabricRequestsInMinutes.Text = setting.Value.ToString();
                        else if (setting.Key == "PostViaExternalRouter")
                            checkBoxPostViaExternalRouter.Checked = (bool)setting.Value;
                        else if (setting.Key == "SslHeader")
                            textBoxSslHeader.Text = setting.Value.ToString();
                    }
                }

                toolStripStatusLabel1.Text = connection.OrganizationName + " deployment properties were successfully loaded.";
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                //string url = connection.ServerAddress + "main.aspx?pagetype=entityrecord&etn=eaf_contrat_client&id=" + entity.Id.ToString();
                LogManager.WriteLog("Error: " + ex.Detail.Message + "\n" + ex.Detail.TraceText);
                MessageBox.Show("Error: " + ex.Detail.Message + "\n" + ex.Detail.TraceText);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                    MessageBox.Show("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                }
                else
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                    MessageBox.Show("Error:" + ex.Message);
                }
            }
        }