Esempio n. 1
0
        private async Task RegisterNewPluginTypes(IOrganizationServiceExtented service, IEnumerable <string> typesToRegister, EntityReference assemblyRef, bool isWorkflowActivity, string workflowActivityGroupName)
        {
            foreach (var pluginType in typesToRegister.OrderBy(s => s))
            {
                var pluginTypeEntity = new PluginType()
                {
                    Name         = pluginType,
                    TypeName     = pluginType,
                    FriendlyName = pluginType,

                    PluginAssemblyId = assemblyRef,
                };

                if (isWorkflowActivity)
                {
                    pluginTypeEntity.WorkflowActivityGroupName = workflowActivityGroupName;
                }

                this._iWriteToOutput.WriteToOutput(service.ConnectionData, pluginType);

                try
                {
                    pluginTypeEntity.Id = await service.CreateAsync(pluginTypeEntity);
                }
                catch (Exception ex)
                {
                    this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.RegisteringPluginTypeFailedFormat2, service.ConnectionData.Name, pluginType);

                    _iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
                    _iWriteToOutput.ActivateOutputWindow(service.ConnectionData);
                }
            }
        }
        public async Task <Guid> UpsertAsync(Entity entity, Action <string> updateStatus)
        {
            Guid entityId = entity.Id;

            if (entity.Attributes.ContainsKey(PluginAssembly.EntityPrimaryIdAttribute) &&
                entity.Attributes[PluginAssembly.EntityPrimaryIdAttribute] != null &&
                entity.Attributes[PluginAssembly.EntityPrimaryIdAttribute] is Guid tempId
                )
            {
                entityId = tempId;
            }

            if (entityId == Guid.Empty)
            {
                return(await _service.CreateAsync(entity));
            }
            else
            {
                entity.Id = entityId;

                var exists = await GetByIdAsync(entityId, ColumnSetInstances.None);

                if (exists != null)
                {
                    var updateAssembly = await GetAssemblyByIdRetrieveRequestAsync(entityId, ColumnSetInstances.AllColumns);

                    foreach (var attribute in entity.Attributes)
                    {
                        updateAssembly.Attributes[attribute.Key] = attribute.Value;
                    }

                    updateAssembly.Id = entityId;
                    updateAssembly.PluginAssemblyId = entityId;

                    await _service.UpdateAsync(updateAssembly);

                    return(entityId);
                }
                else
                {
                    return(await _service.CreateAsync(entity));
                }
            }
        }
