public static bool AddWebResourceToSolution(CrmServiceClient client, string uniqueName, Guid webResourceId) { try { var scRequest = new AddSolutionComponentRequest { ComponentType = 61, SolutionUniqueName = uniqueName, ComponentId = webResourceId }; client.Execute(scRequest); ExLogger.LogToFile(Logger, Resource.Message_NewWebResourceAddedSolution, LogLevel.Info); OutputLogger.WriteToOutputWindow(Resource.Message_NewWebResourceAddedSolution, MessageType.Info); return(true); } catch (Exception ex) { ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorAddingWebResourceSolution, ex); return(false); } }
public static bool AddAssemblyToSolution(CrmServiceClient client, Guid assemblyId, string uniqueName) { try { var scRequest = new AddSolutionComponentRequest { ComponentType = 91, SolutionUniqueName = uniqueName, ComponentId = assemblyId }; client.Execute(scRequest); ExLogger.LogToFile(Logger, $"{Resource.Message_AssemblyAddedSolution}: {uniqueName} - {assemblyId}", LogLevel.Info); OutputLogger.WriteToOutputWindow($"{Resource.Message_AssemblyAddedSolution}: {uniqueName} - {assemblyId}", MessageType.Info); return(true); } catch (Exception ex) { ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorAddingAssemblySolution, ex); return(false); } }
public static bool AddWebResourceToSolution(CrmServiceClient client, string uniqueName, Guid webResourceId) { try { AddSolutionComponentRequest scRequest = new AddSolutionComponentRequest { ComponentType = 61, SolutionUniqueName = uniqueName, ComponentId = webResourceId }; AddSolutionComponentResponse response = (AddSolutionComponentResponse)client.Execute(scRequest); OutputLogger.WriteToOutputWindow("New Web Resource Added To Solution: " + response.id, MessageType.Info); return(true); } catch (FaultException <OrganizationServiceFault> crmEx) { OutputLogger.WriteToOutputWindow( "Error adding web resource to solution: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, MessageType.Error); return(false); } catch (Exception ex) { OutputLogger.WriteToOutputWindow( "Error adding web resource to solution: " + ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error); return(false); } }
private void AddSolutionComponents(string solutionTargetUniqueName, IEnumerable <SolutionComponent> componentesOnlyInSource) { foreach (var component in componentesOnlyInSource.Where(c => c.ObjectId.HasValue && c.ComponentType != null).OrderBy(c => c.ComponentType.Value)) { AddSolutionComponentRequest request = new AddSolutionComponentRequest() { SolutionUniqueName = solutionTargetUniqueName, ComponentType = component.ComponentType.Value, ComponentId = component.ObjectId.Value, AddRequiredComponents = false, }; if (component.RootComponentBehaviorEnum == SolutionComponent.Schema.OptionSets.rootcomponentbehavior.Do_not_include_subcomponents_1) { request.DoNotIncludeSubcomponents = true; } else if (component.RootComponentBehaviorEnum == SolutionComponent.Schema.OptionSets.rootcomponentbehavior.Include_As_Shell_Only_2) { request.DoNotIncludeSubcomponents = true; request.IncludedComponentSettingsValues = new string[0]; } try { var response = (AddSolutionComponentResponse)_service.Execute(request); } catch (Exception ex) { Helpers.DTEHelper.WriteExceptionToOutput(_service.ConnectionData, ex); } } }
private static void AddSolutionComponentToSolution(IOrganizationService service, string solutionUniqueName, EntityReference objectRef) { if (GetRegisteredSolutionComponent(objectRef) == null) { var s = new AddSolutionComponentRequest { AddRequiredComponents = false, ComponentId = objectRef.Id, SolutionUniqueName = solutionUniqueName }; switch (objectRef.LogicalName) { case PluginAssembly.EntityLogicalName: s.ComponentType = (int)componenttype.PluginAssembly; break; case PluginType.EntityLogicalName: s.ComponentType = (int)componenttype.PluginType; break; case SdkMessageProcessingStep.EntityLogicalName: s.ComponentType = (int)componenttype.SDKMessageProcessingStep; break; case SdkMessageProcessingStepImage.EntityLogicalName: s.ComponentType = (int)componenttype.SDKMessageProcessingStepImage; break; } service.Execute(s); } }
public void AddExistingEntity(string entityLogicalName, bool addRequiredComponents, bool doNotIncludeSubcomponents) { using (var svc = new CrmServiceClient(connection)) { RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest() { LogicalName = entityLogicalName }; RetrieveEntityResponse retrieveEntityResponse = (RetrieveEntityResponse)svc.Execute(retrieveEntityRequest); AddSolutionComponentRequest addRequest = new AddSolutionComponentRequest() { ComponentType = (int)ComponentType.Entity, ComponentId = (Guid)retrieveEntityResponse.EntityMetadata.MetadataId, SolutionUniqueName = "samplesolution", AddRequiredComponents = addRequiredComponents, DoNotIncludeSubcomponents = doNotIncludeSubcomponents }; svc.Execute(addRequest); AddExistingComponentToSolution(ComponentType.SystemForm, "EA01497A-3AFD-45AF-8824-05179E65241F", "samplesolution"); AddExistingComponentToSolution(ComponentType.Attribute, "D2C12E2D-D487-EB11-A812-000D3A4C1CE8", "samplesolution"); } }
public static void AddToSolution(this IOrganizationService service, string solutionUniqueName, Guid[] resourceIds) { foreach (var id in resourceIds) { var solutionAddReq = new AddSolutionComponentRequest() { ComponentId = id, ComponentType = 61, SolutionUniqueName = solutionUniqueName }; service.Execute(solutionAddReq); } }
private bool CreateReport(Guid solutionId, string uniqueName, string name, string filePath, string relativePath, int viewableIndex) { try { CrmConnection connection = CrmConnection.Parse(_connection.ConnectionString); using (_orgService = new OrganizationService(connection)) { Entity report = new Entity("report"); report["name"] = name; report["bodytext"] = File.ReadAllText(filePath); report["reporttypecode"] = new OptionSetValue(1); //ReportingServicesReport report["filename"] = Path.GetFileName(filePath); report["languagecode"] = 1033; //TODO: handle multiple report["ispersonal"] = (viewableIndex == 0); Guid id = _orgService.Create(report); _logger.WriteToOutputWindow("Report Created: " + id, Logger.MessageType.Info); //Add to the choosen solution (not default) if (solutionId != new Guid("FD140AAF-4DF4-11DD-BD17-0019B9312238")) { AddSolutionComponentRequest scRequest = new AddSolutionComponentRequest { ComponentType = 31, SolutionUniqueName = uniqueName, ComponentId = id }; AddSolutionComponentResponse response = (AddSolutionComponentResponse)_orgService.Execute(scRequest); _logger.WriteToOutputWindow("New Report Added To Solution: " + response.id, Logger.MessageType.Info); } NewId = id; NewName = name; NewBoudndFile = relativePath; return(true); } } catch (FaultException <OrganizationServiceFault> crmEx) { _logger.WriteToOutputWindow("Error Creating Report: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error); return(false); } catch (Exception ex) { _logger.WriteToOutputWindow("Error Creating Report: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error); return(false); } }
public void AddExistingComponentToSolution(ComponentType type, string id, string solutionUniqueName) { using (var svc = new CrmServiceClient(connection)) { AddSolutionComponentRequest request = new AddSolutionComponentRequest() { ComponentType = (int)type, ComponentId = new Guid(id), SolutionUniqueName = solutionUniqueName }; svc.Execute(request); } }
private void AddComponentToCRMSolution(Guid componentId, int componentType, string solutionUniqueName, IOrganizationService crmService) { if (!string.IsNullOrEmpty(solutionUniqueName)) { AddSolutionComponentRequest addSolutionCompent = new AddSolutionComponentRequest(); addSolutionCompent.ComponentId = componentId; addSolutionCompent.SolutionUniqueName = solutionUniqueName; addSolutionCompent.ComponentType = componentType; crmService.Execute(addSolutionCompent); logMessages.Append(Environment.NewLine); logMessages.Append("Component Type : " + componentType + ", with GUID : " + componentId + " added to solution " + solutionUniqueName); } }
private void AddTypeToSolution(string solutionName, PluginType sdkPluginType) { // Find solution AddSolutionComponentRequest addToSolution = new AddSolutionComponentRequest() { ComponentType = (int)componenttype.PluginType, ComponentId = sdkPluginType.Id, SolutionUniqueName = solutionName }; _trace.WriteLine("Adding to solution '{0}'", solutionName); _service.Execute(addToSolution); }
private static void AddWebResourceToSolution(DTE dte, CrmServiceClient crmServiceClient, string solutionUniqueName, Guid webResourceId, string webResourceName) { var request = new AddSolutionComponentRequest { AddRequiredComponents = true, ComponentType = 61, ComponentId = webResourceId, SolutionUniqueName = solutionUniqueName }; crmServiceClient.Execute(request); UtilityPackage.SetDTEStatusBar(dte, $"[{webResourceName}] Added to solution: [{solutionUniqueName}]"); }
private void AddWebresourceToSolution(string solutionName, WebResource webresource) { // Find solution AddSolutionComponentRequest addToSolution = new AddSolutionComponentRequest() { AddRequiredComponents = true, ComponentType = (int)componenttype.WebResource, ComponentId = webresource.Id, SolutionUniqueName = solutionName }; _trace.WriteLine("Adding to solution '{0}'", solutionName); _service.Execute(addToSolution); }
private void AddAssemblyToSolution(string solutionName, PluginAssembly assembly) { // Find solution AddSolutionComponentRequest addToSolution = new AddSolutionComponentRequest() { AddRequiredComponents = true, ComponentType = (int)componenttype.PluginAssembly, ComponentId = assembly.Id, SolutionUniqueName = solutionName }; _trace.WriteLine("Adding to solution '{0}'", solutionName); _service.Execute(addToSolution); }
public void AddComponent(IOrganizationService service, string solutionName, int componentType, Guid componentid) { AppendTextBox("Attempting to add component to " + solutionName); AddSolutionComponentRequest addComponentRequest = new AddSolutionComponentRequest() { ComponentType = componentType, ComponentId = componentid, SolutionUniqueName = solutionName }; service.Execute(addComponentRequest); AppendTextBox("Component added successfully"); return; }
private void AddStepToSolution(string solutionName, SdkMessageProcessingStep sdkPluginType) { // Find solution AddSolutionComponentRequest addToSolution = new AddSolutionComponentRequest() { AddRequiredComponents = false, ComponentType = (int)componenttype.SDKMessageProcessingStep, ComponentId = sdkPluginType.Id, SolutionUniqueName = solutionName }; _trace.WriteLine("Adding to solution '{0}'", solutionName); _service.Execute(addToSolution); }
internal void AddToSolution(List<Guid> idsToPublish, string solutionUniqueName) { foreach (var id in idsToPublish) { var request = new AddSolutionComponentRequest { AddRequiredComponents = false, ComponentId = id, ComponentType = SolutionComponentType.WebResource, SolutionUniqueName = solutionUniqueName }; innerService.Execute(request); } }
internal void AddToSolution(List <WebResource> resources, string solutionUniqueName) { foreach (var resource in resources) { var request = new AddSolutionComponentRequest { AddRequiredComponents = false, ComponentId = resource.Entity.Id, ComponentType = SolutionComponentType.WebResource, SolutionUniqueName = solutionUniqueName }; innerService.Execute(request); } }
internal static void AddToSolution(this CrmServiceClient service, EntityCollection resources, string solutionUniqueName) { foreach (var resource in resources.Entities) { var request = new AddSolutionComponentRequest { AddRequiredComponents = false, ComponentId = resource.Id, ComponentType = SolutionComponentType.WebResource, SolutionUniqueName = solutionUniqueName }; service.Execute(request); } }
internal void AddToSolution(List <Guid> idsToPublish, string solutionUniqueName) { foreach (var id in idsToPublish) { var request = new AddSolutionComponentRequest { AddRequiredComponents = false, ComponentId = id, ComponentType = SolutionComponentType.WebResource, SolutionUniqueName = solutionUniqueName }; innerService.Execute(request); } }
internal void AddToSolution(List<WebResource> resources, string solutionUniqueName) { foreach (var resource in resources) { var request = new AddSolutionComponentRequest { AddRequiredComponents = false, ComponentId = resource.Entity.Id, ComponentType = SolutionComponentType.WebResource, SolutionUniqueName = solutionUniqueName }; innerService.Execute(request); } }
private void AddComponentToSolution(Guid componentId, int componentType, string solutionName) { if (string.IsNullOrEmpty(solutionName)) { return; } var request = new AddSolutionComponentRequest { AddRequiredComponents = false, ComponentId = componentId, ComponentType = componentType, SolutionUniqueName = solutionName }; OrganizationService.Execute(request); }
protected override void ProcessRecord() { base.ProcessRecord(); base.WriteVerbose(string.Format("Moving Solution Components from {0} to {1}", FromSolutionName, ToSolutionName)); using (var context = new CIContext(OrganizationService)) { var fromSolutionId = GetSolutionId(context, FromSolutionName); var toSolutionId = GetSolutionId(context, ToSolutionName); var fromSolutionComponents = (from s in context.SolutionComponentSet where s.SolutionId == new EntityReference(Solution.EntityLogicalName, fromSolutionId) orderby s.RootSolutionComponentId descending select new { s.Id, s.ComponentType, s.ObjectId, s.RootSolutionComponentId, s.IsMetadata }).ToList(); var toSolutionComponents = (from s in context.SolutionComponentSet where s.SolutionId == new EntityReference(Solution.EntityLogicalName, toSolutionId) select new { s.Id, s.ComponentType, s.ObjectId, s.RootSolutionComponentId }).ToList(); foreach (var solutionComponent in fromSolutionComponents) { if (toSolutionComponents.Exists(depen => depen.ObjectId == solutionComponent.ObjectId && depen.ComponentType.Value == solutionComponent.ComponentType.Value)) { continue; } var addReq = new AddSolutionComponentRequest() { ComponentId = (Guid)solutionComponent.ObjectId, ComponentType = (int)solutionComponent.ComponentType.Value, AddRequiredComponents = false, SolutionUniqueName = ToSolutionName }; if ((solutionComponent.IsMetadata ?? false) && fromSolutionComponents.Exists(depen => depen.RootSolutionComponentId == solutionComponent.Id)) { addReq.DoNotIncludeSubcomponents = true; base.WriteVerbose("DoNotIncludeSubcomponents set to true"); } OrganizationService.Execute(addReq); base.WriteVerbose(string.Format("Moved component from solution with Id : {0} and Type : {1}", solutionComponent.ObjectId, solutionComponent.ComponentType.Value)); } } }
private void CreateWebResource(XElement webResourceInfo) { try { //Create the Web Resource. WebResource wr = new WebResource() { Content = getEncodedFileContents(ActivePackage.Attribute("rootPath").Value + webResourceInfo.Attribute("filePath").Value), DisplayName = webResourceInfo.Attribute("displayName").Value, Description = webResourceInfo.Attribute("description").Value, LogicalName = WebResource.EntityLogicalName, Name = GetWebResourceFullNameIncludingPrefix(webResourceInfo) }; wr.WebResourceType = new OptionSetValue((int)ResourceExtensions.ConvertStringExtension(webResourceInfo.Attribute("type").Value)); //Special cases attributes for different web resource types. switch (wr.WebResourceType.Value) { case (int)ResourceExtensions.WebResourceType.Silverlight: wr.SilverlightVersion = "4.0"; break; } // ActivePublisher.CustomizationPrefix + "_/" + ActivePackage.Attribute("name").Value + webResourceInfo.Attribute("name").Value.Replace("\\", "/"), Guid theGuid = _serviceProxy.Create(wr); //If not the "Default Solution", create a SolutionComponent to assure it gets //associated with the ActiveSolution. Web Resources are automatically added //as SolutionComponents to the Default Solution. if (ActiveSolution.UniqueName != "Default") { AddSolutionComponentRequest scRequest = new AddSolutionComponentRequest(); scRequest.ComponentType = (int)componenttype.WebResource; scRequest.SolutionUniqueName = ActiveSolution.UniqueName; scRequest.ComponentId = theGuid; var response = (AddSolutionComponentResponse)_serviceProxy.Execute(scRequest); } } catch (Exception e) { AddMessage("Error: " + e.Message); return; } }
/// <summary> /// Create a new webressource /// </summary> /// <param name="webResourceInfo"></param> public Guid?Create(XElement webResourceInfo) { try { var type = (int)ResourceExtensions.ConvertStringExtension(webResourceInfo?.Attribute(WebResource.Type)?.Value); var optionsetValue = new OptionSetValue(type); var fullName = GetWebResourceFullNameIncludingPrefix(webResourceInfo); //Create the Web Resource. var wr = new Entities.WebResource { Content = GetEncodedFileContents(webResourceInfo?.Attribute(WebResource.FilePath)?.Value), DisplayName = webResourceInfo?.Attribute(WebResource.DisplayName)?.Value, Description = webResourceInfo?.Attribute(WebResource.Description)?.Value, LogicalName = Entities.WebResource.EntityLogicalName, Name = fullName, WebResourceType = optionsetValue }; var guid = Service.Create(wr); //If not the "Default Solution", create a SolutionComponent to assure it gets //associated with the ActiveSolution. Web Resources are automatically added //as SolutionComponents to the Default Solution. if (ActiveSolution.UniqueName != "Default") { var scRequest = new AddSolutionComponentRequest { ComponentType = (int)SolutionComponent.OptionSet.ComponentType.WebResource, SolutionUniqueName = ActiveSolution.UniqueName, ComponentId = guid }; Service.Execute(scRequest); } return(guid); } catch (Exception e) { err.Error("Error: " + e.Message); return(null); } }
public void AddComponent(int type, Guid id) { try { // Adding Component to server solution var request = new AddSolutionComponentRequest { ComponentType = type, SolutionUniqueName = currentSolution["uniquename"].ToString(), ComponentId = id }; service.Execute(request); } catch (Exception error) { throw new Exception("Error while adding solution component: " + error.Message); } }
private void AddWebResourceToSolution(Entity webResource) { var fetchData = new { objectid = Guid.Parse(webResource["webresourceid"].ToString()), componenttype = 61, uniquename = json.solution }; var fetchXml = $@" <fetch> <entity name='solutioncomponent'> <attribute name='solutioncomponentid' /> <filter type='and'> <condition attribute='objectid' operator='eq' value='{fetchData.objectid}'/> <condition attribute='componenttype' operator='eq' value='{fetchData.componenttype}'/> </filter> <link-entity name='solution' from='solutionid' to='solutionid'> <filter type='and'> <condition attribute='uniquename' operator='eq' value='{fetchData.uniquename}'/> </filter> </link-entity> </entity> </fetch>"; var rows = crmServiceClient.RetrieveMultiple(new FetchExpression(fetchXml)); if (rows.Entities.Count != 0) { return; } var request = new AddSolutionComponentRequest { AddRequiredComponents = true, ComponentType = 61, ComponentId = Guid.Parse(webResource["webresourceid"].ToString()), SolutionUniqueName = json.solution }; CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, "\tAdding WebResource: ", CliLog.ColorMagenta, $"{webResource["name"]} ", CliLog.ColorGreen, "to solution: ", CliLog.ColorMagenta, $"{json.solution}"); crmServiceClient.Execute(request); }
/// <summary> /// Method to add a component to a solution. /// </summary> /// <param name="solutionComponentType">The component type.</param> /// <param name="componentId">The component's identifier.</param> /// <param name="solutionUniqueName">The solution's unique name.</param> /// <returns>The result of the execution.</returns> public AddSolutionComponentResponse AddComponentToSolution(SolutionComponentType solutionComponentType, Guid componentId, string solutionUniqueName) { try { AddSolutionComponentRequest addSolutionComponentRequest = new AddSolutionComponentRequest() { ComponentType = (int)solutionComponentType, ComponentId = componentId, SolutionUniqueName = solutionUniqueName }; using (XrmService service = new XrmService(XRMConnectionString)) { return((AddSolutionComponentResponse)service.Execute(addSolutionComponentRequest)); } } catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { throw; } }
/// <summary> /// method copies components with the specified settings /// </summary> /// <param name="settings">copy settings</param> /// <returns>list of components</returns> private List <Entity> CopyComponents(CopySettings settings) { var components = this.RetrieveComponentsFromSolutions(settings.SourceSolutions.Select(s => s.Id).ToList(), settings.ComponentsTypes); if (settings.TargetSolutions.Count > 0) { foreach (var target in settings.TargetSolutions) { foreach (var component in components) { var request = new AddSolutionComponentRequest { AddRequiredComponents = false, ComponentId = component.GetAttributeValue <Guid>("objectid"), ComponentType = component.GetAttributeValue <OptionSetValue>("componenttype").Value, SolutionUniqueName = target.GetAttributeValue <string>("uniquename"), }; Singleton.SolutionFileInfoInstance.WebJobsLog.Append("<tr>"); Singleton.SolutionFileInfoInstance.WebJobsLog.Append("<td style='width:100px;background-color:powderblue;border: 1px solid #ccc'>"); this.GetComponentDetails(settings, target, component, component.GetAttributeValue <OptionSetValue>("componenttype").Value, component.GetAttributeValue <Guid>("objectid"), "componenttype", null); Singleton.SolutionFileInfoInstance.WebJobsLog.Append("</td>"); Singleton.SolutionFileInfoInstance.WebJobsLog.Append("</tr>"); request.DoNotIncludeSubcomponents = component.GetAttributeValue <OptionSetValue>("rootcomponentbehavior")?.Value == 1 || component.GetAttributeValue <OptionSetValue>("rootcomponentbehavior")?.Value == 2; this.service.Execute(request); } } } else { Singleton.SolutionFileInfoInstance.WebJobsLog.Append("<tr>"); Singleton.SolutionFileInfoInstance.WebJobsLog.Append("<td style='width:100px;background-color:powderblue;border: 1px solid #ccc'>"); Singleton.SolutionFileInfoInstance.WebJobsLog.Append("No Components to Display"); Singleton.SolutionFileInfoInstance.WebJobsLog.Append("</td>"); Singleton.SolutionFileInfoInstance.WebJobsLog.Append("</tr>"); } return(components); }
private void AddAssemblyToSolution(Entity workflow) { var fetchData = new { objectid = workflow["pluginassemblyid"].ToString(), componenttype = 91, uniquename = WorkflowJson.solution }; var fetchXml = $@" <fetch> <entity name='solutioncomponent'> <attribute name='solutioncomponentid' /> <filter type='and'> <condition attribute='objectid' operator='eq' value='{fetchData.objectid}'/> <condition attribute='componenttype' operator='eq' value='{fetchData.componenttype}'/> </filter> <link-entity name='solution' from='solutionid' to='solutionid'> <filter type='and'> <condition attribute='uniquename' operator='eq' value='{fetchData.uniquename}'/> </filter> </link-entity> </entity> </fetch>"; var rows = CrmServiceClient.RetrieveMultiple(new FetchExpression(fetchXml)); if (rows.Entities.Count != 0) { return; } var request = new AddSolutionComponentRequest { AddRequiredComponents = true, ComponentType = 91, ComponentId = Guid.Parse(workflow["pluginassemblyid"].ToString()), SolutionUniqueName = WorkflowJson.solution }; CliLog.WriteLine(CliLog.ColorRed, "Adding", CliLog.ColorGreen, " Assembly: ", CliLog.ColorCyan, $"{workflow["name"]} ", CliLog.ColorGreen, "to solution: ", CliLog.ColorCyan, $"{WorkflowJson.solution}"); CrmServiceClient.Execute(request); }
private void AddEntityToSolution(KeyValuePair <Guid, string> entity) { // Get the required entity var entMetadataId = entity.Key; if (entMetadataId == null) { throw new Exception("Could not retrieve entity metadata for " + entity.Value); } // Add the entity to the solution var addReq = new AddSolutionComponentRequest() { ComponentType = 1, // Entity ComponentId = (Guid)entMetadataId, SolutionUniqueName = SolutionUniqueName }; Crm.Service.Execute(addReq); }
private void AddStepToSolution(Entity step) { var fetchData = new { objectid = step["sdkmessageprocessingstepid"].ToString(), componenttype = 92, uniquename = PluginJson.solution }; var fetchXml = $@" <fetch> <entity name='solutioncomponent'> <attribute name='solutioncomponentid' /> <filter type='and'> <condition attribute='objectid' operator='eq' value='{fetchData.objectid}'/> <condition attribute='componenttype' operator='eq' value='{fetchData.componenttype}'/> </filter> <link-entity name='solution' from='solutionid' to='solutionid'> <filter type='and'> <condition attribute='uniquename' operator='eq' value='{fetchData.uniquename}'/> </filter> </link-entity> </entity> </fetch>"; var rows = CrmServiceClient.RetrieveMultiple(new FetchExpression(fetchXml)); if (rows.Entities.Count != 0) { return; } var request = new AddSolutionComponentRequest { AddRequiredComponents = false, ComponentType = 92, ComponentId = Guid.Parse(step["sdkmessageprocessingstepid"].ToString()), SolutionUniqueName = PluginJson.solution }; CliLog.WriteLine(CliLog.ColorRed, "\t\tAdding", CliLog.ColorGreen, " Step: ", CliLog.ColorCyan, $"{step["name"]} ", CliLog.ColorGreen, "to solution: ", CliLog.ColorCyan, $"{PluginJson.solution}"); CrmServiceClient.Execute(request); }
internal void CopyComponents(CopySettings settings, BackgroundWorker backgroundWorker) { backgroundWorker.ReportProgress(0,"Retrieving source solution(s) components..."); var components = RetrieveComponentsFromSolutions(settings.SourceSolutions.Select(s => s.Id).ToList(), settings.ComponentsTypes); foreach (var target in settings.TargetSolutions) { backgroundWorker.ReportProgress(0, string.Format("Adding {0} components to solution '{1}'", components.Count, target.GetAttributeValue<string>("friendlyname"))); foreach (var component in components) { var request = new AddSolutionComponentRequest { AddRequiredComponents = false, ComponentId =component.GetAttributeValue<Guid>("objectid"), ComponentType = component.GetAttributeValue<OptionSetValue>("componenttype").Value, SolutionUniqueName = target.GetAttributeValue<string>("uniquename") }; service.Execute(request); } } }
private bool CreateReport(Guid solutionId, string uniqueName, string name, string filePath, string relativePath, int viewableIndex) { try { CrmConnection connection = CrmConnection.Parse(_connection.ConnectionString); using (_orgService = new OrganizationService(connection)) { Entity report = new Entity("report"); report["name"] = name; report["bodytext"] = File.ReadAllText(filePath); report["reporttypecode"] = new OptionSetValue(1); //ReportingServicesReport report["filename"] = Path.GetFileName(filePath); report["languagecode"] = 1033; //TODO: handle multiple report["ispersonal"] = (viewableIndex == 0); Guid id = _orgService.Create(report); _logger.WriteToOutputWindow("Report Created: " + id, Logger.MessageType.Info); //Add to the choosen solution (not default) if (solutionId != new Guid("FD140AAF-4DF4-11DD-BD17-0019B9312238")) { AddSolutionComponentRequest scRequest = new AddSolutionComponentRequest { ComponentType = 31, SolutionUniqueName = uniqueName, ComponentId = id }; AddSolutionComponentResponse response = (AddSolutionComponentResponse)_orgService.Execute(scRequest); _logger.WriteToOutputWindow("New Report Added To Solution: " + response.id, Logger.MessageType.Info); } NewId = id; NewName = name; NewBoudndFile = relativePath; return true; } } catch (FaultException<OrganizationServiceFault> crmEx) { _logger.WriteToOutputWindow("Error Creating Report: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error); return false; } catch (Exception ex) { _logger.WriteToOutputWindow("Error Creating Report: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error); return false; } }
private bool CreateWebResource(Guid solutionId, string uniqueName, int type, string prefix, string name, string displayName, string filePath, string relativePath) { try { CrmConnection connection = CrmConnection.Parse(_connection.ConnectionString); using (_orgService = new OrganizationService(connection)) { Entity webResource = new Entity("webresource"); webResource["name"] = prefix + name; webResource["webresourcetype"] = new OptionSetValue(type); if (!string.IsNullOrEmpty(displayName)) webResource["displayname"] = displayName; if (type == 8) webResource["silverlightversion"] = "4.0"; string extension = Path.GetExtension(filePath); List<string> imageExs = new List<string>() { ".ICO", ".PNG", ".GIF", ".JPG" }; string content; //TypeScript if (extension != null && (extension.ToUpper() == ".TS")) { content = File.ReadAllText(Path.ChangeExtension(filePath, ".js")); webResource["content"] = EncodeString(content); } //Images else if (extension != null && imageExs.Any(s => extension.ToUpper().EndsWith(s))) { content = EncodedImage(filePath, extension); webResource["content"] = content; } //Everything else else { content = File.ReadAllText(filePath); webResource["content"] = EncodeString(content); } Guid id = _orgService.Create(webResource); _logger.WriteToOutputWindow("New Web Resource Created: " + id, Logger.MessageType.Info); //Add to the choosen solution (not default) if (solutionId != new Guid("FD140AAF-4DF4-11DD-BD17-0019B9312238")) { AddSolutionComponentRequest scRequest = new AddSolutionComponentRequest { ComponentType = 61, SolutionUniqueName = uniqueName, ComponentId = id }; AddSolutionComponentResponse response = (AddSolutionComponentResponse)_orgService.Execute(scRequest); _logger.WriteToOutputWindow("New Web Resource Added To Solution: " + response.id, Logger.MessageType.Info); } NewId = id; NewType = type; NewName = prefix + name; if (!string.IsNullOrEmpty(displayName)) NewDisplayName = displayName; NewBoundFile = relativePath; NewSolutionId = solutionId; return true; } } catch (FaultException<OrganizationServiceFault> crmEx) { _logger.WriteToOutputWindow("Error Creating Web Resource: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error); return false; } catch (Exception ex) { _logger.WriteToOutputWindow("Error Creating Web Resource: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error); return false; } }
/// <summary> /// Shows how to perform the following tasks with solutions: /// - Create a Publisher /// - Retrieve the Default Publisher /// - Create a Solution /// - Retrieve a Solution /// - Add an existing Solution Component /// - Remove a Solution Component /// - Export or Package a Solution /// - Install or Upgrade a solution /// - Delete a Solution /// </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(); //<snippetWorkWithSolutions1> //Define a new publisher Publisher _crmSdkPublisher = new Publisher { UniqueName = "sdksamples", FriendlyName = "Microsoft CRM SDK Samples", SupportingWebsiteUrl = "http://msdn.microsoft.com/en-us/dynamics/crm/default.aspx", CustomizationPrefix = "sample", EMailAddress = "*****@*****.**", Description = "This publisher was created with samples from the Microsoft Dynamics CRM SDK" }; //Does publisher already exist? QueryExpression querySDKSamplePublisher = new QueryExpression { EntityName = Publisher.EntityLogicalName, ColumnSet = new ColumnSet("publisherid", "customizationprefix"), Criteria = new FilterExpression() }; querySDKSamplePublisher.Criteria.AddCondition("uniquename", ConditionOperator.Equal, _crmSdkPublisher.UniqueName); EntityCollection querySDKSamplePublisherResults = _serviceProxy.RetrieveMultiple(querySDKSamplePublisher); Publisher SDKSamplePublisherResults = null; //If it already exists, use it if (querySDKSamplePublisherResults.Entities.Count > 0) { SDKSamplePublisherResults = (Publisher)querySDKSamplePublisherResults.Entities[0]; _crmSdkPublisherId = (Guid)SDKSamplePublisherResults.PublisherId; _customizationPrefix = SDKSamplePublisherResults.CustomizationPrefix; } //If it doesn't exist, create it if (SDKSamplePublisherResults == null) { _crmSdkPublisherId = _serviceProxy.Create(_crmSdkPublisher); Console.WriteLine(String.Format("Created publisher: {0}.", _crmSdkPublisher.FriendlyName)); _customizationPrefix = _crmSdkPublisher.CustomizationPrefix; } //</snippetWorkWithSolutions1> //<snippetWorkWithSolutions2> // Retrieve the Default Publisher //The default publisher has a constant GUID value; Guid DefaultPublisherId = new Guid("{d21aab71-79e7-11dd-8874-00188b01e34f}"); Publisher DefaultPublisher = (Publisher)_serviceProxy.Retrieve(Publisher.EntityLogicalName, DefaultPublisherId, new ColumnSet(new string[] {"friendlyname" })); EntityReference DefaultPublisherReference = new EntityReference { Id = DefaultPublisher.Id, LogicalName = Publisher.EntityLogicalName, Name = DefaultPublisher.FriendlyName }; Console.WriteLine("Retrieved the {0}.", DefaultPublisherReference.Name); //</snippetWorkWithSolutions2> //<snippetWorkWithSolutions3> // Create a Solution //Define a solution Solution solution = new Solution { UniqueName = "samplesolution", FriendlyName = "Sample Solution", PublisherId = new EntityReference(Publisher.EntityLogicalName, _crmSdkPublisherId), Description = "This solution was created by the WorkWithSolutions sample code in the Microsoft Dynamics CRM SDK samples.", Version = "1.0" }; //Check whether it already exists QueryExpression queryCheckForSampleSolution = new QueryExpression { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet(), Criteria = new FilterExpression() }; queryCheckForSampleSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solution.UniqueName); //Create the solution if it does not already exist. EntityCollection querySampleSolutionResults = _serviceProxy.RetrieveMultiple(queryCheckForSampleSolution); Solution SampleSolutionResults = null; if (querySampleSolutionResults.Entities.Count > 0) { SampleSolutionResults = (Solution)querySampleSolutionResults.Entities[0]; _solutionsSampleSolutionId = (Guid)SampleSolutionResults.SolutionId; } if (SampleSolutionResults == null) { _solutionsSampleSolutionId = _serviceProxy.Create(solution); } //</snippetWorkWithSolutions3> //<snippetWorkWithSolutions4> // Retrieve a solution String solutionUniqueName = "samplesolution"; QueryExpression querySampleSolution = new QueryExpression { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet(new string[] { "publisherid", "installedon", "version", "versionnumber", "friendlyname" }), Criteria = new FilterExpression() }; querySampleSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solutionUniqueName); Solution SampleSolution = (Solution)_serviceProxy.RetrieveMultiple(querySampleSolution).Entities[0]; //</snippetWorkWithSolutions4> //<snippetWorkWithSolutions5> // Add an existing Solution Component //Add the Account entity to the solution RetrieveEntityRequest retrieveForAddAccountRequest = new RetrieveEntityRequest() { LogicalName = Account.EntityLogicalName }; RetrieveEntityResponse retrieveForAddAccountResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveForAddAccountRequest); AddSolutionComponentRequest addReq = new AddSolutionComponentRequest() { ComponentType = (int)componenttype.Entity, ComponentId = (Guid)retrieveForAddAccountResponse.EntityMetadata.MetadataId, SolutionUniqueName = solution.UniqueName }; _serviceProxy.Execute(addReq); //</snippetWorkWithSolutions5> //<snippetWorkWithSolutions6> // Remove a Solution Component //Remove the Account entity from the solution RetrieveEntityRequest retrieveForRemoveAccountRequest = new RetrieveEntityRequest() { LogicalName = Account.EntityLogicalName }; RetrieveEntityResponse retrieveForRemoveAccountResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveForRemoveAccountRequest); RemoveSolutionComponentRequest removeReq = new RemoveSolutionComponentRequest() { ComponentId = (Guid)retrieveForRemoveAccountResponse.EntityMetadata.MetadataId, ComponentType = (int)componenttype.Entity, SolutionUniqueName = solution.UniqueName }; _serviceProxy.Execute(removeReq); //</snippetWorkWithSolutions6> //<snippetWorkWithSolutions7> // Export or package a solution //Export an a solution ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = false; exportSolutionRequest.SolutionName = solution.UniqueName; ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)_serviceProxy.Execute(exportSolutionRequest); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; string filename = solution.UniqueName + ".zip"; File.WriteAllBytes(outputDir + filename, exportXml); Console.WriteLine("Solution exported to {0}.", outputDir + filename); //</snippetWorkWithSolutions7> //<snippetWorkWithSolutions8> // Install or Upgrade a Solution byte[] fileBytes = File.ReadAllBytes(ManagedSolutionLocation); ImportSolutionRequest impSolReq = new ImportSolutionRequest() { CustomizationFile = fileBytes }; _serviceProxy.Execute(impSolReq); Console.WriteLine("Imported Solution from {0}", ManagedSolutionLocation); //</snippetWorkWithSolutions8> //<snippetWorkWithSolutions9> // Monitor import success byte[] fileBytesWithMonitoring = File.ReadAllBytes(ManagedSolutionLocation); ImportSolutionRequest impSolReqWithMonitoring = new ImportSolutionRequest() { CustomizationFile = fileBytes, ImportJobId = Guid.NewGuid() }; _serviceProxy.Execute(impSolReqWithMonitoring); Console.WriteLine("Imported Solution with Monitoring from {0}", ManagedSolutionLocation); ImportJob job = (ImportJob)_serviceProxy.Retrieve(ImportJob.EntityLogicalName, impSolReqWithMonitoring.ImportJobId, new ColumnSet(new System.String[] { "data", "solutionname" })); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(job.Data); String ImportedSolutionName = doc.SelectSingleNode("//solutionManifest/UniqueName").InnerText; String SolutionImportResult = doc.SelectSingleNode("//solutionManifest/result/@result").Value; Console.WriteLine("Report from the ImportJob data"); Console.WriteLine("Solution Unique name: {0}", ImportedSolutionName); Console.WriteLine("Solution Import Result: {0}", SolutionImportResult); Console.WriteLine(""); // This code displays the results for Global Option sets installed as part of a solution. System.Xml.XmlNodeList optionSets = doc.SelectNodes("//optionSets/optionSet"); foreach (System.Xml.XmlNode node in optionSets) { string OptionSetName = node.Attributes["LocalizedName"].Value; string result = node.FirstChild.Attributes["result"].Value; if (result == "success") { Console.WriteLine("{0} result: {1}",OptionSetName, result); } else { string errorCode = node.FirstChild.Attributes["errorcode"].Value; string errorText = node.FirstChild.Attributes["errortext"].Value; Console.WriteLine("{0} result: {1} Code: {2} Description: {3}",OptionSetName, result, errorCode, errorText); } } //</snippetWorkWithSolutions9> //<snippetWorkWithSolutions10> // Delete a solution QueryExpression queryImportedSolution = new QueryExpression { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet(new string[] { "solutionid", "friendlyname" }), Criteria = new FilterExpression() }; queryImportedSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, ImportedSolutionName); Solution ImportedSolution = (Solution)_serviceProxy.RetrieveMultiple(queryImportedSolution).Entities[0]; _serviceProxy.Delete(Solution.EntityLogicalName, (Guid)ImportedSolution.SolutionId); Console.WriteLine("Deleted the {0} solution.", ImportedSolution.FriendlyName); //</snippetWorkWithSolutions10> 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; } }
void BWorkerDoWork(object sender, DoWorkEventArgs e) { foreach (ListViewItem item in ListViewDelegates.GetItems(lvFiles)) { var fi = (FileInfo)item.Tag; var extension = fi.Extension.Remove(0, 1).ToLower(); var webR = new Entity("webresource"); webR["displayname"] = fi.Name; webR["webresourcetype"] = extension == "png" ? new OptionSetValue(5) : extension == "jpg" || extension == "jpeg" ? new OptionSetValue(6) : new OptionSetValue(7); webR["name"] = (txtPrefixToUse.Text + fi.Name).Replace(" ", ""); var fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read); var binaryData = new byte[fs.Length]; fs.Read(binaryData, 0, (int)fs.Length); fs.Close(); webR["content"] = Convert.ToBase64String(binaryData, 0, binaryData.Length); bool processed = false; if (CheckBoxDelegates.IsChecked(chkOverwriteExistingImages)) { var existingWr = _service.RetrieveMultiple(new QueryByAttribute { EntityName = "webresource", Attributes = {"name"}, Values = {webR["name"]} }).Entities.ToList().FirstOrDefault(); if (existingWr != null) { webR.Id = existingWr.Id; _service.Update(webR); processed = true; } } if (!processed) { Guid wrId = _service.Create(webR); webR.Id = wrId; } if (!CheckBoxDelegates.IsChecked(chkAddToDefaultSolution)) { var request = new AddSolutionComponentRequest { ComponentType = 61, SolutionUniqueName = cbbSolutions.SelectedItem.ToString(), ComponentId = webR.Id }; _service.Execute(request); } WebResourcesCreated.Add(webR); } }