public static bool UpdateAndPublishSingle(CrmServiceClient client, List <Entity> webResources) { //CRM 2011 < UR12 try { OrganizationRequestCollection requests = CreateUpdateRequests(webResources); foreach (OrganizationRequest request in requests) { client.Execute(request); OutputLogger.WriteToOutputWindow(Resource.Message_UploadedWebResource, MessageType.Info); } string publishXml = CreatePublishXml(webResources); PublishXmlRequest publishRequest = CreatePublishRequest(publishXml); client.Execute(publishRequest); OutputLogger.WriteToOutputWindow(Resource.Message_PublishedWebResources, MessageType.Info); return(true); } catch (Exception ex) { ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorUpdatingPublishingWebResources, ex); return(false); } }
public static bool UpdateAndPublishSingle(CrmServiceClient client, List <Entity> webResources) { //CRM 2011 < UR12 try { OrganizationRequestCollection requests = CreateUpdateRequests(webResources); foreach (OrganizationRequest request in requests) { client.Execute(request); OutputLogger.WriteToOutputWindow("Uploaded Web Resource", MessageType.Info); } string publishXml = CreatePublishXml(webResources); PublishXmlRequest publishRequest = CreatePublishRequest(publishXml); client.Execute(publishRequest); OutputLogger.WriteToOutputWindow("Published Web Resource(s)", MessageType.Info); return(true); } catch (FaultException <OrganizationServiceFault> crmEx) { OutputLogger.WriteToOutputWindow("Error Updating And Publishing Web Resource(s) To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, MessageType.Error); return(false); } catch (Exception ex) { OutputLogger.WriteToOutputWindow("Error Updating And Publishing Web Resource(s) To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error); return(false); } }
private void PublishWebResources(OrganizationService orgService, List <WebResource> toBePublishedWebResources) { if (toBePublishedWebResources.Count < 1) { FinishingPublishing(_error, "There is no webresource to publish."); AddLineToOutputWindow("There is no webresource to publish."); return; } StartToPublish(); var webResourcesString = ""; foreach (var webResource in toBePublishedWebResources) { webResourcesString = webResourcesString + string.Format("<webresource>{0}</webresource>", webResource.Id); } var prequest = new PublishXmlRequest { ParameterXml = string.Format("<importexportxml><webresources>{0}</webresources></importexportxml>", webResourcesString) }; orgService.Execute(prequest); FinishingPublishing(_success, null); var webResourcesNames = new string[toBePublishedWebResources.Count]; for (var i = 0; i < toBePublishedWebResources.Count; i++) { webResourcesNames[i] = toBePublishedWebResources[i].Name; } AddLineToOutputWindow(string.Format("Published webresources : \n\t- {0}", string.Join("\n\t- ", webResourcesNames))); }
public static void PublishEntity(IOrganizationService service, string entityLogicalName, bool executeOutsideOfTrancation = false) { var request = new PublishXmlRequest(); request.ParameterXml = $"<importexportxml><entities><entity>{entityLogicalName}</entity></entities></importexportxml>"; if (executeOutsideOfTrancation) { var execMultipleRequest = new ExecuteMultipleRequest() { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings() { ContinueOnError = false, ReturnResponses = true } }; execMultipleRequest.Requests.Add(request); var response = (ExecuteMultipleResponse)service.Execute(execMultipleRequest); if (response.IsFaulted) { throw new InvalidPluginExecutionException("An error occured while publishing changes."); } } else { service.Execute(request); } }
/// <summary> /// Procedure: InsertGlobalOptionSet /// Handles: Inserts Values to existing optionset /// Created By: Steve Weinberger /// Created Date: 06/07/2016 /// Changes By: /// Changes Date: /// Changes Made: /// </summary> public void InsertGlobalOptionSet(IOrganizationService service, string solutionName, string schema, string label, int lang, string[] optionLabels) { string globalOptionSetName = schema; int _insertedOptionValue; OptionMetadataCollection options = new OptionMetadataCollection(); foreach (string o in optionLabels) { InsertOptionValueRequest req = new InsertOptionValueRequest() { SolutionUniqueName = solutionName, OptionSetName = globalOptionSetName, Label = new Label(o, lang) }; //InsertOptionValueResponse res = (InsertOptionValueResponse)service.Execute(req); _insertedOptionValue = ((InsertOptionValueResponse)service.Execute(req)).NewOptionValue; Console.WriteLine("Created {0} with the value of {1}.", req.Label.LocalizedLabels[0].Label, _insertedOptionValue); } //Publish the OptionSet PublishXmlRequest pxReq2 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", globalOptionSetName) }; service.Execute(pxReq2); Console.WriteLine("Global OptionSet inserted: {0}", schema); }
public static void ApplyImagesToEntities(List <EntityImageMap> mappings, IOrganizationService service) { foreach (var mapping in mappings) { if (mapping.ImageSize == 16) { mapping.Entity.IconSmallName = mapping.WebResourceName; } else { mapping.Entity.IconMediumName = mapping.WebResourceName; } var request = new UpdateEntityRequest { Entity = mapping.Entity }; service.Execute(request); } string parameter = mappings.Aggregate(string.Empty, (current, mapping) => current + ("<entity>" + mapping.Entity.LogicalName + "</entity>")); string parameterXml = string.Format("<importexportxml ><entities>{0}</entities></importexportxml>", parameter); var publishRequest = new PublishXmlRequest { ParameterXml = parameterXml }; service.Execute(publishRequest); }
public static void ApplyImagesToEntities(List<EntityImageMap> mappings, IOrganizationService service) { foreach (var mapping in mappings) { if (mapping.ImageSize == 16) { mapping.Entity.IconSmallName = mapping.WebResourceName; } else { mapping.Entity.IconMediumName = mapping.WebResourceName; } var request = new UpdateEntityRequest { Entity = mapping.Entity }; service.Execute(request); } string parameter = mappings.Aggregate(string.Empty, (current, mapping) => current + ("<entity>" + mapping.Entity.LogicalName + "</entity>")); string parameterXml = string.Format("<importexportxml ><entities>{0}</entities></importexportxml>", parameter); var publishRequest = new PublishXmlRequest { ParameterXml = parameterXml }; service.Execute(publishRequest); }
internal void PublishWebResources(List <WebResource> resources) { try { string idsXml = string.Empty; foreach (WebResource resource in resources) { idsXml += $"<webresource>{resource.Id:B}</webresource>"; } var pxReq1 = new PublishXmlRequest { ParameterXml = $"<importexportxml><webresources>{idsXml}</webresources></importexportxml>" }; innerService.Execute(pxReq1); foreach (var resource in resources) { resource.ReinitStatus(); } } catch (Exception error) { throw new Exception("Error while publishing web resources: " + error.Message); } }
public static void PublishXml(BackgroundWorker worker, IOrganizationService service) { string xml = "<importexportxml><entities></entities></importexportxml>"; var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); XmlNode parentNode = xmlDoc["importexportxml"]; if (FieldCreatorPluginControl.ImportGlobalOptionSets.Count > 0) { XmlNode globalOptionSetNode = xmlDoc.CreateNode(XmlNodeType.Element, "optionsets", ""); parentNode.AppendChild(globalOptionSetNode); } if (FieldCreatorPluginControl.ImportEntities.Count > 0) { IEnumerable <string> distinctEntityList = FieldCreatorPluginControl.ImportEntities.Distinct(); XmlNode entitiesNode = xmlDoc["importexportxml"]["entities"]; foreach (var entity in distinctEntityList) { XmlNode entityNode = xmlDoc.CreateNode(XmlNodeType.Element, "entity", ""); entityNode.InnerText = entity; entitiesNode.AppendChild(entityNode); } } worker.ReportProgress(100, "Publishing"); var publishRequest = new PublishXmlRequest { ParameterXml = xmlDoc.OuterXml.ToString() }; service.Execute(publishRequest); }
private void tsbPublish_Click(object sender, EventArgs e) { if (Service == null) { MessageBox.Show("Please connect to CRM.", ((ToolStripButton)sender).Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string entity = ViewEditor != null ? ViewEditor.ViewEntityName : null; if (string.IsNullOrEmpty(entity)) { MessageBox.Show("First select a view to design.", ((ToolStripButton)sender).Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } WorkAsync("Publishing changes", a => { var pubRequest = new PublishXmlRequest(); pubRequest.ParameterXml = string.Format("<importexportxml><entities><entity>{0}</entity></entities><nodes/><securityroles/><settings/><workflows/></importexportxml>", entity); Service.Execute(pubRequest); }, a => { if (a.Error != null) { MessageBox.Show(a.Error.Message, ((ToolStripButton)sender).Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } }); }
internal void PublishWebResources(List <WebResource> resources) { try { string idsXml = string.Empty; foreach (WebResource resource in resources) { idsXml += string.Format("<webresource>{0}</webresource>", resource.Entity.Id.ToString("B")); } var pxReq1 = new PublishXmlRequest { ParameterXml = string.Format("<importexportxml><webresources>{0}</webresources></importexportxml>", idsXml) }; innerService.Execute(pxReq1); foreach (var resource in resources) { resource.ReinitStatus(); resource.SyncedWithCrm = true; } } catch (Exception error) { throw new Exception("Error while publishing web resources: " + error.Message); } }
private static PublishXmlRequest CreatePublishRequest(string publishXml) { PublishXmlRequest pubRequest = new PublishXmlRequest { ParameterXml = publishXml }; return(pubRequest); }
public void PublishEntity(string entityName) { var request = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><entities><entity>{0}</entity></entities></importexportxml>", entityName) }; Service.Execute(request); }
public void PublishForm(Entity en) { var request = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><entities><entity>{0}</entity></entities></importexportxml>", en.GetAttributeValue <string>("objecttypecode")) }; _serviceProxy.Execute(request); }
private void publishWebResource() { PublishXmlRequest publishRequest = new PublishXmlRequest(); string webResctag = "<webresource>" + this.webResourceEntity.Id + "</webresource>"; string webrescXml = "<importexportxml><webresources>" + webResctag + "</webresources></importexportxml>"; publishRequest.ParameterXml = String.Format(webrescXml); Service.Execute(publishRequest); }
protected static void publishUpdatedEntity(CrmServiceClient service) { var publishXmlRequest = new PublishXmlRequest { ParameterXml = "<importexportxml><entities><entity>" + _customEntitySchemaName.ToLower() + "</entity></entities></importexportxml>" }; service.Execute(publishXmlRequest); }
//</snippetLabelQueryExpression2> protected void publishUpdatedEntity() { PublishXmlRequest publishXmlRequest = new PublishXmlRequest { ParameterXml = "<importexportxml><entities><entity>" + _customEntitySchemaName.ToLower() + "</entity></entities></importexportxml>" }; _service.Execute(publishXmlRequest); }
private void UpdateSiteMap() { if (siteMap == null) { var qe = new QueryExpression("sitemap"); qe.ColumnSet = new ColumnSet(true); EntityCollection ec = Service.RetrieveMultiple(qe); siteMap = ec[0]; siteMapDoc = new XmlDocument(); siteMapDoc.LoadXml(ec[0]["sitemapxml"].ToString()); } EnableControls(false); WorkAsync(new WorkAsyncInfo { Message = "Updating Sitemap...", Work = (bw, e) => { // Build the Xml SiteMap from SiteMap TreeView var doc = new XmlDocument(); XmlNode rootNode = doc.CreateElement("SiteMap"); doc.AppendChild(rootNode); AddXmlNode(tvSiteMap.Nodes[0], rootNode); siteMap["sitemapxml"] = doc.SelectSingleNode("SiteMap/SiteMap").OuterXml; siteMapDoc.LoadXml(doc.SelectSingleNode("SiteMap/SiteMap").OuterXml); Service.Update(siteMap); var request = new PublishXmlRequest(); request.ParameterXml = "<importexportxml><sitemaps><sitemap></sitemap></sitemaps></importexportxml>"; Service.Execute(request); }, PostWorkCallBack = e => { if (e.Error != null) { if (e.Error.Message.Contains("DefaultDashboard")) { MessageBox.Show(ParentForm, "Error while updating SiteMap: Defining 'DefaultDashboard' attribute on 'SubArea' element is only available in CRM 2013 and Microsoft Dynamics CRM Online Fall '13 Service Update", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show(ParentForm, "Error while updating SiteMap: " + e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } EnableControls(true); } }); }
public void CreateSiteMap() { QueryExpression query = new QueryExpression(); query.EntityName = "sitemap"; query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(true); EntityCollection col = _serviceProxy.RetrieveMultiple(query); Entity sitemap = null; if (col != null && col.Entities.Count > 0) { sitemap = col.Entities[0]; } string sitemapcontent = sitemap["sitemapxml"].ToString(); XDocument sitemapxml = XDocument.Parse(sitemapcontent); // create new area sitemapxml.Element("SiteMap") .Elements("Area") .Where(x => (string)x.Attribute("Id") == "DotsquaresPack") .Remove(); XElement root = new XElement("Area"); root.Add(new XAttribute("Id", "DotsquaresPack"), new XAttribute("ShowGroups", "true"), new XAttribute("Title", "DotsquaresPack")); //root.Add(new XElement("Group", // new XAttribute("Id", "Group_SubDotsquaresWebForm"), // new XAttribute("Title", "DotsquaresAutoNumber"), // new XElement("SubArea", new XAttribute("Id", "SubArea_dots_autonumber"), // new XAttribute("Entity", "dots_autonumber") // ))); root.Add(new XElement("Group", new XAttribute("Id", "Group_SubDotsquaresAutoSMSWebForm"), new XAttribute("Title", "DotsquaresAutoSMS"), new XElement("SubArea", new XAttribute("Id", "SubArea_dots_autosms"), new XAttribute("Entity", _customEntityName) ))); sitemapxml.Element("SiteMap").Add(root); sitemap["sitemapxml"] = sitemapxml.ToString(); _serviceProxy.Update(sitemap); PublishXmlRequest request = new PublishXmlRequest(); request.ParameterXml = "<importexportxml><sitemaps><sitemap></sitemap></sitemaps></importexportxml>"; _serviceProxy.Execute(request); }
private static void PublishWebResource(DTE dte, CrmServiceClient crmServiceClient, Guid webResourceId, string crmUrl, string webResourceName, string fileName) { var publishXml = $"<importexportxml><webresources><webresource>{webResourceId}</webresource></webresources></importexportxml>"; var request = new PublishXmlRequest { ParameterXml = publishXml }; crmServiceClient.Execute(request); UtilityPackage.SetDTEStatusBar(dte, $"Deployed: [{fileName}] to [{webResourceName}]"); }
public static void Publish(this IOrganizationService service, Guid[] resourceIds) { var publishXml = string.Concat("<importexportxml><webresources>", string.Join(string.Empty, resourceIds.Select(id => string.Format("<webresource>{0}</webresource>", id.ToString())).ToArray()), "</webresources></importexportxml>"); var publishReq = new PublishXmlRequest() { ParameterXml = publishXml }; service.Execute(publishReq); }
private static void DeployWebResource(DTE dte, CrmServiceClient crmServiceClient, string crmUrl, string fullFileName, string fileName, Guid webResourceId) { var requests = new OrganizationRequestCollection(); var webResource = new Entity("webresource") { Id = webResourceId }; webResource["content"] = Convert.ToBase64String(File.ReadAllBytes(fullFileName)); var request = new UpdateRequest { Target = webResource }; requests.Add(request); var publishXml = $"<importexportxml><webresources><webresource>{webResource.Id}</webresource></webresources></importexportxml>"; var pubRequest = new PublishXmlRequest { ParameterXml = publishXml }; requests.Add(pubRequest); var multipleRequest = new ExecuteMultipleRequest { Requests = requests, Settings = new ExecuteMultipleSettings { ContinueOnError = false, ReturnResponses = true } }; UtilityPackage.SetDTEStatusBar(dte, $"[{crmUrl}] Updating & Publishing WebResource"); var multipleResponse = (ExecuteMultipleResponse)crmServiceClient.Execute(multipleRequest); foreach (var response in multipleResponse.Responses) { if (response.Fault == null) { continue; } UtilityPackage.SetDTEStatusBar(dte, $"[{crmUrl}] Deploy WebResource failed"); return; } var webResourceName = string.Empty; var selected = DevKitSetting.SelectedWebResources.Where(x => x.FullFileName == fullFileName).FirstOrDefault(); if (selected != null) { webResourceName = selected.WebResourceName; } UtilityPackage.SetDTEStatusBar(dte, $"Deployed: [{fileName}] to [{webResourceName}]"); }
public void PublishForm(IOrganizationService service) { var request = new PublishXmlRequest { ParameterXml = string.Format("<importexportxml><entities><entity>{0}</entity></entities></importexportxml>", EntityLogicalName) }; service.Execute(request); }
public void When_calling_publish_xml_no_exception_is_raised() { var ctx = new XrmFakedContext(); var service = ctx.GetFakedOrganizationService(); var req = new PublishXmlRequest() { ParameterXml = "<somexml></somexml>" }; Assert.DoesNotThrow(() => service.Execute(req)); }
public void When_calling_publish_xml_exception_is_raised_if_parameter_xml_is_blank() { var ctx = new XrmFakedContext(); var service = ctx.GetFakedOrganizationService(); var req = new PublishXmlRequest() { ParameterXml = "" }; Assert.Throws<Exception>(() => service.Execute(req)); }
private void ExecutePublishXml( string contentEntities = null , string contentRibbons = null , string contentDashboards = null , string contentOptionSets = null , string contentSiteMaps = null , string contentWebResources = null ) { StringBuilder parameterXml = new StringBuilder(); if (!string.IsNullOrEmpty(contentEntities)) { parameterXml.AppendFormat("<entities>{0}</entities>", contentEntities).AppendLine(); } if (!string.IsNullOrEmpty(contentRibbons)) { parameterXml.AppendFormat("<ribbons>{0}</ribbons>", contentRibbons).AppendLine(); } if (!string.IsNullOrEmpty(contentDashboards)) { parameterXml.AppendFormat("<dashboards>{0}</dashboards>", contentDashboards).AppendLine(); } if (!string.IsNullOrEmpty(contentOptionSets)) { parameterXml.AppendFormat("<optionsets>{0}</optionsets>", contentOptionSets).AppendLine(); } if (!string.IsNullOrEmpty(contentSiteMaps)) { parameterXml.AppendFormat("<sitemaps>{0}</sitemaps>", contentSiteMaps).AppendLine(); } if (!string.IsNullOrEmpty(contentWebResources)) { parameterXml.AppendFormat("<webresources>{0}</webresources>", contentWebResources).AppendLine(); } if (parameterXml.Length == 0) { return; } var request = new PublishXmlRequest { ParameterXml = string.Format(_formatPublishWebResources, parameterXml.ToString()), }; _service.Execute(request); }
public void When_calling_publish_xml_exception_is_raised_if_parameter_xml_is_blank() { var ctx = new XrmFakedContext(); var service = ctx.GetFakedOrganizationService(); var req = new PublishXmlRequest() { ParameterXml = "" }; Assert.Throws <Exception>(() => service.Execute(req)); }
private void Publish() { var pubRequest = new PublishXmlRequest(); pubRequest.ParameterXml = string.Format(@"<importexportxml> <dashboards> <dashboard>{0}</dashboard> </dashboards> </importexportxml>", record.Id.ToString()); targetService.Execute(pubRequest); }
public void Publish() { var pubRequest = new PublishXmlRequest(); pubRequest.ParameterXml = string.Format(@"<importexportxml> <entities> <entity>{0}</entity> </entities> </importexportxml>", entity); service.Execute(pubRequest); }
public static void PublishWebResouce(IOrganizationService service, Guid webResourceId) { PublishXmlRequest publishxmlrequest = new PublishXmlRequest { ParameterXml = @"<importexportxml> <webresources> <webresource>{" + webResourceId.ToString() + @"}</webresource> </webresources> </importexportxml>" }; service.Execute(publishxmlrequest); }
public static void ResetIcons(EntityMetadata emd, IOrganizationService service) { emd.IconSmallName = ""; emd.IconMediumName = ""; emd.IconLargeName = ""; var request = new UpdateEntityRequest { Entity = emd }; service.Execute(request); string parameterXml = string.Format("<importexportxml ><entities><entity>{0}</entity></entities></importexportxml>", emd.LogicalName); var publishRequest = new PublishXmlRequest { ParameterXml = parameterXml }; service.Execute(publishRequest); }
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 void UpdateAndPublishSingle(CrmConnection connection, ProjectItem projectItem, Guid webResourceId) { try { _dte.StatusBar.Text = "Updating & publishing web resource..."; _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy); using (OrganizationService orgService = new OrganizationService(connection)) { string publishXml = "<importexportxml><webresources>"; Entity webResource = new Entity("webresource") { Id = webResourceId }; string extension = Path.GetExtension(projectItem.FileNames[1]); string content = extension != null && (extension.ToUpper() != ".TS") ? File.ReadAllText(projectItem.FileNames[1]) : File.ReadAllText(Path.ChangeExtension(projectItem.FileNames[1], ".js")); webResource["content"] = EncodeString(content); UpdateRequest request = new UpdateRequest { Target = webResource }; orgService.Execute(request); _logger.WriteToOutputWindow("Uploaded Web Resource", Logger.MessageType.Info); publishXml += "<webresource>{" + webResource.Id + "}</webresource>"; publishXml += "</webresources></importexportxml>"; PublishXmlRequest pubRequest = new PublishXmlRequest { ParameterXml = publishXml }; orgService.Execute(pubRequest); _logger.WriteToOutputWindow("Published Web Resource", Logger.MessageType.Info); } } catch (FaultException <OrganizationServiceFault> crmEx) { _logger.WriteToOutputWindow("Error Updating And Publishing Web Resource To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error); } catch (Exception ex) { _logger.WriteToOutputWindow("Error Updating And Publishing Web Resource To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error); } _dte.StatusBar.Clear(); _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); }
public void PublishForm(string entityName) { var request = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><entities><entity>{0}</entity></entities></importexportxml>", entityName) }; Service.Execute(request); }
private void UpdateAndPublishMultiple(CrmConnection connection, ProjectItem projectItem, Guid webResourceId) { try { ExecuteMultipleRequest emRequest = new ExecuteMultipleRequest { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings { ContinueOnError = false, ReturnResponses = true } }; OrganizationRequestCollection requests = new OrganizationRequestCollection(); string publishXml = "<importexportxml><webresources>"; Entity webResource = new Entity("webresource") { Id = webResourceId }; string extension = Path.GetExtension(projectItem.FileNames[1]); string content = extension != null && (extension.ToUpper() != ".TS") ? File.ReadAllText(projectItem.FileNames[1]) : File.ReadAllText(Path.ChangeExtension(projectItem.FileNames[1], ".js")); webResource["content"] = EncodeString(content); UpdateRequest request = new UpdateRequest { Target = webResource }; requests.Add(request); publishXml += "<webresource>{" + webResource.Id + "}</webresource>"; publishXml += "</webresources></importexportxml>"; PublishXmlRequest pubRequest = new PublishXmlRequest { ParameterXml = publishXml }; requests.Add(pubRequest); emRequest.Requests = requests; using (OrganizationService orgService = new OrganizationService(connection)) { _dte.StatusBar.Text = "Updating & publishing web resource..."; _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy); ExecuteMultipleResponse emResponse = (ExecuteMultipleResponse)orgService.Execute(emRequest); bool wasError = false; foreach (var responseItem in emResponse.Responses) { if (responseItem.Fault == null) continue; _logger.WriteToOutputWindow( "Error Updating And Publishing Web Resources To CRM: " + responseItem.Fault.Message + Environment.NewLine + responseItem.Fault.TraceText, Logger.MessageType.Error); wasError = true; } if (wasError) MessageBox.Show("Error Updating And Publishing Web Resources To CRM. See the Output Window for additional details."); else _logger.WriteToOutputWindow("Updated And Published Web Resource", Logger.MessageType.Info); } } catch (FaultException<OrganizationServiceFault> crmEx) { _logger.WriteToOutputWindow("Error Updating And Publishing Web Resource To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error); } catch (Exception ex) { _logger.WriteToOutputWindow("Error Updating And Publishing Web Resource To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error); } _dte.StatusBar.Clear(); _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); }
private void UpdateAndPublishSingle(CrmConnection connection, ProjectItem projectItem, Guid webResourceId) { try { _dte.StatusBar.Text = "Updating & publishing web resource..."; _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy); using (OrganizationService orgService = new OrganizationService(connection)) { string publishXml = "<importexportxml><webresources>"; Entity webResource = new Entity("webresource") { Id = webResourceId }; string extension = Path.GetExtension(projectItem.FileNames[1]); string content = extension != null && (extension.ToUpper() != ".TS") ? File.ReadAllText(projectItem.FileNames[1]) : File.ReadAllText(Path.ChangeExtension(projectItem.FileNames[1], ".js")); webResource["content"] = EncodeString(content); UpdateRequest request = new UpdateRequest { Target = webResource }; orgService.Execute(request); _logger.WriteToOutputWindow("Uploaded Web Resource", Logger.MessageType.Info); publishXml += "<webresource>{" + webResource.Id + "}</webresource>"; publishXml += "</webresources></importexportxml>"; PublishXmlRequest pubRequest = new PublishXmlRequest { ParameterXml = publishXml }; orgService.Execute(pubRequest); _logger.WriteToOutputWindow("Published Web Resource", Logger.MessageType.Info); } } catch (FaultException<OrganizationServiceFault> crmEx) { _logger.WriteToOutputWindow("Error Updating And Publishing Web Resource To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error); } catch (Exception ex) { _logger.WriteToOutputWindow("Error Updating And Publishing Web Resource To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error); } _dte.StatusBar.Clear(); _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); }
private void bwUpdateView_DoWork(object sender, DoWorkEventArgs e) { var bw = (BackgroundWorker) sender; service.Update((Entity)e.Argument); bw.ReportProgress(0, "Publishing..."); var request = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><entities><entity>{0}</entity></entities></importexportxml>", ((Entity)e.Argument).GetAttributeValue<string>("returnedtypecode")) }; service.Execute(request); e.Result = e.Argument; }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateImageAttributeDemoEntity() { //Create a Custom entity CreateEntityRequest createrequest = new CreateEntityRequest { //Define the entity Entity = new EntityMetadata { SchemaName = _customEntityName, DisplayName = new Label("Image Attribute Demo", 1033), DisplayCollectionName = new Label("Image Attribute Demos", 1033), Description = new Label("An entity created by an SDK sample to demonstrate how to upload and retrieve entity images.", 1033), OwnershipType = OwnershipTypes.UserOwned, IsActivity = false, }, // Define the primary attribute for the entity PrimaryAttribute = new StringAttributeMetadata { SchemaName = "sample_Name", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = StringFormatName.Text, DisplayName = new Label("Name", 1033), Description = new Label("The primary attribute for the Image Attribute Demo entity.", 1033) } }; _serviceProxy.Execute(createrequest); Console.WriteLine("The Image Attribute Demo entity has been created."); //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.ToLower(), Attribute = new ImageAttributeMetadata { SchemaName = "EntityImage", //The name is always EntityImage //Required level must be AttributeRequiredLevel.None RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), DisplayName = new Label("Image", 1033), Description = new Label("An image to show with this demonstration.", 1033) } }; _serviceProxy.Execute(createEntityImageRequest); Console.WriteLine("The Image attribute has been created."); //<snippetEntityImages5> QueryExpression qe = new QueryExpression("systemform"); qe.Criteria.AddCondition("type", ConditionOperator.Equal, 2); //main form qe.Criteria.AddCondition("objecttypecode", ConditionOperator.Equal, _customEntityName.ToLower()); qe.ColumnSet.AddColumn("formxml"); SystemForm ImageAttributeDemoMainForm = (SystemForm)_serviceProxy.RetrieveMultiple(qe).Entities[0]; XDocument ImageAttributeDemoMainFormXml = XDocument.Parse(ImageAttributeDemoMainForm.FormXml); //Set the showImage attribute so the entity image will be displayed ImageAttributeDemoMainFormXml.Root.SetAttributeValue("showImage", true); //Updating the entity form definition ImageAttributeDemoMainForm.FormXml = ImageAttributeDemoMainFormXml.ToString(); _serviceProxy.Update(ImageAttributeDemoMainForm); //</snippetEntityImages5> Console.WriteLine("The Image Attribute Demo main form has been updated to show images."); PublishXmlRequest pxReq1 = new PublishXmlRequest { ParameterXml = String.Format(@" <importexportxml> <entities> <entity>{0}</entity> </entities> </importexportxml>", _customEntityName.ToLower()) }; _serviceProxy.Execute(pxReq1); Console.WriteLine("The Image Attribute Demo entity was published"); }
private void PublishWebResources(OrganizationService orgService, List<WebResource> toBePublishedWebResources) { var webResourcesString = ""; foreach (var webResource in toBePublishedWebResources) webResourcesString = webResourcesString + string.Format("<webresource>{0}</webresource>", webResource.Id); var prequest = new PublishXmlRequest { ParameterXml = string.Format("<importexportxml><webresources>{0}</webresources></importexportxml>", webResourcesString) }; orgService.Execute(prequest); }
private void tsbPublish_Click(object sender, EventArgs e) { if (this.Service == null) { MessageBox.Show("Please connect to CRM.", "Publish", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string entity = ViewEditor != null ? ViewEditor.ViewEntityName : null; if (string.IsNullOrEmpty(entity)) { MessageBox.Show("First select a view to design.", "Publish", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } this.WorkAsync("Publishing changes", a => { var pubRequest = new PublishXmlRequest(); pubRequest.ParameterXml = string.Format("<importexportxml><entities><entity>{0}</entity></entities><nodes/><securityroles/><settings/><workflows/></importexportxml>", entity); this.Service.Execute(pubRequest); }, a => { if (a.Error != null) { MessageBox.Show(a.Error.Message, "Publish", MessageBoxButtons.OK, MessageBoxIcon.Error); } }); }
public void UpdateRuleFromSystemView(Entity systemView, Entity rule, BackgroundWorker worker = null) { var ruleToUpdate = new Entity("savedquery") { Id = rule.Id }; if (rule.GetAttributeValue<int>("querytype") == 256 || rule.GetAttributeValue<int>("querytype") == 131072) { // Remove Order nodes if Outlook template var fetchDoc = new XmlDocument(); fetchDoc.LoadXml(systemView.GetAttributeValue<string>("fetchxml")); var orderNodes = fetchDoc.SelectNodes("//order"); foreach (XmlNode orderNode in orderNodes) { orderNode.ParentNode.RemoveChild(orderNode); } rule["fetchxml"] = fetchDoc.OuterXml; } else { ruleToUpdate["fetchxml"] = systemView.GetAttributeValue<string>("fetchxml"); } service.Update(ruleToUpdate); if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, string.Format("Publishing entity '{0}'...", rule.GetAttributeValue<string>("returnedtypecode"))); } var request = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><entities><entity>{0}</entity></entities></importexportxml>", rule.GetAttributeValue<string>("returnedtypecode")) }; service.Execute(request); }
internal void PublishWebResources(List<WebResource> resources) { try { string idsXml = string.Empty; foreach (WebResource resource in resources) { idsXml += string.Format("<webresource>{0}</webresource>", resource.Entity.Id.ToString("B")); } var pxReq1 = new PublishXmlRequest { ParameterXml = string.Format("<importexportxml><webresources>{0}</webresources></importexportxml>", idsXml) }; innerService.Execute(pxReq1); } catch (Exception error) { throw new Exception("Error while publishing web resources: " + error.Message); } }
/// <summary> /// Create and configure the organization service proxy. /// Create a dashboard. /// Retrieve the dashboard. /// Update the dashboard. /// Delete the dashboard. /// </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(); //<snippetCRUDDashboards1> //Grab the default public view for opportunities. QueryExpression mySavedQuery = new QueryExpression { ColumnSet = new ColumnSet("savedqueryid"), EntityName = SavedQuery.EntityLogicalName, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "isdefault", Operator = ConditionOperator.Equal, Values = {true} }, new ConditionExpression { AttributeName = "querytype", Operator = ConditionOperator.Equal, Values = {0} }, new ConditionExpression { AttributeName = "returnedtypecode", Operator = ConditionOperator.Equal, Values = {Opportunity.EntityTypeCode} } } } }; //This query should return one and only one result. SavedQuery defaultOpportunityQuery = _serviceProxy.RetrieveMultiple(mySavedQuery) .Entities.Select(x => (SavedQuery)x).FirstOrDefault(); // Retrieve visualizations out of the system. // This sample assumes that you have the "Top Opportunities" // visualization that is installed with Microsoft Dynamics CRM. QueryByAttribute visualizationQuery = new QueryByAttribute { EntityName = SavedQueryVisualization.EntityLogicalName, ColumnSet = new ColumnSet("savedqueryvisualizationid"), Attributes = { "name" }, //If you do not have this visualization, you will need to change //this line. Values = { "Top Opportunities" } }; SavedQueryVisualization visualization = _serviceProxy.RetrieveMultiple(visualizationQuery). Entities.Select(x => (SavedQueryVisualization)x).FirstOrDefault(); //<snippetCRUDDashboards2> //This is the language code for U.S. English. If you are running this code //in a different locale, you will need to modify this value. int languageCode = 1033; //We set up our dashboard and specify the FormXml. Refer to the //FormXml schema in the Microsoft Dynamics CRM SDK for more information. SystemForm dashboard = new SystemForm { Name = "Sample Dashboard", Description = "Sample organization-owned dashboard.", FormXml = String.Format(@"<form> <tabs> <tab name='Test Dashboard' verticallayout='true'> <labels> <label description='Sample Dashboard' languagecode='{0}' /> </labels> <columns> <column width='100%'> <sections> <section name='Information Section' showlabel='false' showbar='false' columns='111'> <labels> <label description='Information Section' languagecode='{0}' /> </labels> <rows> <row> <cell colspan='1' rowspan='10' showlabel='false'> <labels> <label description='Top Opportunitiess - 1' languagecode='{0}' /> </labels> <control id='TopOpportunities' classid='{{E7A81278-8635-4d9e-8D4D-59480B391C5B}}'> <parameters> <ViewId>{1}</ViewId> <IsUserView>false</IsUserView> <RelationshipName /> <TargetEntityType>opportunity</TargetEntityType> <AutoExpand>Fixed</AutoExpand> <EnableQuickFind>false</EnableQuickFind> <EnableViewPicker>false</EnableViewPicker> <EnableJumpBar>false</EnableJumpBar> <ChartGridMode>Chart</ChartGridMode> <VisualizationId>{2}</VisualizationId> <EnableChartPicker>false</EnableChartPicker> <RecordsPerPage>10</RecordsPerPage> </parameters> </control> </cell> <cell colspan='1' rowspan='10' showlabel='false'> <labels> <label description='Top Opportunities - 2' languagecode='{0}' /> </labels> <control id='TopOpportunities2' classid='{{E7A81278-8635-4d9e-8D4D-59480B391C5B}}'> <parameters> <ViewId>{1}</ViewId> <IsUserView>false</IsUserView> <RelationshipName /> <TargetEntityType>opportunity</TargetEntityType> <AutoExpand>Fixed</AutoExpand> <EnableQuickFind>false</EnableQuickFind> <EnableViewPicker>false</EnableViewPicker> <EnableJumpBar>false</EnableJumpBar> <ChartGridMode>Grid</ChartGridMode> <VisualizationId>{2}</VisualizationId> <EnableChartPicker>false</EnableChartPicker> <RecordsPerPage>10</RecordsPerPage> </parameters> </control> </cell> </row> <row /> <row /> <row /> <row /> <row /> <row /> <row /> <row /> <row /> </rows> </section> </sections> </column> </columns> </tab> </tabs> </form>", languageCode, defaultOpportunityQuery.SavedQueryId.Value.ToString("B"), visualization.SavedQueryVisualizationId.Value.ToString("B")), IsDefault = false }; _dashboardId = _serviceProxy.Create(dashboard); //</snippetCRUDDashboards2> Console.WriteLine("Created {0}.", dashboard.Name); //Now we will retrieve the dashboard. SystemForm retrievedDashboard = (SystemForm)_serviceProxy.Retrieve(SystemForm.EntityLogicalName, _dashboardId, new ColumnSet(true)); Console.WriteLine("Retrieved the dashboard."); // Update the retrieved dashboard. Enable the chart picker on the chart. XDocument xDocument = XDocument.Parse(retrievedDashboard.FormXml); var chartPicker = (from control in xDocument.Descendants("control") where control.Attribute("id").Value == "TopOpportunities" select control.Descendants("EnableChartPicker").First() ).First(); chartPicker.Value = "true"; //Now we place the updated Xml back into the dashboard, and update it. retrievedDashboard.FormXml = xDocument.ToString(); _serviceProxy.Update(retrievedDashboard); // Publish the dashboard changes to the solution. // This is only required for organization-owned dashboards. PublishXmlRequest updateRequest = new PublishXmlRequest { ParameterXml = @"<dashboard>_dashboardId</dashboard>" }; _serviceProxy.Execute(updateRequest); Console.WriteLine("Updated the dashboard."); DeleteRequiredRecords(promptForDelete); //</snippetCRUDDashboards1> } } // 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 static void PublishForms(IOrganizationService service, IEnumerable<string> entities) { var entitiesToPublish = ""; entitiesToPublish = entities.Aggregate(entitiesToPublish, (current, e) => current + ("<entity>" + e + "</entity>")); var request = new PublishXmlRequest { ParameterXml = string.Format("<importexportxml><entities>{0}</entities></importexportxml>", entitiesToPublish) }; service.Execute(request); }
private void SaveGlobalOptionSet() { WorkAsync("Saving global optionset...", (w, e) => { var req = new RetrieveOptionSetRequest() { Name = ((Item)cboOptionSets.SelectedItem).Value, }; var resp = (RetrieveOptionSetResponse)Service.Execute(req); OptionSetMetadata md = (OptionSetMetadata)resp.OptionSetMetadata; //foreach (var option in md.Options) //{ // var delReq = new DeleteOptionValueRequest() // { // OptionSetName = md.Name, // Value = option.Value.Value // }; // Service.Execute(delReq); //} var data = (BindingList<Item>)dgvOptions.DataSource; var execMultiReq = new ExecuteMultipleRequest() { Settings = new Microsoft.Xrm.Sdk.ExecuteMultipleSettings() { ContinueOnError = true, ReturnResponses = false }, Requests = new Microsoft.Xrm.Sdk.OrganizationRequestCollection() }; foreach (var item in data) { var exists = (from o in md.Options where o.Value.Value == int.Parse(item.Value) select true).FirstOrDefault(); if (exists) { var upReq = new UpdateOptionValueRequest() { OptionSetName = md.Name, Label = new Microsoft.Xrm.Sdk.Label(item.Name, 1033), Value = int.Parse(item.Value) }; execMultiReq.Requests.Add(upReq); } else { var addReq = new InsertOptionValueRequest() { OptionSetName = md.Name, Label = new Microsoft.Xrm.Sdk.Label(item.Name, 1033), Value = int.Parse(item.Value) }; execMultiReq.Requests.Add(addReq); } } foreach (var item in md.Options) { var exists = (from d in data where int.Parse(d.Value) == item.Value.Value select true).FirstOrDefault(); if (!exists) { var delReq = new DeleteOptionValueRequest() { OptionSetName = md.Name, Value = item.Value.Value }; execMultiReq.Requests.Add(delReq); } } Service.Execute(execMultiReq); w.ReportProgress(50, "Publishing global optionset..."); PublishXmlRequest pxReq1 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", md.Name) }; Service.Execute(pxReq1); }, e => { }, e => { SetWorkingMessage(e.UserState.ToString()); } ); }
/// <summary> /// Updates the entity customizations and publishes the entity /// </summary> /// <param name="entityName"></param> private void EnableDuplicateDetectionForEntity(string entityName) { Console.WriteLine(String.Format("Retrieving entity metadata for {0}", entityName)); // Retrieve the entity metadata var crmEntity = ((RetrieveEntityResponse)_serviceProxy.Execute( new RetrieveEntityRequest { RetrieveAsIfPublished = true, LogicalName = entityName })).EntityMetadata; Console.WriteLine(String.Concat("Enabling duplicate for ", entityName)); // Update the duplicate detection flag crmEntity.IsDuplicateDetectionEnabled = new BooleanManagedProperty(true); // Update the entity metadata _serviceProxy.Execute(new UpdateEntityRequest { Entity = crmEntity }); Console.WriteLine(String.Concat("Publishing ", entityName, " entity")); // Publish the entity var publishRequest = new PublishXmlRequest { ParameterXml = String.Concat("<importexportxml><entities><entity>", entityName, "</entity></entities></importexportxml>"), }; _serviceProxy.Execute(publishRequest); }
private void UpdateSiteMap() { if (siteMap == null) { var qe = new QueryExpression("sitemap"); qe.ColumnSet = new ColumnSet(true); EntityCollection ec = Service.RetrieveMultiple(qe); siteMap = ec[0]; siteMapDoc = new XmlDocument(); siteMapDoc.LoadXml(ec[0]["sitemapxml"].ToString()); } EnableControls(false); WorkAsync("Updating Sitemap...", e => { // Build the Xml SiteMap from SiteMap TreeView var doc = new XmlDocument(); XmlNode rootNode = doc.CreateElement("SiteMap"); doc.AppendChild(rootNode); AddXmlNode(tvSiteMap.Nodes[0], rootNode); siteMap["sitemapxml"] = doc.SelectSingleNode("SiteMap/SiteMap").OuterXml; siteMapDoc.LoadXml(doc.SelectSingleNode("SiteMap/SiteMap").OuterXml); Service.Update(siteMap); var request = new PublishXmlRequest(); request.ParameterXml = "<importexportxml><sitemaps><sitemap></sitemap></sitemaps></importexportxml>"; Service.Execute(request); }, e => { if (e.Error != null) { if (e.Error.Message.Contains("DefaultDashboard")) { MessageBox.Show(ParentForm, "Error while updating SiteMap: Defining 'DefaultDashboard' attribute on 'SubArea' element is only available in CRM 2013 and Microsoft Dynamics CRM Online Fall '13 Service Update", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show(ParentForm, "Error while updating SiteMap: " + e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } EnableControls(true); }); }
/// <summary> /// Create a global option set. /// Set the options for that option set. /// Create a new reference to that option set on an entity. /// Update the option set's properties. /// Check the global option set for dependencies. /// Delete the option set. /// </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(); //<snippetWorkwithGlobalOptionSets1> //<snippetWorkwithGlobalOptionSets2> #region How to create global option set // Define the request object and pass to the service. CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { // Create a global option set (OptionSetMetadata). OptionSet = new OptionSetMetadata { Name = _globalOptionSetName, DisplayName = new Label("Example Option Set", _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("Open", _languageCode), null), new OptionMetadata(new Label("Suspended", _languageCode), null), new OptionMetadata(new Label("Cancelled", _languageCode), null), new OptionMetadata(new Label("Closed", _languageCode), null) } } }; // Execute the request. CreateOptionSetResponse optionsResp = (CreateOptionSetResponse)_serviceProxy.Execute(createOptionSetRequest); //</snippetWorkwithGlobalOptionSets2> #endregion How to create global option set // Store the option set's id as it will be needed to find all the // dependent components. _optionSetId = optionsResp.OptionSetId; Console.WriteLine("The global option set has been created."); #region How to create a picklist linked to the global option set //<snippetWorkwithGlobalOptionSets3> // Create a Picklist linked to the option set. // Specify which entity will own the picklist, and create it. CreateAttributeRequest createRequest = new CreateAttributeRequest { EntityName = Contact.EntityLogicalName, Attribute = new PicklistAttributeMetadata { SchemaName = "sample_examplepicklist", LogicalName = "sample_examplepicklist", DisplayName = new Label("Example Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), // In order to relate the picklist to the global option set, be sure // to specify the two attributes below appropriately. // Failing to do so will lead to errors. OptionSet = new OptionSetMetadata { IsGlobal = true, Name = _globalOptionSetName } } }; _serviceProxy.Execute(createRequest); //</snippetWorkwithGlobalOptionSets3> Console.WriteLine("Referring picklist attribute created."); #endregion How to create a picklist linked to the global option set #region How to update a global option set //<snippetWorkwithGlobalOptionSets4> // Use UpdateOptionSetRequest to update the basic information of an option // set. Updating option set values requires different messages (see below). UpdateOptionSetRequest updateOptionSetRequest = new UpdateOptionSetRequest { OptionSet = new OptionSetMetadata { DisplayName = new Label("Updated Option Set", _languageCode), Name = _globalOptionSetName, IsGlobal = true } }; _serviceProxy.Execute(updateOptionSetRequest); //Publish the OptionSet PublishXmlRequest pxReq1 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq1); //</snippetWorkwithGlobalOptionSets4> Console.WriteLine("Option Set display name changed."); #endregion How to update a global option set properties #region How to insert a new option item in a global option set //<snippetWorkwithGlobalOptionSets5> // Use InsertOptionValueRequest to insert a new option into a // global option set. InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest { OptionSetName = _globalOptionSetName, Label = new Label("New Picklist Label", _languageCode) }; // Execute the request and store the newly inserted option value // for cleanup, used in the later part of this sample. _insertedOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute( insertOptionValueRequest)).NewOptionValue; //Publish the OptionSet PublishXmlRequest pxReq2 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq2); //</snippetWorkwithGlobalOptionSets5> Console.WriteLine("Created {0} with the value of {1}.", insertOptionValueRequest.Label.LocalizedLabels[0].Label, _insertedOptionValue); #endregion How to insert a new option item in a global option set #region How to retrieve a global option set by it's name //<snippetWorkwithGlobalOptionSets6> // Use the RetrieveOptionSetRequest message to retrieve // a global option set by it's name. RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest { Name = _globalOptionSetName }; // Execute the request. RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)_serviceProxy.Execute( retrieveOptionSetRequest); Console.WriteLine("Retrieved {0}.", retrieveOptionSetRequest.Name); // Access the retrieved OptionSetMetadata. OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata; // Get the current options list for the retrieved attribute. OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray(); //</snippetWorkwithGlobalOptionSets6> #endregion How to retrieve a global option set by it's name #region How to update an option item in a picklist //<snippetWorkwithGlobalOptionSets7> // In order to change labels on option set values (or delete) option set // values, you must use UpdateOptionValueRequest // (or DeleteOptionValueRequest). UpdateOptionValueRequest updateOptionValueRequest = new UpdateOptionValueRequest { OptionSetName = _globalOptionSetName, // Update the second option value. Value = optionList[1].Value.Value, Label = new Label("Updated Option 1", _languageCode) }; _serviceProxy.Execute(updateOptionValueRequest); //Publish the OptionSet PublishXmlRequest pxReq3 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq3); //</snippetWorkwithGlobalOptionSets7> Console.WriteLine("Option Set option label changed."); #endregion How to update an option item in a picklist #region How to change the order of options of a global option set //<snippetWorkwithGlobalOptionSets8> // Change the order of the original option's list. // Use the OrderBy (OrderByDescending) linq function to sort options in // ascending (descending) order according to label text. // For ascending order use this: var updateOptionList = optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList(); // For descending order use this: // var updateOptionList = // optionList.OrderByDescending( // x => x.Label.LocalizedLabels[0].Label).ToList(); // Create the request. OrderOptionRequest orderOptionRequest = new OrderOptionRequest { // Set the properties for the request. OptionSetName = _globalOptionSetName, // Set the changed order using Select linq function // to get only values in an array from the changed option list. Values = updateOptionList.Select(x => x.Value.Value).ToArray() }; // Execute the request _serviceProxy.Execute(orderOptionRequest); //Publish the OptionSet PublishXmlRequest pxReq4 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq4); //</snippetWorkwithGlobalOptionSets8> Console.WriteLine("Option Set option order changed"); #endregion How to change the order of options of a global option set #region How to retrieve all global option sets //<snippetWorkwithGlobalOptionSets9> // Use RetrieveAllOptionSetsRequest to retrieve all global option sets. // Create the request. RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest = new RetrieveAllOptionSetsRequest(); // Execute the request RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse = (RetrieveAllOptionSetsResponse)_serviceProxy.Execute( retrieveAllOptionSetsRequest); // Now you can use RetrieveAllOptionSetsResponse.OptionSetMetadata property to // work with all retrieved option sets. if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0) { Console.WriteLine("All the global option sets retrieved as below:"); int count = 1; foreach (OptionSetMetadataBase optionSetMetadata in retrieveAllOptionSetsResponse.OptionSetMetadata) { Console.WriteLine("{0} {1}", count++, (optionSetMetadata.DisplayName.LocalizedLabels.Count >0)? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty); } } //</snippetWorkwithGlobalOptionSets9> #endregion How to retrieve all global option sets //</snippetWorkwithGlobalOptionSets1> 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 TsbApplyChangesClick(object sender, EventArgs e) { if (entityInfos.All(ei => ei.Action == ActionState.None) && attributeInfos.All(ai => ai.Action == ActionState.None)) return; gbEntities.Enabled = false; gbAttributes.Enabled = false; toolStripMenu.Enabled = false; WorkAsync("Updating entities...", (bw, evt) => { foreach (EntityInfo ei in entityInfos.OrderBy(entity => entity.Emd.LogicalName)) { if (ei.Action == ActionState.Added) { bw.ReportProgress(0,string.Format("Enabling entity '{0}' for audit...", ei.Emd.LogicalName)); ei.Emd.IsAuditEnabled.Value = true; } else if (ei.Action == ActionState.Removed) { bw.ReportProgress(0, string.Format("Disabling entity '{0}' for audit...", ei.Emd.LogicalName)); ei.Emd.IsAuditEnabled.Value = false; } else { continue; } var request = new UpdateEntityRequest { Entity = ei.Emd }; Service.Execute(request); ei.Action = ActionState.None; } bw.ReportProgress(0, "Updating attributes..."); foreach (AttributeInfo ai in attributeInfos.OrderBy(a => a.Amd.EntityLogicalName).ThenBy(a => a.Amd.LogicalName)) { if (ai.Action == ActionState.Added) { bw.ReportProgress(0, string.Format("Enabling attribute '{0}' ({1}) for audit...", ai.Amd.LogicalName, ai.Amd.EntityLogicalName)); ai.Amd.IsAuditEnabled.Value = true; } else if (ai.Action == ActionState.Removed) { bw.ReportProgress(0, string.Format("Disabling attribute '{0}' ({1}) for audit...", ai.Amd.LogicalName, ai.Amd.EntityLogicalName)); ai.Amd.IsAuditEnabled.Value = false; } else { continue; } var request = new UpdateAttributeRequest { Attribute = ai.Amd, EntityName = ai.Amd.EntityLogicalName }; Service.Execute(request); ai.Action = ActionState.None; } bw.ReportProgress(0, "Publishing changes..."); var publishRequest = new PublishXmlRequest { ParameterXml = "<importexportxml><entities>" }; foreach (EntityInfo ei in entityInfos.OrderBy(entity => entity.Emd.LogicalName)) { publishRequest.ParameterXml += string.Format("<entity>{0}</entity>", ei.Emd.LogicalName); } publishRequest.ParameterXml += "</entities><securityroles/><settings/><workflows/></importexportxml>"; Service.Execute(publishRequest); }, evt => { if (evt.Error != null) { MessageBox.Show(this, "An error occured: " + evt.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } gbEntities.Enabled = true; gbAttributes.Enabled = true; toolStripMenu.Enabled = true; tsbApplyChanges.Enabled = !((entityInfos.All(ei => ei.Action == ActionState.None) && attributeInfos.All(ai => ai.Action == ActionState.None))); }, evt => SetWorkingMessage(evt.UserState.ToString())); }
public void UpdateRuleFromSystemView(Entity systemView, Entity rule, BackgroundWorker worker = null) { var ruleToUpdate = new Entity("savedquery") { Id = rule.Id }; // Remove Order nodes if Outlook template and Offline template ruleToUpdate["fetchxml"] = RemoveFetchOrderNodes(systemView.GetAttributeValue<string>("fetchxml")); service.Update(ruleToUpdate); if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, string.Format("Publishing entity '{0}'...", rule.GetAttributeValue<string>("returnedtypecode"))); } var request = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><entities><entity>{0}</entity></entities></importexportxml>", rule.GetAttributeValue<string>("returnedtypecode")) }; service.Execute(request); }
private void PublishWebResources(OrganizationService orgService, List<WebResource> toBePublishedWebResources) { if (toBePublishedWebResources.Count < 1) { FinishingPublishing(_error, "There is no webresource to publish."); AddLineToOutputWindow("There is no webresource to publish."); return; } StartToPublish(); var webResourcesString = ""; foreach (var webResource in toBePublishedWebResources) webResourcesString = webResourcesString + string.Format("<webresource>{0}</webresource>", webResource.Id); var prequest = new PublishXmlRequest { ParameterXml = string.Format("<importexportxml><webresources>{0}</webresources></importexportxml>", webResourcesString) }; orgService.Execute(prequest); FinishingPublishing(_success, null); var webResourcesNames = new string[toBePublishedWebResources.Count]; for (var i = 0; i < toBePublishedWebResources.Count; i++) { webResourcesNames[i] = toBePublishedWebResources[i].Name; } AddLineToOutputWindow(string.Format("Published webresources : \n\t- {0}", string.Join("\n\t- ", webResourcesNames))); }
private void UpdateWebResources(List<WebResourceItem> items) { //TODO: Handle CRM 2011 w/o execute multiple ExecuteMultipleRequest emRequest = new ExecuteMultipleRequest { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings { ContinueOnError = false, ReturnResponses = true } }; OrganizationRequestCollection requests = new OrganizationRequestCollection(); string projectName = ((ComboBoxItem)Projects.SelectedItem).Content.ToString(); Project project = GetProjectByName(projectName); if (project == null) return; string publishXml = "<importexportxml><webresources>"; foreach (var webResourceItem in items) { Entity webResource = new Entity("webresource") { Id = webResourceItem.WebResourceId }; string filePath = Path.GetDirectoryName(project.FullName) + webResourceItem.BoundFile.Replace("/", "\\"); if (!File.Exists(filePath)) continue; string content = File.ReadAllText(filePath); webResource["content"] = EncodeString(content); UpdateRequest request = new UpdateRequest { Target = webResource }; requests.Add(request); publishXml += "<webresource>{" + webResource.Id + "}</webresource>"; } publishXml += "</webresources></importexportxml>"; PublishXmlRequest pubRequest = new PublishXmlRequest { ParameterXml = publishXml }; requests.Add(pubRequest); emRequest.Requests = requests; string connString = ((CrmConn)Connections.SelectedItem).ConnectionString; CrmConnection connection = CrmConnection.Parse(connString); using (OrganizationService orgService = new OrganizationService(connection)) { DisplayStatusMessage("Updating & publishing web resources"); ExecuteMultipleResponse emResponse = (ExecuteMultipleResponse)orgService.Execute(emRequest); foreach (var responseItem in emResponse.Responses) { if (responseItem.Fault == null) continue; //Some error - do something //TODO: handle error DisplayStatusMessage(String.Empty); return; } MessageBox.Show("Published");//change to status message that goes away itself DisplayStatusMessage(String.Empty); } }
private void BwPublishDoWork(object sender, DoWorkEventArgs e) { EntityMetadata currentEmd = entitiesCache.Find( emd => emd.DisplayName.UserLocalizedLabel.Label == e.Argument.ToString()); var pubRequest = new PublishXmlRequest(); pubRequest.ParameterXml = string.Format(@"<importexportxml> <entities> <entity>{0}</entity> </entities> <nodes/><securityroles/><settings/><workflows/> </importexportxml>", currentEmd.LogicalName); targetService.Execute(pubRequest); }
private void UpdateTheWebresource(string selectedFilePath, string connectionString) { try { OrganizationService orgService; var crmConnection = CrmConnection.Parse(connectionString); //to escape "another assembly" exception crmConnection.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); using (orgService = new OrganizationService(crmConnection)) { var isCreateRequest = false; var fileName = Path.GetFileName(selectedFilePath); var choosenWebresource = GetWebresource(orgService, fileName); AddLineToOutputWindow("Connected to : " + crmConnection.ServiceUri); if (choosenWebresource == null) { AddErrorLineToOutputWindow("Error : Selected file is not exist in CRM."); AddLineToOutputWindow("Creating new webresource.."); var createWebresoruce = new CreateWebResourceWindow(fileName); createWebresoruce.ShowDialog(); if (createWebresoruce.CreatedWebResource == null) { AddLineToOutputWindow("Creating new webresource is cancelled."); return; } isCreateRequest = true; choosenWebresource = createWebresoruce.CreatedWebResource; } choosenWebresource.Content = GetEncodedFileContents(selectedFilePath); if (isCreateRequest) { //create function returns, created webresource's guid. choosenWebresource.Id = orgService.Create(choosenWebresource); AddLineToOutputWindow("Webresource is created."); } else { AddLineToOutputWindow("Updating to Webresource.."); var updateRequest = new UpdateRequest { Target = choosenWebresource }; orgService.Execute(updateRequest); AddLineToOutputWindow("Webresource is updated."); } AddLineToOutputWindow("Publishing the webresource.."); var prequest = new PublishXmlRequest { ParameterXml = string.Format("<importexportxml><webresources><webresource>{0}</webresource></webresources></importexportxml>", choosenWebresource.Id) }; orgService.Execute(prequest); AddLineToOutputWindow("Webresource is published."); } _myStopwatch.Stop(); AddLineToOutputWindow(string.Format("Time : " + _myStopwatch.Elapsed)); } catch (Exception ex) { AddErrorLineToOutputWindow("Error : " + ex.Message); } }
private void TsbPublishEntityClick(object sender, EventArgs e) { if (lvEntities.SelectedItems.Count > 0) { tsbPublishEntity.Enabled = false; tsbPublishAll.Enabled = false; tsbSaveViews.Enabled = false; tsbLoadEntities.Enabled = false; WorkAsync("Publishing entity...", evt => { var pubRequest = new PublishXmlRequest(); pubRequest.ParameterXml = string.Format(@"<importexportxml> <entities> <entity>{0}</entity> </entities> <nodes/><securityroles/><settings/><workflows/> </importexportxml>", evt.Argument); 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; }, lvEntities.SelectedItems[0].Tag); } }
private void SaveView() { var currentAttributes = GetAttributesSignature(null); if (currentAttributes != attributesChecksum) { MessageBox.Show("Cannot save view, returned attributes must not be changed.\n\nExpected attributes:\n " + attributesChecksum.Replace("\n", "\n ") + "\nCurrent attributes:\n " + currentAttributes.Replace("\n", "\n "), "Cannot save view", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (View.LogicalName == "savedquery") { if (MessageBox.Show("This will update and publish the saved query in CRM.\n\nConfirm!", "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.Cancel) { return; } } var msg = View.LogicalName == "savedquery" ? "Saving and publishing {0}..." : "Saving {0}..."; WorkAsync(string.Format(msg, View["name"]), (eventargs) => { var xml = GetFetchString(false); Entity newView = new Entity(View.LogicalName); newView.Id = View.Id; newView.Attributes.Add("fetchxml", xml); Service.Update(newView); if (View.LogicalName == "savedquery") { var pubRequest = new PublishXmlRequest(); pubRequest.ParameterXml = string.Format( @"<importexportxml><entities><entity>{0}</entity></entities><nodes/><securityroles/><settings/><workflows/></importexportxml>", View["returnedtypecode"].ToString()); Service.Execute(pubRequest); LogUse("SaveView"); } View["fetchxml"] = xml; }, (completedargs) => { if (completedargs.Error != null) { MessageBox.Show(completedargs.Error.Message, "Save view", MessageBoxButtons.OK, MessageBoxIcon.Error); } }); }
private void tsbPublishEntity_Click(object sender, EventArgs e) { if (lvEntities.SelectedItems.Count > 0) { tsbPublishEntity.Enabled = false; tsbSaveAttributes.Enabled = false; tsbLoadEntities.Enabled = false; WorkAsync(new WorkAsyncInfo { Message = "Publishing entities...", AsyncArgument = lvEntities.SelectedItems[0].Tag, Work = (bw, evt) => { var currentEmd = (EntityMetadata)evt.Argument; var pubRequest = new PublishXmlRequest(); pubRequest.ParameterXml = string.Format(@"<importexportxml> <entities> <entity>{0}</entity> </entities> <nodes/><securityroles/><settings/><workflows/> </importexportxml>", currentEmd.LogicalName); Service.Execute(pubRequest); }, PostWorkCallBack = evt => { if (evt.Error != null) { string errorMessage = CrmExceptionHelper.GetErrorMessage(evt.Error, false); MessageBox.Show(ParentForm, errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } tsbPublishEntity.Enabled = true; tsbSaveAttributes.Enabled = true; tsbLoadEntities.Enabled = true; } }); } }