protected override void BeginProcessing() { base.BeginProcessing(); SetSecurityProtocol(); WriteDebug("Connecting to CRM"); WriteVerbose("Creating CrmServiceClient with: " + ConnectionString); ServiceClient = new CrmServiceClient(ConnectionString); if (ServiceClient == null) { throw new PSArgumentException("Connection not established", "ConnectionString"); } if (ServiceClient.OrganizationServiceProxy == null) { throw new PSArgumentException("Connection not established. Last CRM error message:\n" + ServiceClient.LastCrmError, "ConnectionString"); } if (Timeout == 0) { ServiceClient.OrganizationServiceProxy.Timeout = new System.TimeSpan(0, 0, DefaultTime); } else { ServiceClient.OrganizationServiceProxy.Timeout = new System.TimeSpan(0, 0, Timeout); } Container = new CintContainer(new CrmServiceProxy(ServiceClient.OrganizationServiceProxy), CommandRuntime.ToString(), true); }
/// <summary> /// Deletes the provided web resource /// </summary> /// <param name="webResource">Web resource to delete</param> internal static void DeleteWebResource(this CintContainer container, CintDynEntity webResource) { try { webResource.Delete(); } catch (Exception error) { throw new Exception("Error while deleting web resource: " + error.Message); } }
/// <summary> /// Creates the provided web resource /// </summary> /// <param name="webResource">Web resource to create</param> internal static Guid CreateWebResource(this CintContainer container, CintDynEntity webResource) { try { return(webResource.Create()); } catch (Exception error) { throw new Exception("Error while creating web resource: " + error.Message); } }
/// <summary> /// Retrieves a specific web resource from its unique identifier /// </summary> /// <param name="webresourceId">Web resource unique identifier</param> /// <returns>Web resource</returns> internal static CintDynEntity RetrieveWebResource(this CintContainer container, Guid webresourceId) { try { return(CintDynEntity.Retrieve(container, "webresource", webresourceId, new ColumnSet(true))); } catch (Exception error) { throw new Exception("Error while retrieving web resource: " + error.Message); } }
private void UpdateWebResources(List <string> files, CintContainer container) { WriteObject(string.Format("Updating {0} webresources", files.Count)); var progress = new ProgressRecord(0, "UpdateWebResources", "Idle"); var fileno = 0; var updatecount = 0; foreach (var file in files) { fileno++; string crmpath = GetCrmPath(file); WriteVerbose(" " + crmpath); progress.StatusDescription = $"Retrieving {crmpath}"; progress.PercentComplete = (fileno * 50) / files.Count; WriteProgress(progress); var wr = WebResourceManager.RetrieveWebResource(container, crmpath); if (wr == null) { throw new ArgumentOutOfRangeException("file", crmpath, $"{crmpath} does not exist in target CRM. Make sure it is uploaded before updating."); } if (wr.Property("ismanaged", false)) { if (!UpdateManaged) { throw new ArgumentOutOfRangeException("file", crmpath, $"{crmpath} is managed in target CRM. Use parameter UpdateManaged to allow this."); } else { WriteWarning("Updating managed webresource: " + crmpath); } } fileno++; progress.StatusDescription = $"Updating {crmpath}"; progress.PercentComplete = (fileno * 50) / files.Count; WriteProgress(progress); var filecontent = Convert.ToBase64String(File.ReadAllBytes(file)); if (filecontent != wr.Property("content", string.Empty)) { var updatewr = wr.Clone(true); updatewr.AddProperty("content", filecontent); updatewr.Save(); WriteObject($"Updated {wr}"); updatecount++; } else { WriteVerbose($"No change: {wr}"); } } WriteObject($"Successfully updated {updatecount} webresources."); }
internal static bool HasDependencies(this CintContainer container, Guid webresourceId) { var request = new RetrieveDependenciesForDeleteRequest { ComponentType = SolutionComponentType.WebResource, ObjectId = webresourceId }; var response = (RetrieveDependenciesForDeleteResponse)container.Service.Execute(request); return(response.EntityCollection.Entities.Count != 0); }
private CintDynEntity GetAssembly(CintContainer container) { WriteObject($"Reading assembly file {AssemblyFile}"); var file = ReadFile(AssemblyFile); WriteVerbose("Loading assembly file"); var assembly = Assembly.Load(file); var chunks = assembly.FullName.Split(new string[] { ", ", "Version=", "Culture=", "PublicKeyToken=" }, StringSplitOptions.RemoveEmptyEntries); filename = chunks[0]; fileversion = new Version(chunks[1]); fileculture = chunks[2]; filetoken = chunks[3]; WriteObject($"Loaded assembly {filename} {fileversion}"); WriteVerbose("Culture: " + fileculture); WriteVerbose("Token : " + filetoken); var query = new QueryExpression("pluginassembly"); query.ColumnSet.AddColumns("name", "version", "ismanaged"); query.Criteria.AddCondition("name", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, filename); query.Criteria.AddCondition("version", Microsoft.Xrm.Sdk.Query.ConditionOperator.Like, fileversion.ToString(2) + "%"); query.Criteria.AddCondition("culture", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, fileculture); query.Criteria.AddCondition("publickeytoken", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, filetoken); var plugin = CintDynEntity.RetrieveMultiple(container, query).FirstOrDefault(); if (plugin != null) { WriteObject($"Found plugin: {plugin} {plugin.Property("version", "?")}"); if (plugin.Property("ismanaged", false)) { if (!UpdateManaged) { throw new ArgumentOutOfRangeException("AssemblyFile", AssemblyFile, "Assembly is managed in target CRM. Use parameter UpdateManaged to allow this."); } else { WriteWarning("Updating managed assembly"); } } return(plugin); } else { throw new ArgumentOutOfRangeException("AssemblyFile", AssemblyFile, "Assembly does not appear to be registered in CRM"); } }
internal static void AddToSolution(this CintContainer container, CintDynEntityCollection resources, string solutionUniqueName) { foreach (var resource in resources) { var request = new AddSolutionComponentRequest { AddRequiredComponents = false, ComponentId = resource.Id, ComponentType = SolutionComponentType.WebResource, SolutionUniqueName = solutionUniqueName }; container.Service.Execute(request); } }
/// <summary> /// Updates the provided web resource /// </summary> /// <param name="script">Web resource to update</param> internal static void UpdateWebResource(this CintContainer container, CintDynEntity wr) { try { var script = wr; if (!script.Contains("webresourceid")) { var existingEntity = container.RetrieveWebResource(script.Property("name", "")); if (existingEntity == null) { script.Id = container.CreateWebResource(script); } else { script.Id = existingEntity.Id; if (!script.Contains("displayname") && existingEntity.Contains("displayname")) { script.AddProperty("displayname", existingEntity.Property("displayname", "")); } if (!script.Contains("description") && existingEntity.Contains("description")) { script.AddProperty("description", existingEntity.Property("description", "")); } script.Save(); } } else { script.Save(); } } catch (Exception error) { throw new Exception("Error while updating web resource: " + error.Message); } }
internal static void PublishWebResources(this CintContainer container, CintDynEntityCollection resources) { try { string idsXml = string.Empty; foreach (var resource in resources) { idsXml += string.Format("<webresource>{0}</webresource>", resource.Id.ToString("B")); } var pxReq1 = new PublishXmlRequest { ParameterXml = string.Format("<importexportxml><webresources>{0}</webresources></importexportxml>", idsXml) }; container.Service.Execute(pxReq1); } catch (Exception error) { throw new Exception("Error while publishing web resources: " + error.Message); } }
/// <summary> /// Retrieves a specific web resource from its unique name /// </summary> /// <param name="name">Web resource unique name</param> /// <returns>Web resource</returns> internal static CintDynEntity RetrieveWebResource(this CintContainer container, string name) { try { var qba = new QueryByAttribute("webresource"); qba.Attributes.Add("name"); qba.Values.Add(name); qba.ColumnSet = new ColumnSet(true); var collection = CintDynEntity.RetrieveMultiple(container, qba); if (collection.Count > 1) { throw new Exception(string.Format("there are more than one web resource with name '{0}'", name)); } return(collection.FirstOrDefault()); } catch (Exception error) { throw new Exception("Error while retrieving web resource: " + error.Message); } }
private string Deploy(List <Module> selectedModules) { var packagefolder = Path.GetDirectoryName(packagefile); logfile = Path.Combine(packagefolder, DateTime.Now.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("HHmmss") + "_" + Path.GetFileName(packagefile).Replace(".cdpkg", "") + "_" + ConnectionDetail + ".log"); var container = new CintContainer(Service, logfile); var progress = new ShuffleCounter() { Modules = selectedModules.Count }; var created = 0; var updated = 0; var skipped = 0; var deleted = 0; var failed = 0; var returnmessage = string.Empty; UpdateCounters(0, 0, 0, 0, 0, 0); try { progress.ModuleNo = 0; ClearLog(); ClearProgressBars(false); AddLogText(container, $"Deploying package: {packagefile}", false); foreach (var module in selectedModules) { progress.ModuleNo++; progress.Module = module.ToString(); UpdateProgressBars(progress); DeployShuffleDefinition(container, module, packagefolder, ref created, ref updated, ref skipped, ref deleted, ref failed); UpdateCounters(progress.ModuleNo, created, updated, deleted, skipped, failed); } ClearProgressBars(true); } catch (Exception ex) { container.Logger.Log(ex); AddLogText(container, "_______________________________________________"); AddLogText(container, "ERROR: " + ex.Message); returnmessage = ex.Message; if (container.Logger is FileLogger) { AddLogText(container, "See detailed errors in file:"); var fileName = (container.Logger as FileLogger).FileName ?? "FileName not available"; AddLogText(container, $" {fileName}"); } else { AddLogText(container, "Activate logging to get details about this problem"); } } finally { AddLogText(container, ""); AddLogText(container, "Deployment completed"); //SaveLog(); container.Logger.CloseLog(); } return(returnmessage); }
private void btnShuffle_Click(object sender, EventArgs e) { lbLog.Items.Clear(); var type = cmbType.SelectedItem != null ? (SerializationType)cmbType.SelectedItem : SerializationType.Simple; WorkAsync(new WorkAsyncInfo("Doing the Shuffle...", (eventargs) => { shuffeling = true; EnableShuffle(); var logpath = Path.Combine(Paths.LogsPath, "ShuffleRunner"); var container = new CintContainer(new CrmServiceProxy(Service), logpath, true); var log = container.Logger; var location = System.Reflection.Assembly.GetExecutingAssembly().Location; var verinfo = FileVersionInfo.GetVersionInfo(location); log.Log(" *** {0} ***", verinfo.Comments.PadRight(50)); log.Log(" *** {0} ***", verinfo.LegalCopyright.PadRight(50)); log.Log(" *** {0} ***", (verinfo.InternalName + ", " + verinfo.FileVersion).PadRight(50)); var definition = new XmlDocument(); definition.Load(txtFile.Text); ReplaceShufflePlaceholders(definition); var definitionpath = Path.GetDirectoryName(txtFile.Text); try { if (rbExport.Checked) { var export = Shuffler.QuickExport(definition, type, ';', ShuffleEventHandler, container, definitionpath); if (export != null) { export.Save(txtData.Text); AddLogText("Export saved to: " + txtData.Text); } } else if (rbImport.Checked) { XmlDocument data = null; if (datafilerequired) { AddLogText("Loading data from: " + txtData.Text); data = ShuffleHelper.LoadDataFile(txtData.Text); } var importresult = Shuffler.QuickImport(definition, data, ShuffleEventHandler, container, definitionpath); AddLogText("---"); AddLogText(string.Format("Created: {0}", importresult.Item1)); AddLogText(string.Format("Updated: {0}", importresult.Item2)); AddLogText(string.Format("Skipped: {0}", importresult.Item3)); AddLogText(string.Format("Deleted: {0}", importresult.Item4)); AddLogText(string.Format("Failed : {0}", importresult.Item5)); AddLogText("---"); } } catch (Exception ex) { log.Log(ex); throw; } finally { log.CloseLog(); shuffeling = false; EnableShuffle(); } }) { PostWorkCallBack = (completedeventargs) => { if (completedeventargs.Error != null) { AddLogText(completedeventargs.Error.Message); } } }); }
/// <summary> /// Retrieves all web resources that are customizable /// </summary> /// <returns>List of web resources</returns> internal static CintDynEntityCollection RetrieveWebResources(this CintContainer container, Guid solutionId, List <int> types, bool hideMicrosoftWebresources) { try { if (solutionId == Guid.Empty) { var qe = new QueryExpression("webresource") { ColumnSet = new ColumnSet(true), Criteria = new FilterExpression { Filters = { new FilterExpression { FilterOperator = LogicalOperator.And, Conditions = { new ConditionExpression("ishidden", ConditionOperator.Equal, false), } }, new FilterExpression { FilterOperator = LogicalOperator.Or, Conditions = { new ConditionExpression("ismanaged", ConditionOperator.Equal, false), new ConditionExpression("iscustomizable", ConditionOperator.Equal, true), } } } }, Orders = { new OrderExpression("name", OrderType.Ascending) } }; if (hideMicrosoftWebresources) { qe.Criteria.Filters.First().Conditions.AddRange( new ConditionExpression("name", ConditionOperator.DoesNotBeginWith, "cc_MscrmControls"), new ConditionExpression("name", ConditionOperator.DoesNotBeginWith, "msdyn_") ); } if (types.Count != 0) { qe.Criteria.Filters.First().Conditions.Add(new ConditionExpression("webresourcetype", ConditionOperator.In, types.ToArray())); } return(CintDynEntity.RetrieveMultiple(container, qe)); } else { var qba = new QueryByAttribute("solutioncomponent") { ColumnSet = new ColumnSet(true) }; qba.Attributes.AddRange(new[] { "solutionid", "componenttype" }); qba.Values.AddRange(new object[] { solutionId, 61 }); var components = CintDynEntity.RetrieveMultiple(container, qba); var list = components.Select(component => component.Property("objectid", Guid.Empty).ToString("B")) .ToList(); if (list.Count > 0) { var qe = new QueryExpression("webresource") { ColumnSet = new ColumnSet(true), Criteria = new FilterExpression { Filters = { new FilterExpression { FilterOperator = LogicalOperator.And, Conditions = { new ConditionExpression("ishidden", ConditionOperator.Equal, false), new ConditionExpression("webresourceid", ConditionOperator.In, list.ToArray()), } }, new FilterExpression { FilterOperator = LogicalOperator.Or, Conditions = { new ConditionExpression("ismanaged", ConditionOperator.Equal, false), new ConditionExpression("iscustomizable", ConditionOperator.Equal, true), } } } }, Orders = { new OrderExpression("name", OrderType.Ascending) } }; if (types.Count != 0) { qe.Criteria.Filters.First().Conditions.Add(new ConditionExpression("webresourcetype", ConditionOperator.In, types.ToArray())); } return(CintDynEntity.RetrieveMultiple(container, qe)); } return(new CintDynEntityCollection()); } } catch (Exception error) { throw new Exception("Error while retrieving web resources: " + error.Message); } }