public static Task <string> GetStepDescriptionAsync(
     SdkMessageProcessingStep step
     , SdkMessageProcessingStepSecureConfig entSecure
     , IEnumerable <SdkMessageProcessingStepImage> stepImages
     )
 {
     return(Task.Run(() => GetStepDescription(step, entSecure, stepImages)));
 }
Beispiel #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pSecureConfig"></param>
        private void CreateSecureConfiguration(string pSecureConfig)
        {
            SdkMessageProcessingStepSecureConfig _secureStep = new SdkMessageProcessingStepSecureConfig()
            {
                SdkMessageProcessingStepSecureConfigId = this._addon.g_MessageStep,
                SecureConfig = pSecureConfig
            };

            this._addon.ServiceClient.Create(_secureStep);
        }
Beispiel #3
0
 /// <summary>
 /// Method to add the Secure Configuration on update of the Plugin Step if missing.
 /// </summary>
 /// <param name="xrmPluginStep">The Plugin Step.</param>
 /// <param name="sdkMessageProcessingStep">The SDK Message Processing Step.</param>
 private void AddSecureConfigIfMissing(XrmPluginStep xrmPluginStep, SdkMessageProcessingStep sdkMessageProcessingStep)
 {
     if (xrmPluginStep.SecureConfiguration != null && xrmPluginStep.SecureConfiguration.SecureConfigurationId.HasValue)
     {
         QueryByAttribute queryByAttribute = new QueryByAttribute(SdkMessageProcessingStepSecureConfig.EntityLogicalName)
         {
             ColumnSet = new ColumnSet(true),
         };
         queryByAttribute.Attributes.Add("sdkmessageprocessingstepsecureconfigid");
         queryByAttribute.Values.Add(sdkMessageProcessingStep.SdkMessageProcessingStepSecureConfigId.Id);
         if (xrmService.RetrieveMultiple(queryByAttribute).Entities.Count == 0)
         {
             SdkMessageProcessingStepSecureConfig sdkMessageProcessingStepSecureConfig = new SdkMessageProcessingStepSecureConfig();
             sdkMessageProcessingStepSecureConfig.SdkMessageProcessingStepSecureConfigId = xrmPluginStep.SecureConfiguration.SecureConfigurationId;
             sdkMessageProcessingStepSecureConfig.SecureConfig = xrmPluginStep.SecureConfiguration.SecureConfiguration;
             xrmService.Create(sdkMessageProcessingStepSecureConfig);
         }
     }
 }
        public static Guid RegisterStep(CrmOrganization org, CrmPluginStep step)
        {
            if (org == null)
            {
                throw new ArgumentNullException("org");
            }
            else if (step == null)
            {
                throw new ArgumentNullException("step");
            }

            Dictionary <string, object> entityList = step.GenerateCrmEntities();
            SdkMessageProcessingStep    sdkStep    = (SdkMessageProcessingStep)entityList[SdkMessageProcessingStep.EntityLogicalName];

            //This is a sanity check. The UI won't allow a user to set the secure configuration.
            if (org.SecureConfigurationPermissionDenied)
            {
                sdkStep.Attributes.Remove("sdkmessageprocessingstepsecureconfigid");
                sdkStep.RelatedEntities.Clear();
            }
            else if (entityList.ContainsKey(Entities.SdkMessageProcessingStepSecureConfig.EntityLogicalName))
            {
                Guid secureConfigId = Guid.NewGuid();

                //Create the related secure config in the related entities
                SdkMessageProcessingStepSecureConfig sdkSecureConfig =
                    (SdkMessageProcessingStepSecureConfig)entityList[SdkMessageProcessingStepSecureConfig.EntityLogicalName];
                sdkSecureConfig.Id = secureConfigId;
                sdkStep.RelatedEntities[new Relationship(CrmPluginStep.RelationshipStepToSecureConfig)] =
                    new EntityCollection(new Entity[] { sdkSecureConfig })
                {
                    EntityName = sdkSecureConfig.LogicalName
                };
                step.SecureConfigurationId = secureConfigId;
            }

            return(org.OrganizationService.Create(sdkStep));
        }
        public Dictionary <string, object> GenerateCrmEntities()
        {
            Dictionary <string, object> entityList = new Dictionary <string, object>();
            //Check for Permissions denied
            bool saveSecureConfiguration = true;

            if (Organization != null)
            {
                saveSecureConfiguration = !Organization.SecureConfigurationPermissionDenied;
            }

            //Create the secure configuration entity
            SdkMessageProcessingStep sdkStep = new SdkMessageProcessingStep();

            // For Create cases, SecureConfig != null , SecureConfigurationId = null

            //For Update cases SecureConfigurationId != null , SecureConfig=null
            if (!string.IsNullOrEmpty(SecureConfiguration))
            {
                SdkMessageProcessingStepSecureConfig sdkSecureConfig = new SdkMessageProcessingStepSecureConfig();
                if (SecureConfigurationId != Guid.Empty)
                {
                    sdkSecureConfig.SdkMessageProcessingStepSecureConfigId    = new Guid?();
                    sdkSecureConfig["sdkmessageprocessingstepsecureconfigid"] = SecureConfigurationId;

                    sdkStep.SdkMessageProcessingStepSecureConfigId             = new EntityReference();
                    sdkStep.SdkMessageProcessingStepSecureConfigId.LogicalName = SdkMessageProcessingStepSecureConfig.EntityLogicalName;
                    sdkStep.SdkMessageProcessingStepSecureConfigId.Id          = SecureConfigurationId;
                }

                sdkSecureConfig.SecureConfig = SecureConfiguration;

                entityList.Add(SdkMessageProcessingStepSecureConfig.EntityLogicalName, sdkSecureConfig);
            }

            //Create the main entity
            if (StepId != Guid.Empty)
            {
                sdkStep.SdkMessageProcessingStepId    = new Guid?();
                sdkStep["sdkmessageprocessingstepid"] = StepId;
            }

            sdkStep.Configuration = UnsecureConfiguration;

            if (ServiceBusConfigurationId == Guid.Empty)
            {
                sdkStep.EventHandler = new EntityReference(PluginType.EntityLogicalName, PluginId);
            }
            else
            {
                sdkStep.EventHandler = new EntityReference(ServiceEndpoint.EntityLogicalName, ServiceBusConfigurationId);
            }

            sdkStep.Name = Name;

            sdkStep.Mode       = new OptionSetValue();
            sdkStep.Mode.Value = (int)Mode;

            sdkStep.Rank    = new int?();
            sdkStep["rank"] = Rank;

            if (null != InvocationSource)
            {
#pragma warning disable 0612
                sdkStep.InvocationSource = new OptionSetValue((int)InvocationSource);
#pragma warning restore 0612
            }

            sdkStep.SdkMessageId             = new EntityReference();
            sdkStep.SdkMessageId.LogicalName = SdkMessage.EntityLogicalName;

            sdkStep.SdkMessageFilterId             = new EntityReference();
            sdkStep.SdkMessageFilterId.LogicalName = SdkMessageFilter.EntityLogicalName;

            if (MessageId == Guid.Empty)
            {
                sdkStep.SdkMessageId = null;
            }
            else
            {
                sdkStep.SdkMessageId.Id = MessageId;
            }
            if (MessageEntityId == Guid.Empty)
            {
                sdkStep.SdkMessageFilterId = null;
            }
            else
            {
                sdkStep.SdkMessageFilterId.Id = MessageEntityId;
            }
            sdkStep.ImpersonatingUserId             = new EntityReference();
            sdkStep.ImpersonatingUserId.LogicalName = SystemUser.EntityLogicalName;

            if (ImpersonatingUserId != Guid.Empty)
            {
                sdkStep.ImpersonatingUserId.Id = ImpersonatingUserId;
            }
            else
            {
                sdkStep.ImpersonatingUserId = null;
            }

            sdkStep.Stage       = new OptionSetValue();
            sdkStep.Stage.Value = (int)Stage;

            sdkStep.SupportedDeployment       = new OptionSetValue();
            sdkStep.SupportedDeployment.Value = (int)Deployment;

            if (string.IsNullOrEmpty(FilteringAttributes))
            {
                sdkStep.FilteringAttributes = string.Empty;
            }
            else
            {
                sdkStep.FilteringAttributes = FilteringAttributes;
            }

            sdkStep.AsyncAutoDelete = DeleteAsyncOperationIfSuccessful;

            sdkStep.Description = Description;

            entityList.Add(SdkMessageProcessingStep.EntityLogicalName, sdkStep);

            return(entityList);
        }
        public static bool UpdateStep(CrmOrganization org, CrmPluginStep step, Guid?origSecureConfigId,
                                      IList <CrmPluginImage> updateImages)
        {
            if (org == null)
            {
                throw new ArgumentNullException("org");
            }
            else if (step == null)
            {
                throw new ArgumentNullException("step");
            }

            Dictionary <string, object> entityList = step.GenerateCrmEntities();
            SdkMessageProcessingStep    sdkStep    = (SdkMessageProcessingStep)entityList[SdkMessageProcessingStep.EntityLogicalName];

            // Loop through each image and set the new message property
            List <SdkMessageProcessingStepImage> sdkImages = null;

            if (null != updateImages)
            {
                // Ensure that the given message supports images
                CrmMessage message = org.Messages[step.MessageId];
                if (0 == message.ImageMessagePropertyNames.Count && step.Images.Count > 0)
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                                                                      "The step has images registered, but the \"{0}\" message doesn't support images.{1}In order to change the message to \"{0}\", delete the existing images.",
                                                                      message.Name, Environment.NewLine));
                }

                // Loop through the existing images and update their message property name values
                sdkImages = new List <SdkMessageProcessingStepImage>(updateImages.Count);
                foreach (CrmPluginImage image in updateImages)
                {
                    // Set the message property name for each of the images
                    string propertyName = MessagePropertyNameForm.SelectMessagePropertyName(message);
                    if (string.IsNullOrWhiteSpace(propertyName))
                    {
                        return(false);
                    }
                    else if (string.Equals(image.MessagePropertyName, propertyName, StringComparison.Ordinal))
                    {
                        continue;
                    }

                    // Create the entity to update the value
                    SdkMessageProcessingStepImage sdkImage = new SdkMessageProcessingStepImage();
                    sdkImage.Id = image.ImageId;
                    sdkImage.MessagePropertyName = propertyName;
                    sdkImage.EntityState         = EntityState.Changed;

                    sdkImages.Add(sdkImage);
                }
            }

            //This is a sanity check. The UI won't allow a user to set the secure configuration.
            if (org.SecureConfigurationPermissionDenied)
            {
                sdkStep.Attributes.Remove("sdkmessageprocessingstepsecureconfigid");
                sdkStep.RelatedEntities.Clear();
                origSecureConfigId = null;
            }
            else if (entityList.ContainsKey(Entities.SdkMessageProcessingStepSecureConfig.EntityLogicalName))
            {
                if (null == origSecureConfigId)
                {
                    entityList.Remove(Entities.SdkMessageProcessingStepSecureConfig.EntityLogicalName);
                }
                else
                {
                    SdkMessageProcessingStepSecureConfig sdkSecureConfig =
                        (SdkMessageProcessingStepSecureConfig)entityList[SdkMessageProcessingStepSecureConfig.EntityLogicalName];

                    Guid        secureConfigId;
                    EntityState secureConfigState;
                    if (step.SecureConfigurationId == origSecureConfigId && origSecureConfigId.GetValueOrDefault() != Guid.Empty)
                    {
                        //Set the ID of the secure configuration to be the
                        secureConfigId    = origSecureConfigId.GetValueOrDefault();
                        secureConfigState = EntityState.Changed;

                        //Set the original secure config id so that the current id is not deleted
                        sdkStep.SdkMessageProcessingStepSecureConfigId =
                            new EntityReference(SdkMessageProcessingStepSecureConfig.EntityLogicalName, secureConfigId);
                    }
                    else
                    {
                        secureConfigId    = Guid.NewGuid();
                        secureConfigState = EntityState.Created;
                    }

                    //Set the configuration id for the step
                    step.SecureConfigurationId = secureConfigId;

                    //Populate the secure configuration object and add it to the related entities
                    sdkSecureConfig.SdkMessageProcessingStepSecureConfigId = secureConfigId;
                    sdkSecureConfig.EntityState = secureConfigState;

                    //Update the related entities
                    sdkStep.sdkmessageprocessingstepsecureconfigid_sdkmessageprocessingstep = sdkSecureConfig;

                    //Reset the original secure configuration
                    origSecureConfigId = null;
                }
            }
            else if (null != origSecureConfigId)
            {
                // To null out if it was set before
                sdkStep.SdkMessageProcessingStepSecureConfigId = null;
                step.SecureConfigurationId = Guid.Empty;

                if (Guid.Empty == origSecureConfigId)
                {
                    origSecureConfigId = null;
                }
            }

            // If the images need to be updated, there are two possible scenarios:
            // 1) The step is profiled -- The parent of the image is not the step that is currently being updated
            //    but rather the profiler step itself. In order to avoid changing this, there will have to be two SDK
            //    operations (update the step and update the images). Otherwise, the next time the profiled step executes,
            //    the images won't be present.
            // 2) The step is not profiled -- The image can be added to the related entities because the parent step is the
            //    current step being updated.
            if (null != sdkImages && sdkImages.Count > 0)
            {
                if (!step.IsProfiled || step.ProfilerStepId == step.StepId)
                {
                    sdkStep.sdkmessageprocessingstepid_sdkmessageprocessingstepimage = sdkImages;
                }
            }

            //Update the step
            org.OrganizationService.Update(sdkStep);

            if (step.IsProfiled && null != sdkImages && sdkImages.Count > 0)
            {
                // Update the Profiler step with the new property values as a single transaction to minimize the
                // possibility of data corruption.
                SdkMessageProcessingStep profilerStep = new SdkMessageProcessingStep();
                profilerStep.Id = step.ProfilerStepId.GetValueOrDefault();
                profilerStep.sdkmessageprocessingstepid_sdkmessageprocessingstepimage = sdkImages;
                org.OrganizationService.Update(profilerStep);
            }

            // Refresh the objects so that the caller has up-to-date data
            OrganizationHelper.RefreshStep(org, step);
            if (null != updateImages)
            {
                foreach (CrmPluginImage image in updateImages)
                {
                    OrganizationHelper.RefreshImage(org, image, step);
                }
            }

            // Delete the orphaned Secure config when nulling out the value on the step
            if (null != origSecureConfigId)
            {
                org.OrganizationService.Delete(SdkMessageProcessingStepSecureConfig.EntityLogicalName, origSecureConfigId.GetValueOrDefault());
            }

            return(true);
        }
        private void _UpdateStep(CrmTypeStep step)
        {
            UpdateStatus($"Updating step '{step.Name}' in type ... ", 1);

            //var updatedStep = Context.SdkMessageProcessingStepSet.FirstOrDefault(entity => entity.SdkMessageProcessingStepId == step.Id)
            //					  ?? new SdkMessageProcessingStep();
            //if (updatedStep.Id == Guid.Empty)
            //{
            //	updatedStep.Id = step.Id;
            //}
            var updatedStep = new SdkMessageProcessingStep
            {
                Id                  = step.Id,
                SdkMessageId        = new EntityReference(SdkMessage.EntityLogicalName, step.MessageId),
                FilteringAttributes = step.Attributes ?? "",
                Name                = step.Name,
                Rank                = step.ExecutionOrder,
                Description         = step.Description ?? "",
                Stage               = step.Stage.ToOptionSetValue(),
                Mode                = step.Mode.ToOptionSetValue(),
                SupportedDeployment = step.Deployment.ToOptionSetValue(),
                AsyncAutoDelete     = step.IsDeleteJob,
                Configuration       = step.UnsecureConfig ?? ""
            };

            if (step.UserId == Guid.Empty)
            {
                updatedStep.ImpersonatingUserId = null;
            }
            else
            {
                updatedStep.ImpersonatingUserId = new EntityReference(SystemUser.EntityLogicalName,
                                                                      step.UserId);
            }

            if (step.FilterId == Guid.Empty)
            {
                updatedStep.SdkMessageFilterId = null;
            }
            else
            {
                updatedStep.SdkMessageFilterId = new EntityReference(SdkMessageFilter.EntityLogicalName,
                                                                     step.FilterId);
            }

            var secureId = step.SecureId;

            if (string.IsNullOrEmpty(step.SecureConfig))
            {
                secureId = Guid.Empty;
            }
            else
            {
                if (secureId == Guid.Empty)
                {
                    secureId = step.SecureId = ((CreateResponse)Context.Execute(
                                                    new CreateRequest
                    {
                        Target = new SdkMessageProcessingStepSecureConfig
                        {
                            SecureConfig = step.SecureConfig
                        }
                    })).id;
                }
                else
                {
                    //var updatedSecure = Context.SdkMessageProcessingStepSecureConfigSet.FirstOrDefault(
                    //	entity => entity.SdkMessageProcessingStepSecureConfigId == step.SecureId)
                    //                    ?? new SdkMessageProcessingStepSecureConfig();
                    //if (updatedSecure.Id == Guid.Empty)
                    //{
                    //	updatedSecure.Id = step.SecureId;
                    //}
                    var updatedSecure = new SdkMessageProcessingStepSecureConfig
                    {
                        Id           = step.SecureId,
                        SecureConfig = step.SecureConfig
                    };

                    //Context.ConfirmAttached(updatedSecure);
                    //Context.UpdateObject(updatedSecure);
                    UpdateStatus("Updated secure config ... ");
                    Service.Update(updatedSecure);
                }
            }

            if (secureId == Guid.Empty)
            {
                updatedStep.SdkMessageProcessingStepSecureConfigId = null;
            }
            else
            {
                updatedStep.SdkMessageProcessingStepSecureConfigId
                    = new EntityReference(SdkMessageProcessingStepSecureConfig.EntityLogicalName,
                                          secureId);
            }

            //Context.ConfirmAttached(updatedStep);
            //Context.UpdateObject(updatedStep);
            UpdateStatus("Updated step ... ");
            Service.Update(updatedStep);
            //UpdateStatus("Saving updated step to CRM ... ");
            //Context.SaveChanges();

            UpdateStatus($"Finished updating step '{step.Name}'.", -1);
        }