Esempio n. 3
0
        public async Task PerformUpdateRibbonDiffXml(IWriteToOutput iWriteToOutput, CommonConfiguration commonConfig, XDocument doc, EntityMetadata entityMetadata, RibbonCustomization ribbonCustomization)
        {
            if (entityMetadata == null && ribbonCustomization == null)
            {
                throw new ArgumentException("entityMetadata or ribbonCustomization");
            }

            ContentComparerHelper.ClearRoot(doc);

            Publisher publisherDefault = null;

            {
                var repositoryPublisher = new PublisherRepository(_service);
                publisherDefault = await repositoryPublisher.GetDefaultPublisherAsync();

                if (publisherDefault == null)
                {
                    iWriteToOutput.WriteToOutput(_service.ConnectionData, Properties.OutputStrings.NotFoundedDefaultPublisher);
                    iWriteToOutput.ActivateOutputWindow(_service.ConnectionData);
                    return;
                }
            }

            var idSolution = Guid.NewGuid();

            var solutionUniqueName = string.Format("RibbonDiffXml_{0}", idSolution);

            solutionUniqueName = solutionUniqueName.Replace("-", "_");

            var solution = new Solution()
            {
                UniqueName   = solutionUniqueName,
                FriendlyName = solutionUniqueName,

                SolutionId = idSolution,

                Description = "Temporary solution for exporting RibbonDiffXml.",

                PublisherId = publisherDefault.ToEntityReference(),

                Version = "1.0.0.0",
            };

            iWriteToOutput.WriteToOutput(_service.ConnectionData, Properties.OutputStrings.CreatingNewSolutionFormat1, solutionUniqueName);

            solution.Id = await _service.CreateAsync(solution);

            iWriteToOutput.WriteToOutputSolutionUri(_service.ConnectionData, solution.UniqueName, solution.Id);

            try
            {
                if (entityMetadata != null)
                {
                    iWriteToOutput.WriteToOutput(_service.ConnectionData, Properties.OutputStrings.InConnectionAddingInSolutionEntityFormat3, _service.ConnectionData.Name, solutionUniqueName, entityMetadata.LogicalName);

                    {
                        var repositorySolutionComponent = new SolutionComponentRepository(_service);

                        await repositorySolutionComponent.AddSolutionComponentsAsync(solutionUniqueName, new[] { new SolutionComponent()
                                                                                                                 {
                                                                                                                     ComponentType             = new OptionSetValue((int)ComponentType.Entity),
                                                                                                                     ObjectId                  = entityMetadata.MetadataId.Value,
                                                                                                                     RootComponentBehaviorEnum = SolutionComponent.Schema.OptionSets.rootcomponentbehavior.Include_Subcomponents_0,
                                                                                                                 } });
                    }

                    iWriteToOutput.WriteToOutput(_service.ConnectionData, Properties.OutputStrings.ExportingSolutionAndExtractingRibbonDiffXmlForEntityFormat2, solutionUniqueName, entityMetadata.LogicalName);
                }
                else if (ribbonCustomization != null)
                {
                    iWriteToOutput.WriteToOutput(_service.ConnectionData, Properties.OutputStrings.InConnectionAddingInSolutionApplicationRibbonFormat2, _service.ConnectionData.Name, solutionUniqueName);

                    {
                        var repositorySolutionComponent = new SolutionComponentRepository(_service);

                        await repositorySolutionComponent.AddSolutionComponentsAsync(solutionUniqueName, new[] { new SolutionComponent()
                                                                                                                 {
                                                                                                                     ComponentType             = new OptionSetValue((int)ComponentType.RibbonCustomization),
                                                                                                                     ObjectId                  = ribbonCustomization.Id,
                                                                                                                     RootComponentBehaviorEnum = SolutionComponent.Schema.OptionSets.rootcomponentbehavior.Include_Subcomponents_0,
                                                                                                                 } });
                    }

                    iWriteToOutput.WriteToOutput(_service.ConnectionData, Properties.OutputStrings.ExportingSolutionAndExtractingApplicationRibbonDiffXmlFormat1, solutionUniqueName);
                }

                string header = (entityMetadata != null) ? entityMetadata.LogicalName : "ApplicationRibbon";

                var repository = new ExportSolutionHelper(_service);

                var solutionBodyBinary = await repository.ExportSolutionAndGetBodyBinaryAsync(solutionUniqueName);

                {
                    string fileName = EntityFileNameFormatter.GetSolutionFileName(_service.ConnectionData.Name, solution.UniqueName, $"{header} Solution Backup", FileExtension.zip);

                    string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName));

                    File.WriteAllBytes(filePath, solutionBodyBinary);

                    iWriteToOutput.WriteToOutput(_service.ConnectionData, "Solution {0} Backup exported to {1}", solution.UniqueName, filePath);

                    iWriteToOutput.WriteToOutputFilePathUri(_service.ConnectionData, filePath);
                }

                string ribbonDiffXml = string.Empty;

                if (entityMetadata != null)
                {
                    ribbonDiffXml = ExportSolutionHelper.GetRibbonDiffXmlForEntityFromSolutionBody(entityMetadata.LogicalName, solutionBodyBinary);
                }
                else if (ribbonCustomization != null)
                {
                    ribbonDiffXml = ExportSolutionHelper.GetApplicationRibbonDiffXmlFromSolutionBody(solutionBodyBinary);
                }

                ribbonDiffXml = ContentComparerHelper.FormatXmlByConfiguration(
                    ribbonDiffXml
                    , commonConfig
                    , XmlOptionsControls.RibbonXmlOptions
                    , schemaName: AbstractDynamicCommandXsdSchemas.RibbonSchema
                    , entityName: entityMetadata?.LogicalName ?? string.Empty
                    );

                {
                    string filePath = string.Empty;

                    if (entityMetadata != null)
                    {
                        string fileName = EntityFileNameFormatter.GetEntityRibbonDiffXmlFileName(_service.ConnectionData.Name, entityMetadata.LogicalName, "BackUp", FileExtension.xml);
                        filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName));
                        iWriteToOutput.WriteToOutput(_service.ConnectionData, "{0} RibbonDiffXml BackUp exported to {1}", entityMetadata.LogicalName, filePath);
                    }
                    else if (ribbonCustomization != null)
                    {
                        string fileName = EntityFileNameFormatter.GetApplicationRibbonDiffXmlFileName(_service.ConnectionData.Name, "BackUp", FileExtension.xml);
                        filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName));
                        iWriteToOutput.WriteToOutput(_service.ConnectionData, "Application RibbonDiffXml BackUp exported to {0}", filePath);
                    }

                    File.WriteAllText(filePath, ribbonDiffXml, new UTF8Encoding(false));

                    iWriteToOutput.WriteToOutputFilePathUri(_service.ConnectionData, filePath);
                }

                if (entityMetadata != null)
                {
                    solutionBodyBinary = ExportSolutionHelper.ReplaceRibbonDiffXmlForEntityInSolutionBody(entityMetadata.LogicalName, solutionBodyBinary, doc.Root);
                }
                else if (ribbonCustomization != null)
                {
                    solutionBodyBinary = ExportSolutionHelper.ReplaceApplicationRibbonDiffXmlInSolutionBody(solutionBodyBinary, doc.Root);
                }

                {
                    string fileName = EntityFileNameFormatter.GetSolutionFileName(_service.ConnectionData.Name, solution.UniqueName, $"{header} Changed Solution Backup", FileExtension.zip);

                    string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName));

                    File.WriteAllBytes(filePath, solutionBodyBinary);

                    iWriteToOutput.WriteToOutput(_service.ConnectionData, "Changed Solution {0} Backup exported to {1}", solution.UniqueName, filePath);

                    iWriteToOutput.WriteToOutputFilePathUri(_service.ConnectionData, filePath);
                }

                iWriteToOutput.WriteToOutput(_service.ConnectionData, Properties.OutputStrings.ImportingSolutionFormat1, solutionUniqueName);

                await repository.ImportSolutionAsync(solutionBodyBinary);

                await DeleteSolution(iWriteToOutput, solution);

                {
                    var repositoryPublish = new PublishActionsRepository(_service);

                    if (entityMetadata != null)
                    {
                        iWriteToOutput.WriteToOutput(_service.ConnectionData, Properties.OutputStrings.InConnectionPublishingEntitiesFormat2, _service.ConnectionData.Name, entityMetadata.LogicalName);

                        await repositoryPublish.PublishEntitiesAsync(new[] { entityMetadata.LogicalName });
                    }
                    else if (ribbonCustomization != null)
                    {
                        iWriteToOutput.WriteToOutput(_service.ConnectionData, Properties.OutputStrings.InConnectionPublishingApplicationRibbonFormat1, _service.ConnectionData.Name);

                        await repositoryPublish.PublishApplicationRibbonAsync();
                    }
                }
            }
            finally
            {
                var task = DeleteSolution(iWriteToOutput, solution);
            }
        }
        private async Task RegisterSingleStep(StringBuilder log, SdkMessageRepository repositoryMessage, SdkMessageFilterRepository repositoryFilter, SystemUserRepository repositorySystemUser, Entities.PluginType entPluginType, Model.Backup.PluginStep step)
        {
            var entMessage = await repositoryMessage.FindMessageAsync(step.Message);

            if (entMessage == null)
            {
                log.AppendFormat("Message {0} not founded in CRM.", step.Message).AppendLine();
                return;
            }

            var refMessageFilter = await repositoryFilter.FindFilterAsync(entMessage.Id, step.PrimaryEntity, step.SecondaryEntity);

            EntityReference refSecure     = null;
            EntityReference refSystemUser = null;

            if (!string.IsNullOrEmpty(step.SecureConfiguration))
            {
                var entSecure = new Entity(Entities.SdkMessageProcessingStepSecureConfig.EntityLogicalName);
                entSecure.Attributes[Entities.SdkMessageProcessingStepSecureConfig.Schema.Attributes.secureconfig] = step.SecureConfiguration;

                entSecure.Id = await _service.CreateAsync(entSecure);

                refSecure = entSecure.ToEntityReference();
            }

            if (!string.IsNullOrEmpty(step.RunInUserContext) && step.RunInUserContext != "Calling User")
            {
                refSystemUser = repositorySystemUser.FindUser(step.RunInUserContext);
            }

            var entStep = new Entity(Entities.SdkMessageProcessingStep.EntityLogicalName)
            {
                Id = step.Id
            };

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.asyncautodelete] = step.AsyncAutoDelete.GetValueOrDefault();
            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.name]            = step.Name;
            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.description]     = step.Description;
            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.rank]            = step.ExecutionOrder;

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.stage] = new OptionSetValue((int)step.Stage);
            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.mode]  = new OptionSetValue((int)step.ExecutionMode);

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.supporteddeployment] = new OptionSetValue((int)step.SupportedDeploymentCode);

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.configuration] = step.UnsecureConfiguration;

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.filteringattributes] = string.Join(",", step.FilteringAttributes.OrderBy(s => s));

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.plugintypeid] = entPluginType.ToEntityReference();

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.eventhandler] = entPluginType.ToEntityReference();

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.sdkmessageid] = entMessage.ToEntityReference();

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.sdkmessagefilterid] = refMessageFilter;

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.sdkmessageprocessingstepsecureconfigid] = refSecure;

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.impersonatinguserid] = refSystemUser;

            entStep.Id = await _service.CreateAsync(entStep);

            foreach (var image in step.PluginImages)
            {
                var entImage = new Entity(Entities.SdkMessageProcessingStepImage.EntityLogicalName)
                {
                    Id = image.Id
                };

                entImage.Attributes[Entities.SdkMessageProcessingStepImage.Schema.Attributes.sdkmessageprocessingstepid] = entStep.ToEntityReference();

                entImage.Attributes[Entities.SdkMessageProcessingStepImage.Schema.Attributes.imagetype] = new OptionSetValue(image.ImageType.Value);

                entImage.Attributes[Entities.SdkMessageProcessingStepImage.Schema.Attributes.name]        = image.Name;
                entImage.Attributes[Entities.SdkMessageProcessingStepImage.Schema.Attributes.entityalias] = image.EntityAlias;

                entImage.Attributes[Entities.SdkMessageProcessingStepImage.Schema.Attributes.customizationlevel]   = image.CustomizationLevel;
                entImage.Attributes[Entities.SdkMessageProcessingStepImage.Schema.Attributes.relatedattributename] = image.RelatedAttributeName;
                entImage.Attributes[Entities.SdkMessageProcessingStepImage.Schema.Attributes.messagepropertyname]  = image.MessagePropertyName;

                entImage.Attributes[Entities.SdkMessageProcessingStepImage.Schema.Attributes.attributes] = string.Join(",", image.Attributes.OrderBy(s => s));

                entImage.Id = await _service.CreateAsync(entImage);
            }

            _service.Execute(new SetStateRequest()
            {
                EntityMoniker = entStep.ToEntityReference(),

                State  = new OptionSetValue(step.StateCode.Value),
                Status = new OptionSetValue(step.StatusCode.Value),
            });
        }
        private async Task PerformSaveClick()
        {
            if (_assemblyLoad == null)
            {
                return;
            }

            if (_listMissingCrm.Count > 0)
            {
                return;
            }

            string workflowActivityGroupName = txtBWorkflowActivityGroupName.Text.Trim();

            var updateAssembly = new PluginAssembly();

            if (PluginAssembly.PluginAssemblyId.HasValue)
            {
                updateAssembly.Id = PluginAssembly.PluginAssemblyId.Value;
                updateAssembly.PluginAssemblyId = PluginAssembly.PluginAssemblyId;
            }
            else
            {
                updateAssembly.Name = _assemblyLoad.Name;
            }

            updateAssembly.Description = txtBDescription.Text.Trim();

            var isolationMode = GetIsolationMode();
            var sourceType    = GetSourceType();

            updateAssembly.IsolationMode  = new Microsoft.Xrm.Sdk.OptionSetValue(isolationMode);
            updateAssembly.SourceType     = new Microsoft.Xrm.Sdk.OptionSetValue(sourceType);
            updateAssembly.Version        = _assemblyLoad.Version;
            updateAssembly.Culture        = _assemblyLoad.Culture;
            updateAssembly.PublicKeyToken = _assemblyLoad.PublicKeyToken;

            if (sourceType == (int)PluginAssembly.Schema.OptionSets.sourcetype.Database_0 &&
                _assemblyLoad.Content != null &&
                _assemblyLoad.Content.Length > 0
                )
            {
                updateAssembly.Content = Convert.ToBase64String(_assemblyLoad.Content);
            }

            if (sourceType == (int)PluginAssembly.Schema.OptionSets.sourcetype.Disk_1)
            {
                updateAssembly.Path = txtBFileNameOnServer.Text.Trim();
            }
            else
            {
                updateAssembly.Path = string.Empty;
            }

            var listToRegister = _listLocalAssembly.Where(p => p.IsChecked).ToList();

            _service.ConnectionData.AddAssemblyMapping(_assemblyLoad.Name, _assemblyLoad.FilePath);
            _service.ConnectionData.Save();

            ToggleControls(false, Properties.WindowStatusStrings.UpdatingPluginAssemblyFormat1, _service.ConnectionData.Name);

            try
            {
                this.PluginAssembly.Id = await _service.UpsertAsync(updateAssembly);

                if (listToRegister.Any())
                {
                    var assemblyRef = this.PluginAssembly.ToEntityReference();

                    ToggleControls(false, Properties.WindowStatusStrings.RegisteringNewPluginTypesFormat2, _service.ConnectionData.Name, listToRegister.Count);

                    foreach (var pluginType in listToRegister)
                    {
                        var pluginTypeEntity = new PluginType()
                        {
                            Name         = pluginType.Name,
                            TypeName     = pluginType.Name,
                            FriendlyName = pluginType.Name,

                            PluginAssemblyId = assemblyRef,
                        };

                        if (pluginType.IsWorkflowActivity)
                        {
                            pluginTypeEntity.WorkflowActivityGroupName = workflowActivityGroupName;
                        }

                        ToggleControls(false, Properties.WindowStatusStrings.RegisteringPluginTypeFormat2, _service.ConnectionData.Name, pluginType);

                        try
                        {
                            pluginTypeEntity.Id = await _service.CreateAsync(pluginTypeEntity);

                            ToggleControls(true, Properties.WindowStatusStrings.RegisteringPluginTypeCompletedFormat2, _service.ConnectionData.Name, pluginType);
                        }
                        catch (Exception ex)
                        {
                            ToggleControls(true, Properties.WindowStatusStrings.RegisteringPluginTypeFailedFormat2, _service.ConnectionData.Name, pluginType);

                            _iWriteToOutput.WriteErrorToOutput(_service.ConnectionData, ex);
                            _iWriteToOutput.ActivateOutputWindow(_service.ConnectionData);
                        }
                    }

                    ToggleControls(true, Properties.WindowStatusStrings.RegisteringNewPluginTypesCompletedFormat2, _service.ConnectionData.Name, listToRegister.Count);
                }

                ToggleControls(true, Properties.WindowStatusStrings.UpdatingPluginAssemblyCompletedFormat1, _service.ConnectionData.Name);

                this.DialogResult = true;

                this.Close();
            }
            catch (Exception ex)
            {
                ToggleControls(true, Properties.WindowStatusStrings.UpdatingPluginAssemblyFailedFormat1, _service.ConnectionData.Name);

                _iWriteToOutput.WriteErrorToOutput(_service.ConnectionData, ex);
                _iWriteToOutput.ActivateOutputWindow(_service.ConnectionData);
            }
        }