/// <summary> /// Create a custom entity. /// Update the custom entity. /// Optionally delete the custom entity. /// </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(); // Create the custom entity. //<snippetCreateUpdateEntityMetadata1> CreateEntityRequest createrequest = new CreateEntityRequest { //Define the entity Entity = new EntityMetadata { SchemaName = _customEntityName, DisplayName = new Label("Bank Account", 1033), DisplayCollectionName = new Label("Bank Accounts", 1033), Description = new Label("An entity to store information about customer bank accounts", 1033), OwnershipType = OwnershipTypes.UserOwned, IsActivity = false, }, // Define the primary attribute for the entity PrimaryAttribute = new StringAttributeMetadata { SchemaName = "new_accountname", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Account Name", 1033), Description = new Label("The primary attribute for the Bank Account entity.", 1033) } }; _serviceProxy.Execute(createrequest); Console.WriteLine("The bank account entity has been created."); //</snippetCreateUpdateEntityMetadata1> // Add some attributes to the Bank Account entity //<snippetCreateUpdateEntityMetadata2> CreateAttributeRequest createBankNameAttributeRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new StringAttributeMetadata { SchemaName = "new_bankname", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Bank Name", 1033), Description = new Label("The name of the bank.", 1033) } }; _serviceProxy.Execute(createBankNameAttributeRequest); //</snippetCreateUpdateEntityMetadata2> Console.WriteLine("An bank name attribute has been added to the bank account entity."); //<snippetCreateUpdateEntityMetadata3> CreateAttributeRequest createBalanceAttributeRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new MoneyAttributeMetadata { SchemaName = "new_balance", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), PrecisionSource = 2, DisplayName = new Label("Balance", 1033), Description = new Label("Account Balance at the last known date", 1033), } }; _serviceProxy.Execute(createBalanceAttributeRequest); //</snippetCreateUpdateEntityMetadata3> Console.WriteLine("An account balance attribute has been added to the bank account entity."); //<snippetCreateUpdateEntityMetadata4> CreateAttributeRequest createCheckedDateRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new DateTimeAttributeMetadata { SchemaName = "new_checkeddate", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Format = DateTimeFormat.DateOnly, DisplayName = new Label("Date", 1033), Description = new Label("The date the account balance was last confirmed", 1033) } }; _serviceProxy.Execute(createCheckedDateRequest); Console.WriteLine("An date attribute has been added to the bank account entity."); //</snippetCreateUpdateEntityMetadata4> //Create a lookup attribute to link the bank account with a contact record. //<snippetCreateUpdateEntityMetadata5> CreateOneToManyRequest req = new CreateOneToManyRequest() { Lookup = new LookupAttributeMetadata() { Description = new Label("The owner of the bank account", 1033), DisplayName = new Label("Account Owner", 1033), LogicalName = "new_parent_contactid", SchemaName = "New_Parent_ContactId", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired) }, OneToManyRelationship = new OneToManyRelationshipMetadata() { AssociatedMenuConfiguration = new AssociatedMenuConfiguration() { Behavior = AssociatedMenuBehavior.UseCollectionName, Group = AssociatedMenuGroup.Details, Label = new Label("Bank Accounts", 1033), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration() { Assign = CascadeType.Cascade, Delete = CascadeType.Cascade, Merge = CascadeType.Cascade, Reparent = CascadeType.Cascade, Share = CascadeType.Cascade, Unshare = CascadeType.Cascade }, ReferencedEntity = Contact.EntityLogicalName, ReferencedAttribute = "contactid", ReferencingEntity = _customEntityName, SchemaName = "new_contact_new_bankaccount" } }; _serviceProxy.Execute(req); //</snippetCreateUpdateEntityMetadata5> Console.WriteLine("A lookup attribute has been added to the bank account entity to link it with the Contact entity."); //<snippetCreateUpdateEntityMetadata11> //Create an Image attribute for the custom entity // Only one Image attribute can be added to an entity that doesn't already have one. CreateAttributeRequest createEntityImageRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new ImageAttributeMetadata { SchemaName = "EntityImage", //The name is always EntityImage RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), DisplayName = new Label("Image", 1033), Description = new Label("An image to represent the bank account.", 1033) } }; _serviceProxy.Execute(createEntityImageRequest); Console.WriteLine("An image attribute has been added to the bank account entity."); //</snippetCreateUpdateEntityMetadata11> //<snippetCreateUpdateEntityMetadata9> //<snippetCreateUpdateEntityMetadata.RetrieveEntity> RetrieveEntityRequest retrieveBankAccountEntityRequest = new RetrieveEntityRequest { EntityFilters = EntityFilters.Entity, LogicalName = _customEntityName }; RetrieveEntityResponse retrieveBankAccountEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveBankAccountEntityRequest); //</snippetCreateUpdateEntityMetadata.RetrieveEntity> //<snippetCreateUpdateEntityMetadata8> EntityMetadata BankAccountEntity = retrieveBankAccountEntityResponse.EntityMetadata; // Disable Mail merge BankAccountEntity.IsMailMergeEnabled = new BooleanManagedProperty(false); // Enable Notes UpdateEntityRequest updateBankAccountRequest = new UpdateEntityRequest { Entity = BankAccountEntity, HasNotes = true }; _serviceProxy.Execute(updateBankAccountRequest); //</snippetCreateUpdateEntityMetadata8> //</snippetCreateUpdateEntityMetadata9> Console.WriteLine("The bank account entity has been updated"); //Update the entity form so the new fields are visible UpdateEntityForm(_customEntityName); // Customizations must be published after an entity is updated. //<snippetCreateUpdateEntityMetadata6> PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(publishRequest); //</snippetCreateUpdateEntityMetadata6> Console.WriteLine("Customizations were published."); //Provides option to view the entity in the default solution ShowEntityInBrowser(promptForDelete, BankAccountEntity); //Provides option to view the entity form with the fields added ShowEntityFormInBrowser(promptForDelete, BankAccountEntity); 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; } }
private void PublishAll(string deploymentFolderName) { WorkAsync(new WorkAsyncInfo { Message = "Publishing", Work = (worker, args) => { var publishRequest = new PublishAllXmlRequest(); args.Result = Service.Execute(publishRequest); }, PostWorkCallBack = (args) => { if (args.Error != null) { MessageBox.Show(args.Error.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { var result = args.Result as OrganizationResponse; if (result != null) { MessageBox.Show($"Solution {deploymentFolderName} deployed to Dynamics 365 CE"); } } } }); }
private void TsbPublishAllClick(object sender, EventArgs e) { tsbPublishEntity.Enabled = false; tsbPublishAll.Enabled = false; tsbSaveViews.Enabled = false; tsbLoadEntities.Enabled = false; WorkAsync("Publishing all customizations...", evt => { var pubRequest = new PublishAllXmlRequest(); Service.Execute(pubRequest); }, evt => { if (evt.Error != null) { string errorMessage = CrmExceptionHelper.GetErrorMessage(evt.Error, false); MessageBox.Show(this, errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } tsbPublishEntity.Enabled = true; tsbPublishAll.Enabled = true; tsbSaveViews.Enabled = true; tsbLoadEntities.Enabled = true; }); }
public void ImportSolution(OrganizationServiceProxy _serviceProxy) { string hostName = _serviceProxy.ServiceManagement.CurrentServiceEndpoint.ListenUri.Host; _serviceProxy.Timeout = TimeSpan.MaxValue; foreach (string solution in this.Settings.SolutionsToBeImport) { Console.WriteLine($"importing {solution} into {hostName} at {DateTime.Now.ToLongTimeString()}"); byte[] fileBytes = ReadSolutionFile(solution); ImportSolutionRequest impSolReq = new ImportSolutionRequest() { CustomizationFile = fileBytes, PublishWorkflows = true }; _serviceProxy.Execute(impSolReq); Console.WriteLine($"{solution} has been imported into {hostName} at {DateTime.Now.ToLongTimeString()}"); } if (this.Settings.PublishAllCustomizationAfterImported) { Console.WriteLine("Publishing all customizations " + DateTime.Now.ToLongTimeString()); PublishAllXmlRequest pubReq = new PublishAllXmlRequest(); _serviceProxy.Execute(pubReq); _serviceProxy.Dispose(); Console.WriteLine("All customizations have been published!"); } }
/// <summary> /// Deletes any entity records that were created for this sample. /// <param name="prompt">Indicates whether to prompt the user to delete /// the records created in this sample.</param> /// </summary> public void DeleteRequiredRecords(bool prompt) { bool deleteRecords = true; if (prompt) { Console.WriteLine("\nDo you want these entity records to be deleted? (y/n)"); String answer = Console.ReadLine(); deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y")); } if (deleteRecords) { DeleteAttributeRequest delSeriesAttribute = new DeleteAttributeRequest { LogicalName = "new_customappseriesattribute", EntityLogicalName = RecurringAppointmentMaster.EntityLogicalName }; _serviceProxy.Execute(delSeriesAttribute); DeleteAttributeRequest delInstanceAttribute = new DeleteAttributeRequest { LogicalName = "new_customappinstanceattribute", EntityLogicalName = Appointment.EntityLogicalName }; _serviceProxy.Execute(delInstanceAttribute); // Publish all the changes to the solution. PublishAllXmlRequest delRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(delRequest); Console.WriteLine("Entity records have been deleted."); } }
public void PublishAll() { BaseComponent.LogInfo("Publishing customizations"); PublishAllXmlRequest publishAll = new PublishAllXmlRequest(); Service.Execute(publishAll); }
public ValidationResults Validate(CRMSolution solution) { ValidationResults allValidatorsResult = new ValidationResults(); if (Validators == null || Validators.Count == 0) { throw new InvalidOperationException("No Validators exist, please change the validation settings first"); } //publish all customizations first if the settings allow it if (MySettings.AlwaysPublish) { OnProgressChanged?.Invoke(this, new ProgressEventArgs("Publishing customizations")); PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); CRMService.Execute(publishRequest); } // start the validators foreach (IValidator validator in Validators) { validator.OnValidatorError += (s, e) => { OnError?.Invoke(s, e); }; validator.OnValidatorProgress += (s, e) => { OnProgressChanged?.Invoke(s, new ProgressEventArgs(e.Message)); }; ValidationResults validatorResult = validator.Validate(); allValidatorsResult.AddResultSet(validatorResult); } return(allValidatorsResult); }
public void publishRequest() { if (Service != null) { PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); Service.Execute(publishRequest); } }
public void Publish() { // Obtain an organization service proxy. // The using statement assures that the service proxy will be properly disposed. var publishRequest = new PublishAllXmlRequest(); OrganizationService.Execute(publishRequest); }
protected override void Execute(CodeActivityContext context) { CrmConnection connection = CrmConnection.Parse(CrmConnectionString.Get(context)); using (OrganizationService orgService = new OrganizationService(connection)) { PublishAllXmlRequest req = new PublishAllXmlRequest(); orgService.Execute(req); } }
/// <summary> /// Method publish all the customization /// </summary> /// <param name="serviceProxy">organization service proxy</param> /// <param name="solutionFile">solution file</param> private void PublishAllCustomizationChanges(OrganizationServiceProxy serviceProxy, SolutionFileInfo solutionFile) { PublishAllXmlRequest publishAllXmlRequest = new PublishAllXmlRequest(); serviceProxy.Execute(publishAllXmlRequest); Singleton.SolutionFileInfoInstance.WebJobsLog.AppendLine("Successfully published solution components." + "<br>"); solutionFile.Solution[Constants.SourceControlQueueAttributeNameForStatus] = Constants.SourceControlQueuePublishSuccessfulStatus; solutionFile.Solution.Attributes["syed_webjobs"] = Singleton.SolutionFileInfoInstance.WebJobs(); solutionFile.Update(); Singleton.SolutionFileInfoInstance.UploadFiletoDynamics(Singleton.CrmConstantsInstance.ServiceProxy, solutionFile.Solution); }
public void PublishAll() { try { var request = new PublishAllXmlRequest(); innerService.Execute(request); } catch (FaultException <OrganizationServiceFault> error) { throw new Exception("An error while publishing archive: " + error.Message); } }
protected override void ProcessRecord() { base.ProcessRecord(); base.WriteVerbose(string.Format("Publishing Customizations")); var publishAllXmlRequest = new PublishAllXmlRequest(); OrganizationService.Execute(publishAllXmlRequest); base.WriteVerbose(string.Format("Publish Customizations Completed")); }
private void Publish() { var publishAllXmlRequest = new PublishAllXmlRequest(); if (!(CdsClient.Execute(publishAllXmlRequest) is PublishAllXmlResponse)) { Console.WriteLine("Not Connected"); return; } Console.WriteLine("All customizations published successfully"); }
public static void UpdateViewsInCRM(List <View> views, IOrganizationService service) { foreach (var i in views) { Console.WriteLine($"Processing {i.name}"); service.Update(i.AsEntity()); } Console.WriteLine("Publishing"); PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); service.Execute(publishRequest); }
private PublishAllXmlRequest PreparePublishRequest(ConnectionDetail detail) { var request = new PublishAllXmlRequest(); progressItems.Add(request, new ProgressItem { Type = Enumerations.RequestType.Publish, Detail = detail, Request = request }); return(request); }
/// <summary> /// Delete the Custom Activity itself /// </summary> public static void DeleteCustomActivity() { DeleteEntityRequest request = new DeleteEntityRequest() { LogicalName = _customActivityName, }; service.Execute(request); // Customizations must be published after an entity is updated. PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); service.Execute(publishRequest); Console.WriteLine("The custom entity has been deleted."); }
public static void PublishSystemForm(IOrganizationService service) { var request = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><entities><entity>systemform</entity></entities></importexportxml>") }; service.Execute(request); var publishAllRequest = new PublishAllXmlRequest(); service.Execute(publishAllRequest); }
private static void Publish(IOrganizationService organizationService) { PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); try { organizationService.Execute(publishRequest); } catch (FaultException <OrganizationServiceFault> ) { ExConsole.WriteLineColor("Could not publish solution", ConsoleColor.Red); throw; } }
private void Publish(bool all) { if (lvEntities.SelectedItems.Count == 0) { return; } ManageWorkingState(true); var message = all ? "Publishing all customizations" : "Publishing entity..."; informationPanel = InformationPanel.GetInformationPanel(this, message, 340, 120); var bwPublish = new BackgroundWorker(); bwPublish.DoWork += (sender, e) => { if (string.IsNullOrEmpty(e.Argument.ToString())) { var pubRequest = new PublishAllXmlRequest(); targetService.Execute(pubRequest); } else { var pubRequest = new PublishXmlRequest(); pubRequest.ParameterXml = string.Format(@"<importexportxml> <entities> <entity>{0}</entity> </entities> <nodes/><securityroles/><settings/><workflows/> </importexportxml>", e.Argument.ToString()); targetService.Execute(pubRequest); } }; bwPublish.RunWorkerCompleted += (sender, e) => { ManageWorkingState(false); Controls.Remove(informationPanel); informationPanel.Dispose(); if (e.Error != null) { MessageBox.Show(this, e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }; bwPublish.RunWorkerAsync(all ? "" : ((EntityMetadata)lvEntities.SelectedItems[0].Tag).LogicalName); }
/// <summary> /// Executes the operation. /// </summary> /// <param name="cancel">The cancellation token.</param> /// <param name="progress">The progress.</param> public override void Execute(CancellationToken cancel, IProgress <ExecutionProgress> progress) { OnExecuting(new ExecutableEventArgs(this)); progress?.Report(new ExecutionProgress(NotificationType.Information, string.Format(Properties.Resources.Dynamics365PublishAllOperationExecute, Connection.Name))); PublishAllXmlRequest request = new PublishAllXmlRequest(); using (OrganizationServiceProxy proxy = connection.OrganizationServiceProxy) { proxy.Execute(request); } //progress?.Report(new ExecutionProgress(NotificationType.Information, string.Format(Properties.Resources.Dynamics365PublishAllOperationExecuteSuccessful, Connection.Name))); OnExecuted(new ExecutableEventArgs(this)); }
public void ExportSolution(OrganizationServiceProxy _serviceProxy) { //if (this.Settings.IsChangeWorkFlowName) //{ // ChangeWorkflowName(_serviceProxy); //} string hostName = _serviceProxy.ServiceManagement.CurrentServiceEndpoint.ListenUri.Host; _serviceProxy.Timeout = TimeSpan.MaxValue; _serviceProxy.EnableProxyTypes(); if (Settings.PublishAllCustomizationBeforeExported) { Console.WriteLine($"{hostName} Publishing all customizations at " + DateTime.Now.ToLongTimeString()); PublishAllXmlRequest pubReq = new PublishAllXmlRequest(); _serviceProxy.Execute(pubReq); } foreach (string solution in this.Settings.SolutionsToBeExport) { QueryExpression qe = new QueryExpression("solution"); qe.ColumnSet = new ColumnSet("version"); qe.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solution); qe.TopCount = 1; qe.NoLock = true; Entity entSolution = _serviceProxy.RetrieveMultiple(qe).Entities.FirstOrDefault(); if (entSolution != null) { Console.WriteLine($"Export {solution} from {hostName} at {DateTime.Now.ToLongTimeString()}"); string monthDay = DateTime.Today.ToString("MMdd"); string newVersion = entSolution.GetAttributeValue <string>("version") + monthDay; entSolution.Attributes["version"] = newVersion; _serviceProxy.Update(entSolution); ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = false; exportSolutionRequest.SolutionName = solution; //exportSolutionRequest.TargetVersion = "8.2"; ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)_serviceProxy.Execute(exportSolutionRequest); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; string filename = string.Format("{0}_{1}.zip", solution, newVersion.Replace('.', '_')); WriteSolutionFile(exportXml, filename); } } Console.WriteLine("solution has been exported at " + DateTime.Now.ToLongTimeString()); }
protected override void ProcessRecord() { base.ProcessRecord(); base.WriteVerbose(string.Format("Publishing Customizations")); CrmConnection connection = CrmConnection.Parse(connectionString); using (OrganizationService service = new OrganizationService(connection)) { PublishAllXmlRequest req = new PublishAllXmlRequest(); service.Execute(req); base.WriteVerbose(string.Format("Publish Customizations Completed")); } }
public static bool PublishAllCustomizations(CrmServiceClient client) { try { PublishAllXmlRequest request = new PublishAllXmlRequest(); client.Execute(request); return(true); } catch (Exception ex) { ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorPublishing, ex); return(false); } }
private void PublishAll() { try { AddMessage(String.Empty); AddMessage("Publishing all customizations..."); PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); var response = (PublishAllXmlResponse)_serviceProxy.Execute(publishRequest); AddMessage("Done."); } catch (Exception e) { AddMessage("Error publishing: " + e.Message); } }
private void btnPublish_Click(object sender, EventArgs e) { var isValidForm = ValidateChildren(); if (!isValidForm) { return; } var selectedSectionProxy = (SectionProxy)cmbSection.SelectedItem; var selectedSection = selectedSectionProxy.Section; var sectionXml = GeneratePowerBiSectionXml(selectedSection); var regexString = $@"<section[^>]+{selectedSection.Id}.*?<\/section>"; Regex regex = new Regex(regexString); Match match = regex.Match(_fetchXml); var selectedSectionXml = match.Value; _fetchXml = _fetchXml.Replace(selectedSectionXml, sectionXml); var oldformEntity = ((FormProxy)cmbForm.SelectedItem).Entity; var formEntity = new Entity(oldformEntity.LogicalName, oldformEntity.Id); formEntity["formxml"] = _fetchXml; WorkAsync(new WorkAsyncInfo("Publishing report on the form...", (eventargs) => { Service.Update(formEntity); PublishAllXmlRequest publishallxmlrequest = new PublishAllXmlRequest(); Service.Execute(publishallxmlrequest); }) { PostWorkCallBack = (completedargs) => { if (completedargs.Error != null) { MessageBox.Show(completedargs.Error.Message); } } }); }
public static bool PublishAllCustomizations(CrmServiceClient client) { try { ExLogger.LogToFile(Logger, Resource.Message_PublishingAllCustomizations, LogLevel.Info); OutputLogger.WriteToOutputWindow(Resource.Message_PublishingAllCustomizations, MessageType.Info); var request = new PublishAllXmlRequest(); client.Execute(request); return(true); } catch (Exception ex) { ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorPublishing, ex); return(false); } }
public static bool PublishAllCustomizations(CrmServiceClient client) { try { PublishAllXmlRequest request = new PublishAllXmlRequest(); PublishAllXmlResponse response = (PublishAllXmlResponse)client.Execute(request); return(true); } catch (FaultException <OrganizationServiceFault> crmEx) { OutputLogger.WriteToOutputWindow("Error Publishing Customizations To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, MessageType.Error); return(false); } catch (Exception ex) { OutputLogger.WriteToOutputWindow("Error Publishing Customizations To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error); return(false); } }
/// <summary> /// Reverts any changes that were done by this sample. /// <param name="prompt">Indicates whether to prompt the user /// to revert the changes done by this sample.</param> /// </summary> public void RevertChanges(bool prompt) { bool revertChanges = true; if (prompt) { Console.WriteLine("\nDo you want these changes reverted? (y/n) [y]: "); String answer = Console.ReadLine(); revertChanges = (answer.StartsWith("y") || answer.StartsWith("Y") || answer == String.Empty); } if (revertChanges) { RetrieveEntityRequest entityRequest = new RetrieveEntityRequest { EntityFilters = EntityFilters.All, LogicalName = Contact.EntityLogicalName, RetrieveAsIfPublished = false }; RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(entityRequest); EntityMetadata contactEntity = entityResponse.EntityMetadata; // Disable document management for the retrieved entity. contactEntity.IsDocumentManagementEnabled = false; UpdateEntityRequest updateRequest = new UpdateEntityRequest { Entity = contactEntity }; _serviceProxy.Execute(updateRequest); // Publish the customizations to the entity. PublishAllXmlRequest disableRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(disableRequest); Console.WriteLine("Changes have been reverted."); } }
/// <summary> /// Checks if knowledge management is enabled for the Incident entity. /// </summary> private void CheckKnowledgeManagementStatus() { RetrieveEntityRequest entityRequest = new RetrieveEntityRequest { EntityFilters = EntityFilters.All, LogicalName = Incident.EntityLogicalName, // Retrieve only the currently published changes, ignoring the changes // that have not been published. RetrieveAsIfPublished = false }; RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(entityRequest); if (entityResponse.EntityMetadata.IsKnowledgeManagementEnabled == true) { Console.WriteLine("Verified that knowledge management is enabled for Incident entity.\n"); return; } else { // Enable knolwledge management for the Incident entity. Console.WriteLine("Knowledge management is not enabled for the Incident entity."); entityResponse.EntityMetadata.IsKnowledgeManagementEnabled = true; // Create an update request. UpdateEntityRequest updateRequest = new UpdateEntityRequest { Entity = entityResponse.EntityMetadata }; _serviceProxy.Execute(updateRequest); // Publish the entity. // All customizations must be published before they can be used. PublishAllXmlRequest enableRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(enableRequest); Console.WriteLine("Enabled Knowledge management for the Incident entity."); } }
public void UpdateEntity(string entityName, AttributeMetaData attributeMetaData) { using (var crmSvc = new CrmServiceClient(cnString)) { var createAttributeRequest = new CreateAttributeRequest { EntityName = (SchemaPrefix + entityName).ToLower(), Attribute = new emd.StringAttributeMetadata { SchemaName = (SchemaPrefix + attributeMetaData.SchemaName).ToLower(), RequiredLevel = new emd.AttributeRequiredLevelManagedProperty(emd.AttributeRequiredLevel.None), MaxLength = 100, FormatName = emd.StringFormatName.Text, DisplayName = new Label(attributeMetaData.DisplayName, 1033), Description = new Label(attributeMetaData.Description, 1033) } }; var result = crmSvc.OrganizationServiceProxy.Execute(createAttributeRequest); var pub = new PublishAllXmlRequest(); crmSvc.OrganizationServiceProxy.Execute(pub); } }
private void ImportGUI(BackgroundWorker worker, DoWorkEventArgs e) { try { //Check if there is a solutions to import if (Directory.Exists(currentProfile.SolutionExportFolder)) { IOrderedEnumerable<string> subDirectories = Directory.GetDirectories(currentProfile.SolutionExportFolder).OrderByDescending(x => x); if (subDirectories.Count<string>() == 0) { LogManager.WriteLog("There are no solutions for import."); StatusMessage = "There are no solutions for import."; return; } //Check which solutions to import: Newest, Oldest, specific exprot date solutions string solutionsToImportFolder = ""; if (currentProfile.SolutionsToImport == "Newest") solutionsToImportFolder = subDirectories.ElementAt(0); else if (currentProfile.SolutionsToImport == "Oldest") solutionsToImportFolder = subDirectories.ElementAt(subDirectories.Count<string>() - 1); else solutionsToImportFolder = subDirectories.First(s => s.EndsWith(currentProfile.SolutionsToImport)); if (solutionsToImportFolder == "") { LogManager.WriteLog("The specified solutions to import were not found."); StatusMessage = "The specified solutions to import were not found."; return; } //get all solutions archives string[] solutionsArchivesNames = Directory.GetFiles(solutionsToImportFolder, "*.zip"); if (solutionsArchivesNames.Count<string>() == 0) { LogManager.WriteLog("There are no solutions for import."); StatusMessage = "There are no solutions for import."; return; } string[] pathList = solutionsToImportFolder.Split(new Char[] { '\\' }); string DirectoryName = pathList[pathList.Count<string>() - 1]; LogManager.WriteLog("Importing solutions from " + DirectoryName); MSCRMConnection connection = currentProfile.getTargetConneciton(); _serviceProxy = cm.connect(connection); LogManager.WriteLog("Start importing solutions in " + connection.ConnectionName); int solutionsCpt = 0; foreach (string solutionArchiveName in solutionsArchivesNames) { bool selectedsolutionfound = false; foreach (string solutionname in currentProfile.SelectedSolutionsNames) { if (Path.GetFileName(solutionArchiveName).StartsWith(solutionname)) selectedsolutionfound = true; } if(!selectedsolutionfound) continue; solutionsCpt++; //Import Solution LogManager.WriteLog("Importing solution archive " + Path.GetFileName(solutionArchiveName) + " into " + connection.ConnectionName); StatusMessage = "Importing solution archive " + Path.GetFileName(solutionArchiveName) + " into " + connection.ConnectionName; //worker.ReportProgress(solutionsCpt * 100 / currentProfile.SelectedSolutionsNames.Count); byte[] fileBytes = File.ReadAllBytes(solutionArchiveName); Guid ImportJobId = Guid.NewGuid(); impSolReqWithMonitoring = new ImportSolutionRequest() { CustomizationFile = fileBytes, OverwriteUnmanagedCustomizations = currentProfile.OverwriteUnmanagedCustomizations, PublishWorkflows = currentProfile.PublishWorkflows, ImportJobId = ImportJobId }; if (bwSolutionImport.IsBusy != true) bwSolutionImport.RunWorkerAsync(); solutionImportInProgress = true; while (solutionImportInProgress) { if (transportStopped) return; int progress = GetImportProgress(ImportJobId, connection); worker.ReportProgress(progress); System.Threading.Thread.Sleep(5000); } //if (transportStopped) // return; //Entity ImportJob = _serviceProxy.Retrieve("importjob", ImportJobId, new ColumnSet(true)); ////File.WriteAllText(solutionsToImportFolder + "\\importlog_ORIGINAL_" + Path.GetFileNameWithoutExtension(solutionArchiveName) + ".xml", (string)ImportJob["data"]); //impSolReqWithMonitoring = null; //RetrieveFormattedImportJobResultsRequest importLogRequest = new RetrieveFormattedImportJobResultsRequest() //{ // ImportJobId = ImportJobId //}; //RetrieveFormattedImportJobResultsResponse importLogResponse = (RetrieveFormattedImportJobResultsResponse)_serviceProxy.Execute(importLogRequest); //DateTime now = DateTime.Now; //string timeNow = String.Format("{0:yyyyMMddHHmmss}", now); //string exportedSolutionFileName = solutionsToImportFolder + "\\importlog_" + Path.GetFileNameWithoutExtension(solutionArchiveName) + "_" + timeNow + ".xml"; ////Fix bad Status and Message export //System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); //doc.LoadXml((string)ImportJob["data"]); //String SolutionImportResult = doc.SelectSingleNode("//solutionManifest/result/@result").Value; //File.WriteAllText(exportedSolutionFileName, importLogResponse.FormattedResults); writeLogFile(ImportJobId, solutionsToImportFolder, solutionArchiveName); importSourceFolder = solutionsToImportFolder; LogManager.WriteLog("Solution " + Path.GetFileName(solutionArchiveName) + " was imported with success in " + connection.ConnectionName); } //Check if customizations are to be published if (currentProfile.PublishAllCustomizationsTarget) { LogManager.WriteLog("Publishing all Customizations on " + connection.ConnectionName + " ..."); PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(publishRequest); } LogManager.WriteLog("Solutions Import finished for Profile: " + currentProfile.ProfileName); } else { LogManager.WriteLog("There are no solutions for import."); return; } } catch(Exception ex) { transportStopped = true; LogManager.WriteLog("Error ! Detail : " + ex.Message); MessageBox.Show("Error ! Detail : " + ex.Message); toolStripStatusLabel1.Text = "Transport stopped."; } }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// retrieves the Contact entity record, and then enables the document management /// for the entity. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforRevert">When True, the user will be prompted to revert all /// the changes done in this sample.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforRevert) { 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(); //<snippetEnableDocumentManagement1> // Retrieve an entity for which you want to enable document management. // In this sample, we will retrieve and enable document management // for the Contact entity because by default, document management is // not enabled for this entity. RetrieveEntityRequest entityRequest = new RetrieveEntityRequest { EntityFilters = EntityFilters.All, LogicalName = Contact.EntityLogicalName, // Retrieve only the currently published changes, ignoring the changes // that have not been published. RetrieveAsIfPublished = false }; RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(entityRequest); Console.WriteLine("Retrieved the contact entity."); // Get the entity from the response. EntityMetadata contactEntity = entityResponse.EntityMetadata; // Enable document management for the retrieved entity. contactEntity.IsDocumentManagementEnabled = true; // Create an update request. UpdateEntityRequest updateRequest = new UpdateEntityRequest { Entity = contactEntity }; _serviceProxy.Execute(updateRequest); // Publish the entity. // All customizations must be published before they can be used. PublishAllXmlRequest enableRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(enableRequest); // Retrieve the contact entity, and verify that document management is enabled. entityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(entityRequest); contactEntity = entityResponse.EntityMetadata; if (contactEntity.IsDocumentManagementEnabled.Value == true) { Console.WriteLine("Enabled document management for the contact entity."); } RevertChanges(promptforRevert); //</snippetEnableDocumentManagement1> } } // 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> /// Exports the specified profile. /// </summary> /// <param name="profile">The profile.</param> private void Export(MSCRMSolutionsTransportProfile profile) { try { //Set Data export folder if (!Directory.Exists(profile.SolutionExportFolder)) Directory.CreateDirectory(profile.SolutionExportFolder); MSCRMConnection connection = profile.getSourceConneciton(); _serviceProxy = cm.connect(connection); //Download fresh list of solutions for versions update List<MSCRMSolution> solutions = DownloadSolutions(connection); DateTime now = DateTime.Now; string folderName = String.Format("{0:yyyyMMddHHmmss}", now); if (!Directory.Exists(profile.SolutionExportFolder + "\\" + folderName)) Directory.CreateDirectory(profile.SolutionExportFolder + "\\" + folderName); foreach (string SolutionName in profile.SelectedSolutionsNames) { //Check if customizations are to be published if (profile.PublishAllCustomizationsSource) { LogManager.WriteLog("Publishing all Customizations on " + connection.ConnectionName + " ..."); PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(publishRequest); } LogManager.WriteLog("Exporting Solution " + SolutionName + " from " + connection.ConnectionName); ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = profile.ExportAsManaged; exportSolutionRequest.SolutionName = SolutionName; exportSolutionRequest.ExportAutoNumberingSettings = profile.ExportAutoNumberingSettings; exportSolutionRequest.ExportCalendarSettings = profile.ExportCalendarSettings; exportSolutionRequest.ExportCustomizationSettings = profile.ExportCustomizationSettings; exportSolutionRequest.ExportEmailTrackingSettings = profile.ExportEmailTrackingSettings; exportSolutionRequest.ExportGeneralSettings = profile.ExportGeneralSettings; exportSolutionRequest.ExportIsvConfig = profile.ExportIsvConfig; exportSolutionRequest.ExportMarketingSettings = profile.ExportMarketingSettings; exportSolutionRequest.ExportOutlookSynchronizationSettings = profile.ExportOutlookSynchronizationSettings; exportSolutionRequest.ExportRelationshipRoles = profile.ExportRelationshipRoles; string managed = ""; if (profile.ExportAsManaged) managed = "managed"; MSCRMSolution selectedSolution = solutions.Find(s => s.UniqueName == SolutionName); string selectedSolutionVersion = selectedSolution.Version.Replace(".","_"); ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)_serviceProxy.Execute(exportSolutionRequest); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; string filename = SolutionName + "_" + selectedSolutionVersion + "_" + managed + ".zip"; File.WriteAllBytes(profile.SolutionExportFolder + "\\" + folderName + "\\" + filename, exportXml); LogManager.WriteLog("Export finished for Solution: " + SolutionName + ". Exported file: " + filename); } LogManager.WriteLog("Export finished for Profile: " + profile.ProfileName); } catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex) { LogManager.WriteLog("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText); throw; } catch (Exception ex) { if (ex.InnerException != null) LogManager.WriteLog("Error:" + ex.Message + "\n" + ex.InnerException.Message); else LogManager.WriteLog("Error:" + ex.Message); throw; } }
/// <summary> /// Imports the specified profile. /// </summary> /// <param name="profile">The profile.</param> private void Import(MSCRMSolutionsTransportProfile profile) { //Check if there is a solutions to import if (Directory.Exists(profile.SolutionExportFolder)) { IOrderedEnumerable<string> subDirectories = Directory.GetDirectories(profile.SolutionExportFolder).OrderByDescending(x => x); if (subDirectories.Count<string>() == 0) { LogManager.WriteLog("There are no solutions for import."); return; } //Check which solutions to import: Newest, Oldest, specific exprot date solutions string solutionsToImportFolder = ""; if (profile.SolutionsToImport == "Newest") solutionsToImportFolder = subDirectories.ElementAt(0); else if (profile.SolutionsToImport == "Oldest") solutionsToImportFolder = subDirectories.ElementAt(subDirectories.Count<string>() - 1); else solutionsToImportFolder = subDirectories.First(s => s.EndsWith(profile.SolutionsToImport)); if (solutionsToImportFolder == "") { LogManager.WriteLog("The specified solutions to import were not found."); return; } //get all solutions archives string[] solutionsArchivesNames = Directory.GetFiles(solutionsToImportFolder, "*.zip"); if (solutionsArchivesNames.Count<string>() == 0) { LogManager.WriteLog("There are no solutions for import."); return; } string[] pathList = solutionsToImportFolder.Split(new Char [] {'\\'}); string DirectoryName = pathList[pathList.Count<string>() -1]; LogManager.WriteLog("Importing solutions from " + DirectoryName); MSCRMConnection connection = profile.getTargetConneciton(); _serviceProxy = cm.connect(connection); LogManager.WriteLog("Start importing solutions in " + connection.ConnectionName); foreach (string solutionArchiveName in solutionsArchivesNames) { bool selectedsolutionfound = false; foreach (string solutionname in profile.SelectedSolutionsNames) { if (Path.GetFileName(solutionArchiveName).StartsWith(solutionname)) selectedsolutionfound = true; } if (!selectedsolutionfound) continue; //Import Solution LogManager.WriteLog("Importing solution archive " + Path.GetFileName(solutionArchiveName) + " into " + connection.ConnectionName); byte[] fileBytes = File.ReadAllBytes(solutionArchiveName); Guid ImportJobId = Guid.NewGuid(); ImportSolutionRequest impSolReqWithMonitoring = new ImportSolutionRequest() { CustomizationFile = fileBytes, OverwriteUnmanagedCustomizations = profile.OverwriteUnmanagedCustomizations, PublishWorkflows = profile.PublishWorkflows, ImportJobId = ImportJobId }; _serviceProxy.Execute(impSolReqWithMonitoring); Entity ImportJob = _serviceProxy.Retrieve("importjob", impSolReqWithMonitoring.ImportJobId, new ColumnSet(true)); //File.WriteAllText(solutionsToImportFolder + "\\importlog_ORIGINAL_" + Path.GetFileNameWithoutExtension(solutionArchiveName) + ".xml", (string)ImportJob["data"]); RetrieveFormattedImportJobResultsRequest importLogRequest = new RetrieveFormattedImportJobResultsRequest() { ImportJobId = ImportJobId }; RetrieveFormattedImportJobResultsResponse importLogResponse = (RetrieveFormattedImportJobResultsResponse)_serviceProxy.Execute(importLogRequest); DateTime now = DateTime.Now; string timeNow = String.Format("{0:yyyyMMddHHmmss}", now); string exportedSolutionFileName = solutionsToImportFolder + "\\importlog_" + Path.GetFileNameWithoutExtension(solutionArchiveName) + "_" + timeNow + ".xml"; //Fix bad Status and Message export System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml((string)ImportJob["data"]); String SolutionImportResult = doc.SelectSingleNode("//solutionManifest/result/@result").Value; File.WriteAllText(exportedSolutionFileName, importLogResponse.FormattedResults); LogManager.WriteLog("Solution " + Path.GetFileName(solutionArchiveName) + " was imported with success in " + connection.ConnectionName); } //Check if customizations are to be published if (profile.PublishAllCustomizationsTarget) { LogManager.WriteLog("Publishing all Customizations on " + connection.ConnectionName + " ..."); PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(publishRequest); } LogManager.WriteLog("Solutions Import finished for Profile: " + profile.ProfileName); } else { LogManager.WriteLog("There are no solutions for import."); return; } }
/// <summary> /// Create a custom entity that can be used in the To field of an email activity. /// Update the custom entity. /// Optionally delete the custom entity. /// </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(); //<snippetCreateUpdateEmailableEntity1> // Create the custom entity. CreateEntityRequest createrequest = new CreateEntityRequest { // Define an entity to enable for emailing. In order to do so, // IsActivityParty must be set. Entity = new EntityMetadata { SchemaName = _customEntityName, DisplayName = new Label("Agent", 1033), DisplayCollectionName = new Label("Agents", 1033), Description = new Label("Insurance Agents", 1033), OwnershipType = OwnershipTypes.UserOwned, IsActivity = false, // Unless this flag is set, this entity cannot be party to an // activity. IsActivityParty = true }, // As with built-in emailable entities, the Primary Attribute will // be used in the activity party screens. Be sure to choose descriptive // attributes. PrimaryAttribute = new StringAttributeMetadata { SchemaName = "new_fullname", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Agent Name", 1033), Description = new Label("Agent Name", 1033) } }; _serviceProxy.Execute(createrequest); Console.WriteLine("The emailable entity has been created."); // The entity will not be selectable as an activity party until its customizations // have been published. Otherwise, the e-mail activity dialog cannot find // a correct default view. PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(publishRequest); // Before any emails can be created for this entity, an Email attribute // must be defined. CreateAttributeRequest createFirstEmailAttributeRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new StringAttributeMetadata { SchemaName = "new_emailaddress", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Email, DisplayName = new Label("Email Address", 1033), Description = new Label("Email Address", 1033) } }; _serviceProxy.Execute(createFirstEmailAttributeRequest); Console.WriteLine("An email attribute has been added to the emailable entity."); // Create a second, alternate email address. Since there is already one // email attribute on the entity, this will never be used for emailing // even if the first one is not populated. CreateAttributeRequest createSecondEmailAttributeRequest = new CreateAttributeRequest { EntityName = _customEntityName, Attribute = new StringAttributeMetadata { SchemaName = "new_secondaryaddress", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Email, DisplayName = new Label("Secondary Email Address", 1033), Description = new Label("Secondary Email Address", 1033) } }; _serviceProxy.Execute(createSecondEmailAttributeRequest); Console.WriteLine("A second email attribute has been added to the emailable entity."); //</snippetCreateUpdateEmailableEntity1> 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; } }
public void Import(string filePath, IOrganizationService service, BackgroundWorker worker = null) { var stream = File.OpenRead(filePath); var file = new ExcelPackage(stream); var emds = new List<EntityMetadata>(); var forms = new List<Entity>(); var ft = new FormTranslation(); var st = new SiteMapTranslation(); var db = new DashboardTranslation(); bool hasFormContent = false; bool hasDashboardContent = false; bool hasSiteMapContent = false; foreach (var sheet in file.Workbook.Worksheets) { switch (sheet.Name) { case "Entities": if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Importing entities translations..."); } var et = new EntityTranslation(); et.Import(sheet, emds, service); break; case "Attributes": if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Importing attributes translations..."); } var at = new AttributeTranslation(); at.Import(sheet, emds, service); break; case "Relationships": { if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Importing Relationships with custom label translations..."); } var rt = new RelationshipTranslation(); rt.Import(sheet, emds, service); break; } case "RelationshipsNN": { if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Importing NN Relationships with custom label translations..."); } var rtNn = new RelationshipNnTranslation(); rtNn.Import(sheet, emds, service); break; } case "Global OptionSets": if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Importing global optionsets translations..."); } var got = new GlobalOptionSetTranslation(); got.Import(sheet, service); break; case "OptionSets": if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Importing optionsets translations..."); } var ot = new OptionSetTranslation(); ot.Import(sheet, service); break; case "Booleans": if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Importing booleans translations..."); } var bt = new BooleanTranslation(); bt.Import(sheet, service); break; case "Views": if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Importing views translations..."); } var vt = new ViewTranslation(); vt.Import(sheet, service); break; case "Forms": if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Importing forms translations..."); } ft.ImportFormName(sheet, service); break; case "Forms Tabs": ft.PrepareFormTabs(sheet, service, forms); hasFormContent = true; break; case "Forms Sections": ft.PrepareFormSections(sheet, service, forms); hasFormContent = true; break; case "Forms Fields": ft.PrepareFormLabels(sheet, service, forms); hasFormContent = true; break; case "Dashboards": if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Importing dashboard translations..."); } db.ImportFormName(sheet, service); break; case "Dashboards Tabs": db.PrepareFormTabs(sheet, service, forms); hasDashboardContent = true; break; case "Dashboards Sections": db.PrepareFormSections(sheet, service, forms); hasDashboardContent = true; break; case "Dashboards Fields": db.PrepareFormLabels(sheet, service, forms); hasDashboardContent = true; break; case "SiteMap Areas": st.PrepareAreas(sheet, service); hasSiteMapContent = true; break; case "SiteMap Groups": st.PrepareGroups(sheet, service); hasSiteMapContent = true; break; case "SiteMap SubAreas": st.PrepareSubAreas(sheet, service); hasSiteMapContent = true; break; } if (hasFormContent) { if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Importing form content translations..."); } ft.ImportFormsContent(service, forms); } if (hasDashboardContent) { if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Importing dashboard content translations..."); } db.ImportFormsContent(service, forms); } if (hasSiteMapContent) { if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Importing SiteMap translations..."); } st.Import(service); } } if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Publishing customizations..."); } var paxRequest = new PublishAllXmlRequest(); service.Execute(paxRequest); }
private void BwPublishAllDoWork(object sender, DoWorkEventArgs e) { var pubRequest = new PublishAllXmlRequest(); targetService.Execute(pubRequest); }
/// <summary> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// Create an organization-owned visualization. /// Retrieve the visualization. /// Update the visualization; update the name and set it as the default /// visualization for the Opportunity entity. /// Optionally delete any entity records that were created for this sample. /// </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(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetCRUDVisualization1> // Create a visualization // Set The presentation XML string. string presentationXml = @" <Chart Palette='BrightPastel'> <Series> <Series _Template_='All' ShadowOffset='2' BorderColor='64, 64, 64' BorderDashStyle='Solid' BorderWidth='1' IsValueShownAsLabel='true' Font='Tahoma, 6.75pt, GdiCharSet=0' LabelForeColor='100, 100, 100' CustomProperties='FunnelLabelStyle=Outside' ChartType='Funnel'> <SmartLabelStyle Enabled='True' /> <Points /> </Series> </Series> <ChartAreas> <ChartArea _Template_='All' BackColor='Transparent' BorderColor='Transparent' BorderDashStyle='Solid'> <Area3DStyle Enable3D='True' IsClustered='True'/> </ChartArea> </ChartAreas> <Legends> <Legend _Template_='All' Alignment='Center' LegendStyle='Table' Docking='Bottom' IsEquallySpacedItems='True' BackColor='White' BorderColor='228, 228, 228' BorderWidth='0' Font='Tahoma, 8pt, GdiCharSet=0' ShadowColor='0, 0, 0, 0' ForeColor='100, 100, 100'> </Legend> </Legends> <Titles> <Title _Template_='All' Font='Tahoma, 9pt, style=Bold, GdiCharSet=0' ForeColor='102, 102, 102'> </Title> </Titles> <BorderSkin PageColor='Control' BackColor='CornflowerBlue' BackSecondaryColor='CornflowerBlue' /> </Chart> "; // Set the data XML string. string dataXml = @" <datadefinition> <fetchcollection> <fetch mapping='logical' count='10' aggregate='true'> <entity name='opportunity'> <attribute name='actualvalue_base' aggregate='sum' alias='sum_actualvalue_base' /> <attribute name='stepname' groupby='true' alias='stepname' /> <order alias='stepname' descending='false'/> </entity> </fetch> </fetchcollection> <categorycollection> <category> <measurecollection> <measure alias='sum_actualvalue_base'/> </measurecollection> </category> </categorycollection> </datadefinition> "; //<snippetCRUDVisualization2> // Create the visualization entity instance. SavedQueryVisualization newOrgOwnedVisualization = new SavedQueryVisualization { Name = "Sample Visualization", Description = "Sample organization-owned visualization.", PresentationDescription = presentationXml, DataDescription = dataXml, PrimaryEntityTypeCode = Opportunity.EntityLogicalName, IsDefault = false }; _orgOwnedVisualizationId = _serviceProxy.Create(newOrgOwnedVisualization); //</snippetCRUDVisualization2> Console.WriteLine("Created {0}.", newOrgOwnedVisualization.Name); //</snippetCRUDVisualization1> // Retrieve the visualization SavedQueryVisualization retrievedOrgOwnedVisualization = (SavedQueryVisualization)_serviceProxy.Retrieve(SavedQueryVisualization.EntityLogicalName, _orgOwnedVisualizationId, new ColumnSet(true)); Console.WriteLine("Retrieved the visualization."); // Update the retrieved visualization // 1. Update the name. // 2. Update the data description string. string newDataXml = @"<datadefinition> <fetchcollection> <fetch mapping='logical' count='10' aggregate='true'> <entity name='opportunity'> <attribute name='estimatedvalue_base' aggregate='sum' alias='sum_estimatedvalue_base' /> <attribute name='name' groupby='true' alias='name' /> <order alias='name' descending='false'/> </entity> </fetch> </fetchcollection> <categorycollection> <category> <measurecollection> <measure alias='sum_estimatedvalue_base'/> </measurecollection> </category> </categorycollection> </datadefinition>"; retrievedOrgOwnedVisualization.Name = "Updated Sample Visualization"; retrievedOrgOwnedVisualization.DataDescription = newDataXml; _serviceProxy.Update(retrievedOrgOwnedVisualization); // Publish the changes to the solution. This step is only required // for organization-owned visualizations. PublishAllXmlRequest updateRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(updateRequest); Console.WriteLine("Updated the visualization."); 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; } }
public void PublishAll() { try { var request = new PublishAllXmlRequest(); innerService.Execute(request); } catch (FaultException<OrganizationServiceFault> error) { throw new Exception("An error while publishing archive: " + error.Message); } }
/// <summary> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// Link the custom attributes. /// Optionally delete any entity records that were created for this sample. /// </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(); //<snippetLinkCustomAttributesBetweenSeriesandInstances1> // Create a custom string attribute for the appointment instance StringAttributeMetadata customAppointmentInstanceAttribute = new StringAttributeMetadata { LogicalName = "new_customAppInstanceAttribute", DisplayName = new Label("CustomAppInstanceAttribute", 1033), Description = new Label("Sample Custom Appointment Instance Attribute", 1033), MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), SchemaName = "new_customAppInstanceAttribute" }; CreateAttributeRequest instanceAttributeRequest = new CreateAttributeRequest { Attribute = customAppointmentInstanceAttribute, EntityName = "appointment" }; CreateAttributeResponse instanceAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(instanceAttributeRequest); _instanceAttributeID = instanceAttributeResponse.AttributeId; // Create a custom string attribute for the recurring appointment master (series) StringAttributeMetadata customAppointmentSeriesAttribute = new StringAttributeMetadata { LogicalName = "new_customAppSeriesAttribute", DisplayName = new Label("CustomAppSeriesAttribute", 1033), Description = new Label("Sample Custom Appointment Series Attribute", 1033), MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), SchemaName = "new_customAppSeriesAttribute", LinkedAttributeId = _instanceAttributeID // Link the custom attribute to the appointment’s custom attribute. }; CreateAttributeRequest seriesAttributeRequest = new CreateAttributeRequest { Attribute = customAppointmentSeriesAttribute, EntityName = "recurringappointmentmaster" }; CreateAttributeResponse seriesAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(seriesAttributeRequest); _seriesAttributeID = seriesAttributeResponse.AttributeId; // Publish all the changes to the solution. PublishAllXmlRequest createRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(createRequest); Console.WriteLine("Created a custom string attribute, {0}, for the appointment.", customAppointmentInstanceAttribute.LogicalName); Console.WriteLine("Created a custom string attribute, {0}, for the recurring appointment, and linked it with {1}.", customAppointmentSeriesAttribute.LogicalName, customAppointmentInstanceAttribute.LogicalName); //</snippetLinkCustomAttributesBetweenSeriesandInstances1> 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; } }