Beispiel #8
0
        /// <summary>
        /// Method to populate the Dynamics CRM Step Object from the XRM Step Object.
        /// </summary>
        /// <param name="xrmPluginStep">The XRM Step Object from whence to retrieve the Dynamics CRM Step Object.</param>
        /// <returns>The Dynamics CRM Step Object.</returns>
        private SdkMessageProcessingStep GetPluginStep(XrmPluginStep xrmPluginStep)
        {
            try
            {
                SdkMessageProcessingStep = new SdkMessageProcessingStep();
                if (xrmPluginStep.SecureConfiguration != null && !string.IsNullOrEmpty(xrmPluginStep.SecureConfiguration.SecureConfiguration))
                {
                    SdkMessageProcessingStepSecureConfig sdkMessageProcessingStepSecureConfig = new SdkMessageProcessingStepSecureConfig();
                    sdkMessageProcessingStepSecureConfig.SdkMessageProcessingStepSecureConfigId = xrmPluginStep.SecureConfiguration.SecureConfigurationId;
                    sdkMessageProcessingStepSecureConfig.SecureConfig = xrmPluginStep.SecureConfiguration.SecureConfiguration;
                    SdkMessageProcessingStep.SdkMessageProcessingStepSecureConfigId             = new EntityReference();
                    SdkMessageProcessingStep.SdkMessageProcessingStepSecureConfigId.LogicalName = SdkMessageProcessingStepSecureConfig.EntityLogicalName;
                    SdkMessageProcessingStep.SdkMessageProcessingStepSecureConfigId.Id          = xrmPluginStep.SecureConfiguration.SecureConfigurationId.Value;
                    Relationship relationship = new Relationship(XrmPluginStep.RelationshipStepToSecureConfig);
                    Entity       entity       = new Entity();
                    entity = (Entity)sdkMessageProcessingStepSecureConfig;
                    EntityCollection entityCollection = new EntityCollection();
                    entityCollection.Entities.Add(entity);
                    SdkMessageProcessingStep.RelatedEntities[relationship] = entityCollection;
                }
                SdkMessageProcessingStep.Configuration = xrmPluginStep.UnsecureConfiguration;
                if (xrmPluginStep.ServiceBusConfigurationId == Guid.Empty)
                {
                    SdkMessageProcessingStep.EventHandler = new EntityReference(PluginType.EntityLogicalName, xrmPluginStep.PluginId);
                }
                else
                {
                    SdkMessageProcessingStep.EventHandler = new EntityReference(ServiceEndpoint.EntityLogicalName, xrmPluginStep.ServiceBusConfigurationId);
                }
                SdkMessageProcessingStep.Name = xrmPluginStep.Name;
                SdkMessageProcessingStep.SdkMessageProcessingStepId = xrmPluginStep.StepId;
                SdkMessageProcessingStep.Mode       = new OptionSetValue();
                SdkMessageProcessingStep.Mode.Value = (int)xrmPluginStep.Mode;
                SdkMessageProcessingStep.Rank       = xrmPluginStep.Rank;
                if (xrmPluginStep.InvocationSource != null)
                {
#pragma warning disable 0612
                    SdkMessageProcessingStep.InvocationSource = new OptionSetValue((int)xrmPluginStep.InvocationSource);
#pragma warning restore 0612
                }
                SdkMessageProcessingStep.SdkMessageId                   = new EntityReference();
                SdkMessageProcessingStep.SdkMessageId.LogicalName       = SdkMessage.EntityLogicalName;
                SdkMessageProcessingStep.SdkMessageFilterId             = new EntityReference();
                SdkMessageProcessingStep.SdkMessageFilterId.LogicalName = SdkMessageFilter.EntityLogicalName;
                if (xrmPluginStep.MessageId == Guid.Empty)
                {
                    SdkMessageProcessingStep.SdkMessageId = null;
                }
                else
                {
                    SdkMessageProcessingStep.SdkMessageId.Id = xrmPluginStep.MessageId;
                }
                if (xrmPluginStep.MessageEntityId == Guid.Empty)
                {
                    SdkMessageProcessingStep.SdkMessageFilterId = null;
                }
                else
                {
                    SdkMessageProcessingStep.SdkMessageFilterId.Id = xrmPluginStep.MessageEntityId;
                }
                SdkMessageProcessingStep.ImpersonatingUserId             = new EntityReference();
                SdkMessageProcessingStep.ImpersonatingUserId.LogicalName = SystemUser.EntityLogicalName;
                if (xrmPluginStep.ImpersonatingUserId != Guid.Empty)
                {
                    SdkMessageProcessingStep.ImpersonatingUserId.Id = xrmPluginStep.ImpersonatingUserId;
                }
                else
                {
                    SdkMessageProcessingStep.ImpersonatingUserId = null;
                }
                SdkMessageProcessingStep.Stage                     = new OptionSetValue();
                SdkMessageProcessingStep.Stage.Value               = (int)xrmPluginStep.Stage;
                SdkMessageProcessingStep.SupportedDeployment       = new OptionSetValue();
                SdkMessageProcessingStep.SupportedDeployment.Value = (int)xrmPluginStep.Deployment;
                if (string.IsNullOrEmpty(xrmPluginStep.FilteringAttributes))
                {
                    SdkMessageProcessingStep.FilteringAttributes = string.Empty;
                }
                else
                {
                    SdkMessageProcessingStep.FilteringAttributes = xrmPluginStep.FilteringAttributes;
                }
                SdkMessageProcessingStep.AsyncAutoDelete = xrmPluginStep.DeleteAsyncOperationIfSuccessful;
                SdkMessageProcessingStep.Description     = xrmPluginStep.Description;
                return(SdkMessageProcessingStep);
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                throw;
            }
        }
        private static string GetStepDescription(
            SdkMessageProcessingStep step
            , SdkMessageProcessingStepSecureConfig entSecure
            , IEnumerable <SdkMessageProcessingStepImage> stepImages
            )
        {
            StringBuilder description = new StringBuilder();

            var messageName             = step.SdkMessageId?.Name ?? "Unknown";
            var primaryObjectTypeCode   = step.PrimaryObjectTypeCodeName;
            var secondaryObjectTypeCode = step.SecondaryObjectTypeCodeName;

            description.AppendFormat("Primary Entity '{0}',   Secondary Entity '{1}'"
                                     , primaryObjectTypeCode
                                     , secondaryObjectTypeCode
                                     ).AppendLine();

            description.AppendFormat("Message '{0}',    Stage '{1}',    Mode '{2}',    Rank {3},    Status {4}"
                                     , messageName
                                     , SdkMessageProcessingStepRepository.GetStageName(step.Stage.Value, step.Mode.Value)
                                     , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.mode]
                                     , step.Rank.ToString()
                                     , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.statuscode]
                                     ).AppendLine();

            string contextUser = "******";

            if (step.ImpersonatingUserId != null)
            {
                contextUser = step.ImpersonatingUserId.Name;
            }

            description.AppendFormat("RunInUserContext: {0}", contextUser).AppendLine();
            description.AppendFormat("AsyncAutoDelete: {0}", step.AsyncAutoDelete.GetValueOrDefault()).AppendLine();

            if (!string.IsNullOrEmpty(step.FilteringAttributes))
            {
                description.AppendFormat("Filtering Attributes: {0}", step.FilteringAttributesStringsSorted).AppendLine();
            }

            if (!string.IsNullOrEmpty(step.Name))
            {
                description.AppendFormat("Name: {0}", step.Name).AppendLine();
            }

            if (!string.IsNullOrEmpty(step.Description))
            {
                description.AppendFormat("Description: {0}", step.Description).AppendLine();
            }

            if (!string.IsNullOrEmpty(step.Configuration))
            {
                description.AppendFormat("Unsecure Configuration: {0}", step.Configuration).AppendLine();
            }

            if (entSecure != null)
            {
                if (!string.IsNullOrEmpty(entSecure.SecureConfig))
                {
                    description.AppendFormat("Secure Configuration: {0}", entSecure.SecureConfig).AppendLine();
                }
            }

            //{
            //    string dateStr = GetDateString(step.CreatedBy, step.CreatedOn, step.ModifiedBy, step.ModifiedOn, step.OverwriteTime);

            //    if (!string.IsNullOrEmpty(dateStr))
            //    {
            //        description.AppendLine(dateStr);
            //    }
            //}

            int numberImage = 1;

            foreach (var image in stepImages
                     .OrderBy(im => im.ImageType.Value)
                     .ThenBy(im => im.CreatedOn.Value)
                     .ThenBy(im => im.Name)
                     )
            {
                string imageDescription = GetImageDescription(numberImage, image);

                var coll = imageDescription.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var item in coll)
                {
                    description.AppendLine(tabSpacer + item);
                }

                numberImage++;
            }

            return(description.ToString());
        }
        private static string CreateDescription(
            Guid idPluginType
            , IEnumerable <SdkMessageProcessingStep> allSteps
            , IEnumerable <SdkMessageProcessingStepImage> queryImage
            , IEnumerable <SdkMessageProcessingStepSecureConfig> listSecure
            )
        {
            var sortedSteps = allSteps
                              .Where(s => s.EventHandler.Id == idPluginType)
                              .OrderBy(ent => ent.PrimaryObjectTypeCodeName)
                              .ThenBy(ent => ent.SdkMessageId?.Name ?? "Unknown", new MessageComparer())
                              .ThenBy(s => s.Mode.Value)
                              .ThenBy(s => s.Rank)
                              .ThenBy(s => s.Name)
            ;

            if (!sortedSteps.Any())
            {
                return(string.Empty);
            }

            StringBuilder description = new StringBuilder();

            //{
            //    string dateStr = GetDateString(pluginType.CreatedBy, pluginType.CreatedOn, pluginType.ModifiedBy, pluginType.ModifiedOn, pluginType.OverwriteTime);

            //    if (!string.IsNullOrEmpty(dateStr))
            //    {
            //        description.AppendLine(dateStr);
            //    }
            //}

            //description.AppendLine(connectionInfo).AppendLine();
            //description.AppendFormat("Plugin Steps for PluginType '{0}' at {1}", pluginType.TypeName, DateTime.Now.ToString(formatDateTime)).AppendLine();

            int numberStep = 1;

            foreach (var step in sortedSteps)
            {
                if (description.Length > 0)
                {
                    description.AppendLine();
                }

                description.AppendFormat("{0}. Step", numberStep).AppendLine();

                var stepImages = queryImage.Where(i => i.SdkMessageProcessingStepId.Id == step.SdkMessageProcessingStepId);

                SdkMessageProcessingStepSecureConfig entSecure = null;

                if (step.SdkMessageProcessingStepSecureConfigId != null)
                {
                    entSecure = listSecure.FirstOrDefault(s => s.SdkMessageProcessingStepSecureConfigId == step.SdkMessageProcessingStepSecureConfigId.Id);
                }

                description.AppendLine(GetStepDescription(step, entSecure, stepImages));

                numberStep++;
            }

            return(description.ToString());
        }
        private async Task PerformSaveClick()
        {
            string messageName     = cmBMessageName.Text?.Trim();
            string primaryEntity   = cmBPrimaryEntity.Text?.Trim();
            string secondaryEntity = cmBSecondaryEntity.Text?.Trim();

            if (string.IsNullOrEmpty(messageName))
            {
                MessageBox.Show(Properties.MessageBoxStrings.MessageNameIsEmpty, Properties.MessageBoxStrings.ErrorTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            if (!int.TryParse(txtBExecutionOrder.Text.Trim(), out int rank))
            {
                string text = string.Format(Properties.MessageBoxStrings.TextCannotBeParsedToIntFormat1, txtBExecutionOrder.Text);
                MessageBox.Show(text, Properties.MessageBoxStrings.ErrorTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            if (string.IsNullOrEmpty(primaryEntity))
            {
                primaryEntity = "none";
            }
            if (string.IsNullOrEmpty(secondaryEntity))
            {
                secondaryEntity = "none";
            }

            var messageFilterCount = _filters.Count(f =>
                                                    string.Equals(f.SdkMessageId.Name, messageName, StringComparison.InvariantCultureIgnoreCase) &&
                                                    string.Equals(f.PrimaryObjectTypeCode, primaryEntity, StringComparison.InvariantCultureIgnoreCase) &&
                                                    string.Equals(f.SecondaryObjectTypeCode, secondaryEntity, StringComparison.InvariantCultureIgnoreCase)
                                                    );

            if (messageFilterCount != 1)
            {
                string text = string.Format(Properties.MessageBoxStrings.MessageFilterNotFindedForMessageNameAndEntitiesFormat3, messageName, primaryEntity, secondaryEntity);
                MessageBox.Show(text, Properties.MessageBoxStrings.ErrorTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var messageFilter = _filters.Single(f =>
                                                string.Equals(f.SdkMessageId.Name, messageName, StringComparison.InvariantCultureIgnoreCase) &&
                                                string.Equals(f.PrimaryObjectTypeCode, primaryEntity, StringComparison.InvariantCultureIgnoreCase) &&
                                                string.Equals(f.SecondaryObjectTypeCode, secondaryEntity, StringComparison.InvariantCultureIgnoreCase)
                                                );

            this.Step.Name        = txtBName.Text.Trim();
            this.Step.Description = txtBDescription.Text.Trim();

            this.Step.SdkMessageFilterId = messageFilter.ToEntityReference();
            this.Step.SdkMessageId       = messageFilter.SdkMessageId;

            this.Step.Rank          = rank;
            this.Step.Configuration = txtBUnSecureConfiguration.Text.Trim();

            var stage            = GetStage();
            var invocationsource = GetInvocationSource();

            this.Step.Stage = new OptionSetValue(stage);

            if (stage == (int)SdkMessageProcessingStep.Schema.OptionSets.stage.Post_operation_40)
            {
                var mode = GetMode();

                this.Step.Mode = new OptionSetValue(mode);

                if (mode == (int)SdkMessageProcessingStep.Schema.OptionSets.mode.Asynchronous_1)
                {
                    this.Step.AsyncAutoDelete = chBDeleteAsyncOperationIfSuccessful.IsChecked.GetValueOrDefault();
                }
                else
                {
                    this.Step.AsyncAutoDelete = false;
                }
            }
            else
            {
                this.Step.Mode            = new OptionSetValue((int)SdkMessageProcessingStep.Schema.OptionSets.mode.Synchronous_0);
                this.Step.AsyncAutoDelete = false;
            }

            if (!messageFilter.Availability.HasValue || messageFilter.Availability == (int)SdkMessageFilter.Schema.OptionSets.availability.Both)
            {
                var supporteddeployment = GetDeployment();

                this.Step.SupportedDeployment = new OptionSetValue(supporteddeployment);
            }
            else if (messageFilter.Availability == (int)SdkMessageFilter.Schema.OptionSets.availability.Server)
            {
                this.Step.SupportedDeployment = new OptionSetValue((int)SdkMessageProcessingStep.Schema.OptionSets.supporteddeployment.Server_Only_0);
            }
            else if (messageFilter.Availability == (int)SdkMessageFilter.Schema.OptionSets.availability.Client)
            {
                this.Step.SupportedDeployment = new OptionSetValue((int)SdkMessageProcessingStep.Schema.OptionSets.supporteddeployment.Microsoft_Dynamics_365_Client_for_Outlook_Only_1);
            }

#pragma warning disable CS0612 // Type or member is obsolete
            this.Step.InvocationSource = new OptionSetValue(invocationsource);
#pragma warning restore CS0612 // Type or member is obsolete

            if (string.Equals(messageFilter.SdkMessageId.Name, "Update", StringComparison.InvariantCultureIgnoreCase))
            {
                this.Step.FilteringAttributes = txtBFilteringBAttributes.Text.Trim();
            }
            else
            {
                this.Step.FilteringAttributes = string.Empty;
            }

            this.Step.ImpersonatingUserId = _impersonatingUser;

            string          secureConfig   = txtBSecureConfiguration.Text.Trim();
            EntityReference configToDelete = null;

            if (string.IsNullOrEmpty(secureConfig))
            {
                if (this.Step.SdkMessageProcessingStepSecureConfigId != null)
                {
                    configToDelete = this.Step.SdkMessageProcessingStepSecureConfigId;

                    this.Step.SdkMessageProcessingStepSecureConfigId = null;
                }
            }
            else
            {
                SdkMessageProcessingStepSecureConfig config = new SdkMessageProcessingStepSecureConfig()
                {
                    SecureConfig = secureConfig,
                };

                if (this.Step.SdkMessageProcessingStepSecureConfigId != null)
                {
                    config.Id = this.Step.SdkMessageProcessingStepSecureConfigId.Id;
                }

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

                try
                {
                    config.Id = await _service.UpsertAsync(config);

                    ToggleControls(true, Properties.WindowStatusStrings.UpdatingSdkMessageProcessingStepSecureConfigCompletedFormat1, _service.ConnectionData.Name);
                }
                catch (Exception ex)
                {
                    ToggleControls(true, Properties.WindowStatusStrings.UpdatingSdkMessageProcessingStepSecureConfigFailedFormat1, _service.ConnectionData.Name);

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

                if (config.Id != Guid.Empty)
                {
                    this.Step.SdkMessageProcessingStepSecureConfigId = config.ToEntityReference();
                }
            }

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

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

                if (configToDelete != null)
                {
                    ToggleControls(false, Properties.WindowStatusStrings.DeletingSdkMessageProcessingStepSecureConfigFormat1, _service.ConnectionData.Name);

                    try
                    {
                        await _service.DeleteAsync(configToDelete.LogicalName, configToDelete.Id);

                        ToggleControls(true, Properties.WindowStatusStrings.DeletingSdkMessageProcessingStepSecureConfigCompletedFormat1, _service.ConnectionData.Name);
                    }
                    catch (Exception ex)
                    {
                        ToggleControls(true, Properties.WindowStatusStrings.DeletingSdkMessageProcessingStepSecureConfigFailedFormat1, _service.ConnectionData.Name);

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

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

                this.DialogResult = true;

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

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