public static void UpdateImage(CrmOrganization org, CrmPluginImage image, CrmPluginStep step)
        {
            if (null == org)
            {
                throw new ArgumentNullException("org");
            }
            else if (null == image)
            {
                throw new ArgumentNullException("image");
            }
            else if (null == step)
            {
                throw new ArgumentNullException("step");
            }

            //Retrieve the SDK entity equivalent of the given image
            Dictionary <string, object>   entityList = image.GenerateCrmEntities(step.MessageId, step.MessageEntityId);
            SdkMessageProcessingStepImage sdkImage   = (SdkMessageProcessingStepImage)entityList[SdkMessageProcessingStepImage.EntityLogicalName];

            //If the step that owns this image is a profiled step, the step will be the original step (the step that is being profiled),
            //not the profiler step. The Profiler step is what should be set on the server, since that is the step that is actually enabled.
            if (step.IsProfiled && null != sdkImage.SdkMessageProcessingStepId)
            {
                sdkImage.SdkMessageProcessingStepId.Id = step.ProfilerStepId.GetValueOrDefault();
            }

            org.OrganizationService.Update(sdkImage);
            OrganizationHelper.RefreshImage(org, image, step);
        }
        private static CrmPluginImage CreateImage(CrmPluginStep step, XElement imageEl, XElement pluginStepEl)
        {
            var imageAttributes = imageEl.Attribute("Attributes");
            var imageType       = imageEl.Attribute("ImageType").Value;

            // note: ignore EntityAlias for convenience
            switch (imageType)
            {
            case "PreImage":
                return(CreateImage(
                           step,
                           string.IsNullOrEmpty(imageAttributes?.Value) ? null : imageAttributes.Value,
                           pluginStepEl.Attribute("MessageName").Value,
                           CrmPluginImageType.PreImage));

            case "PostImage":
                return(CreateImage(
                           step,
                           string.IsNullOrEmpty(imageAttributes?.Value) ? null : imageAttributes.Value,
                           pluginStepEl.Attribute("MessageName").Value,
                           CrmPluginImageType.PostImage));

            case "Both":
                // ToDo: process "Both"
                return(null);

            default:
                return(null);
            }
        }
 private static CrmPluginImage CreateImage(CrmPluginStep step, string imageAttributes, string pluginMessageName, CrmPluginImageType pluginImageType)
 {
     return
         (new CrmPluginImage(
              step.AssemblyId,
              step.PluginId,
              step.Id,
              imageAttributes,
              null,
              pluginImageType == CrmPluginImageType.PreImage ? "preimage" : "postimage",
              pluginImageType,
              CrmMessage.Instance[pluginMessageName],
              pluginImageType == CrmPluginImageType.PreImage ? "preimage" : "postimage"));
 }
Exemplo n.º 4
0
        public void AddStep(CrmPluginStep step)
        {
            if (step == null)
            {
                throw new ArgumentNullException("step");
            }

            m_stepList.Add(step.StepId, step);

            if (Organization != null)
            {
                Organization.AddStep(this, step);
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            //initialize context and service
            IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            _pluginStepHelper = new CrmPluginStep();

            var preImage = (Entity)context.PreEntityImages["PreImage"];

            Guid             pluginId = _pluginStepHelper.RetrievePluginId(ref service, "CodecLabs.BPFTracking.Plugins.BPFStageChanged");
            EntityCollection steps    = _pluginStepHelper.RetrieveStepsByPluginId(ref service, pluginId);

            DisableSteps(service, preImage, steps);
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            //Create an Organization Service
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        orgService     = serviceFactory.CreateOrganizationService(context.InitiatingUserId);

            //Registered Step Guid
            var pluginStepGuid = Guid.Empty;

            //Plugin Step object
            CrmPluginStep pluginStep = new CrmPluginStep();

            pluginStep.StepId = new Guid(PluginStepId.Get <string>(executionContext));
            pluginStep.UnsecureConfiguration = UnsecureConfiguration.Get <string>(executionContext);

            //Update Step
            pluginStep.UpdatePluginStep(ref orgService);
        }
        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));
        }
Exemplo n.º 8
0
        public StepRegistrationForm(CrmOrganization org, MainControl orgControl, CrmPlugin plugin, CrmPluginStep step, CrmServiceEndpoint serviceEndpoint)
        {
            if (org == null)
            {
                throw new ArgumentNullException("org");
            }
            else if (orgControl == null)
            {
                throw new ArgumentNullException("control");
            }
            m_org         = org;
            m_orgControl  = orgControl;
            m_currentStep = step;

            #region Initialization of crmFilteringAttributes

            //Seems this was removed automatically by VS designer, so added here instead.
            crmFilteringAttributes = new Controls.CrmAttributeSelectionControl()
            {
                Organization = org
            };

            //
            // crmFilteringAttributes
            //
            this.crmFilteringAttributes.Anchor          = ((AnchorStyles.Top | AnchorStyles.Left) | AnchorStyles.Right);
            this.crmFilteringAttributes.Attributes      = null;
            this.crmFilteringAttributes.DisabledMessage = "";
            //this.crmFilteringAttributes.EntityName = null;
            this.crmFilteringAttributes.Location = new System.Drawing.Point(127, 91);
            this.crmFilteringAttributes.Margin   = new Padding(4, 5, 4, 5);
            this.crmFilteringAttributes.Name     = "crmFilteringAttributes";
            //this.crmFilteringAttributes.Organization = null;
            this.crmFilteringAttributes.ScrollBars = ScrollBars.None;
            this.crmFilteringAttributes.Size       = new System.Drawing.Size(316, 20);
            this.crmFilteringAttributes.TabIndex   = 9;
            this.crmFilteringAttributes.WordWrap   = false;

            #endregion Initialization of crmFilteringAttributes

            InitializeComponent();
            this.grpGeneral.Controls.Add(this.crmFilteringAttributes);

            //Initialize the auto-complete on the Message field
            var msgList = new AutoCompleteStringCollection();
            foreach (CrmMessage msg in org.Messages.Values)
            {
                msgList.Add(msg.Name);
            }
            txtMessageName.AutoCompleteCustomSource = msgList;

            //Check whether system plugins should be added to the list
            if (step != null && org[step.AssemblyId][step.PluginId].IsSystemCrmEntity && (!OrganizationHelper.AllowStepRegistrationForPlugin(plugin)))
            {
                cmbPlugins.Enabled = false;
            }
            else if ((plugin != null) && (!OrganizationHelper.AllowStepRegistrationForPlugin(plugin)))
            {
                plugin = null;
            }

            //Add the plugins
            CrmPlugin selectPlugin = null;
            foreach (CrmPluginAssembly assembly in org.Assemblies.Values)
            {
                foreach (CrmPlugin pluginType in assembly.Plugins.Values)
                {
                    if (pluginType.PluginType == CrmPluginType.Plugin &&
                        OrganizationHelper.AllowStepRegistrationForPlugin(pluginType))
                    {
                        if (serviceEndpoint == null && pluginType.TypeName == CrmServiceEndpoint.ServiceBusPluginName && pluginType.CustomizationLevel == 0)
                        {
                            continue;
                            // Donot add OOB Service Bus plugin to the list when it it is not a Service Bus Step
                        }
                        else
                        {
                            if (plugin != null && plugin.PluginId == pluginType.PluginId)
                            {
                                selectPlugin = pluginType;
                                cmbPlugins.Items.Add(pluginType);
                            }
                            else
                            {
                                cmbPlugins.Items.Add(pluginType);
                            }
                        }
                    }
                }
            }

            if (cmbPlugins.Items.Count != 0)
            {
                if (selectPlugin == null)
                {
                    cmbPlugins.SelectedIndex = 0;
                }
                else
                {
                    cmbPlugins.SelectedItem = selectPlugin;
                }
            }

            //Create a user that represents the current user
            var callingUser = new CrmUser(org)
            {
                UserId  = Guid.Empty,
                Name    = "Calling User",
                Enabled = true
            };
            cmbUsers.Items.Add(callingUser);

            CrmServiceEndpoint selectServiceEndpoint = null;
            foreach (CrmServiceEndpoint currentServiceEndpoint in org.ServiceEndpoints.Values)
            {
                if (serviceEndpoint != null && serviceEndpoint.ServiceEndpointId == currentServiceEndpoint.ServiceEndpointId)
                {
                    selectServiceEndpoint = currentServiceEndpoint;
                }
                cmbServiceEndpoint.Items.Add(currentServiceEndpoint);
            }

            if (selectServiceEndpoint != null)
            {
                cmbServiceEndpoint.SelectedItem = selectServiceEndpoint;
            }
            else
            {
                if (cmbServiceEndpoint.Items.Count != 0)
                {
                    cmbServiceEndpoint.SelectedIndex = 0;
                }
            }

            if (serviceEndpoint != null)
            {
                UpdatePluginEventHandlerControls(true);
            }
            else
            {
                UpdatePluginEventHandlerControls(false);
            }

            if (m_currentStep != null)
            {
                txtMessageName.Text = m_org.Messages[m_currentStep.MessageId].Name;

                if (org.MessageEntities.ContainsKey(m_currentStep.MessageEntityId))
                {
                    CrmMessageEntity msgEntity = Message[m_currentStep.MessageEntityId];
                    txtPrimaryEntity.Text   = msgEntity.PrimaryEntity;
                    txtSecondaryEntity.Text = msgEntity.SecondaryEntity;
                }
                else
                {
                    txtPrimaryEntity.Text   = "none";
                    txtSecondaryEntity.Text = "none";
                }

                cmbPlugins.SelectedItem = m_org[m_currentStep.AssemblyId][m_currentStep.PluginId];

                if (m_currentStep.ServiceBusConfigurationId != Guid.Empty)
                {
                    cmbServiceEndpoint.SelectedItem = m_org.ServiceEndpoints[m_currentStep.ServiceBusConfigurationId];
                }

                txtRank.Text = m_currentStep.Rank.ToString();
                switch (m_currentStep.Stage)
                {
                case CrmPluginStepStage.PreValidation:
                    radStagePreValidation.Checked = true;
                    break;

                case CrmPluginStepStage.PreOperation:
                    radStagePreOperation.Checked = true;
                    break;

                case CrmPluginStepStage.PostOperation:
                    radStagePostOperation.Checked = true;
                    break;

                case CrmPluginStepStage.PostOperationDeprecated:
                    radStagePostOperationDeprecated.Checked = true;
                    break;

                default:
                    throw new NotImplementedException("CrmPluginStepStage = " + m_currentStep.Stage.ToString());
                }

                switch (m_currentStep.Mode)
                {
                case CrmPluginStepMode.Asynchronous:

                    radModeAsync.Checked = true;
                    break;

                case CrmPluginStepMode.Synchronous:

                    radModeSync.Checked = true;
                    break;

                default:
                    throw new NotImplementedException("Mode = " + m_currentStep.Mode.ToString());
                }

                switch (m_currentStep.Deployment)
                {
                case CrmPluginStepDeployment.Both:

                    chkDeploymentOffline.Checked = true;
                    chkDeploymentServer.Checked  = true;
                    break;

                case CrmPluginStepDeployment.ServerOnly:

                    chkDeploymentOffline.Checked = false;
                    chkDeploymentServer.Checked  = true;
                    break;

                case CrmPluginStepDeployment.OfflineOnly:

                    chkDeploymentOffline.Checked = true;
                    chkDeploymentServer.Checked  = false;
                    break;

                default:
                    throw new NotImplementedException("Deployment = " + m_currentStep.Deployment.ToString());
                }

                switch (m_currentStep.InvocationSource)
                {
                case null:
                case CrmPluginStepInvocationSource.Parent:

                    radInvocationParent.Checked = true;
                    break;

                case CrmPluginStepInvocationSource.Child:

                    radInvocationChild.Checked = true;
                    break;

                default:
                    throw new NotImplementedException("InvocationSource = " + m_currentStep.InvocationSource.ToString());
                }

                txtDescription.Text = m_currentStep.Description;

                txtSecureConfig.Text = m_currentStep.SecureConfiguration;

                string stepName;
                //if (this.m_currentStep.IsProfiled && org.Plugins[this.m_currentStep.PluginId].IsProfilerPlugin)
                //{
                //    //If the current step is a profiler step, the form that is displayed should use the configuration from the original step.
                //    // ProfilerConfiguration profilerConfig = OrganizationHelper.RetrieveProfilerConfiguration(this.m_currentStep);
                //    // stepName = profilerConfig.OriginalEventHandlerName;
                //    // txtUnsecureConfiguration.Text = profilerConfig.Configuration;
                //}
                //else
                //{
                txtUnsecureConfiguration.Text = m_currentStep.UnsecureConfiguration;
                stepName = m_currentStep.Name;
                //}

                if (stepName == GenerateDescription())
                {
                    m_stepName = GenerateDescription();
                }
                else
                {
                    m_stepName   = null;
                    txtName.Text = stepName;
                }

                if (MessageEntity != null)
                {
                    crmFilteringAttributes.EntityName = MessageEntity.PrimaryEntity;
                }

                crmFilteringAttributes.Attributes           = m_currentStep.FilteringAttributes;
                chkDeleteAsyncOperationIfSuccessful.Checked = m_currentStep.DeleteAsyncOperationIfSuccessful;
                chkDeleteAsyncOperationIfSuccessful.Enabled = (m_currentStep.Mode == CrmPluginStepMode.Asynchronous);

                Text             = "Update Existing Step";
                btnRegister.Text = "Update";

                CheckAttributesSupported();
            }
            else if (!radStagePostOperation.Enabled && radStagePostOperationDeprecated.Enabled)
            {
                radStagePostOperationDeprecated.Checked = true;
            }

            //Check if permissions for the secure configuration was denied
            if (org.SecureConfigurationPermissionDenied)
            {
                picAccessDenied.Visible = true;
                lblAccessDenied.Visible = true;
                txtSecureConfig.Visible = false;

                picAccessDenied.Image = CrmResources.LoadImage("AccessDenied");

                lblAccessDenied.Left = picAccessDenied.Right;

                int groupLeft = (grpSecureConfiguration.ClientSize.Width - (lblAccessDenied.Right - picAccessDenied.Left)) / 2;
                int groupTop  = (grpSecureConfiguration.ClientSize.Height - lblAccessDenied.Height) / 2;

                picAccessDenied.Top = groupTop;
                lblAccessDenied.Top = groupTop;

                picAccessDenied.Left = groupLeft;
                lblAccessDenied.Left = picAccessDenied.Right;
            }
            else if (null != step && step.SecureConfigurationRecordIdInvalid)
            {
                picInvalidSecureConfigurationId.Visible = true;
                lblInvalidSecureConfigurationId.Visible = true;
                lnkInvalidSecureConfigurationId.Visible = true;
                txtSecureConfig.Visible = false;

                picInvalidSecureConfigurationId.Image = CrmResources.LoadImage("AccessDenied");
                lblInvalidSecureConfigurationId.Left  = picInvalidSecureConfigurationId.Right;

                int groupLeft = (grpSecureConfiguration.ClientSize.Width - (lblInvalidSecureConfigurationId.Right - picInvalidSecureConfigurationId.Left)) / 2;
                int groupTop  = (grpSecureConfiguration.ClientSize.Height - (lnkInvalidSecureConfigurationId.Bottom - picInvalidSecureConfigurationId.Top)) / 2;

                picInvalidSecureConfigurationId.Top = groupTop;
                lblInvalidSecureConfigurationId.Top = groupTop;
                lnkInvalidSecureConfigurationId.Top = lblInvalidSecureConfigurationId.Bottom + 6;

                picInvalidSecureConfigurationId.Left = groupLeft;
                lblInvalidSecureConfigurationId.Left = picAccessDenied.Right;
                lnkInvalidSecureConfigurationId.Left = lblInvalidSecureConfigurationId.Left;

                m_secureConfigurationIdIsInvalid = true;
            }

            LoadEntities();
            CheckDeploymentSupported();
        }
Exemplo n.º 9
0
        private void btnRegister_Click(object sender, EventArgs e)
        {
            CrmPluginStep step = new CrmPluginStep(m_org);

            bool isDeploymentOfflineChecked = (chkDeploymentOffline.Enabled && chkDeploymentOffline.Checked);

            //The Server Deployment box should be considered "Checked" when it is enabled and checked OR when it is a service
            //endpoint Step (this is the case when the combo box is enabled)
            bool isDeploymentServerChecked = (chkDeploymentServer.Enabled && chkDeploymentServer.Checked) || cmbServiceEndpoint.Visible;

            #region Extract Information

            //Validate information
            if (!isDeploymentOfflineChecked && !isDeploymentServerChecked)
            {
                MessageBox.Show("At least one Step Deployment must be specified", "Step Registration",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                chkDeploymentServer.Focus();
                return;
            }
            else if (Message == null)
            {
                MessageBox.Show("Invalid Message Name specified. Please re-enter the message name",
                                "Invalid Message Name", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtMessageName.Focus();
                return;
            }
            else if (radModeAsync.Checked && !(radStagePostOperation.Checked || radStagePostOperationDeprecated.Checked))
            {
                MessageBox.Show("Asynchronous Execution Mode requires registration in one of the Post Stages. Please change the Mode or the Stage.",
                                "Step Registration", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (txtName.TextLength == 0)
            {
                MessageBox.Show("Name is a required field.", "Step Registration",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtName.Focus();
                return;
            }
            else if (MessageEntity == null)
            {
                MessageBox.Show("Invalid Primary Entity or Secondary Entity specified. Please re-enter the data.",
                                "Invalid Entity Name", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPrimaryEntity.Focus();
                return;
            }
            else if (MessageEntity.PrimaryEntity != txtPrimaryEntity.Text && txtPrimaryEntity.Text.Length > 0)
            {
                MessageBox.Show("Invalid Primary Entity specified. Please re-enter the data.",
                                "Invalid Entity Name", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPrimaryEntity.Focus();
                return;
            }
            else if (MessageEntity.SecondaryEntity != txtSecondaryEntity.Text && txtSecondaryEntity.Text.Length > 0)
            {
                MessageBox.Show("Invalid Secondary Entity specified. Please re-enter the data.",
                                "Invalid Entity Name", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtSecondaryEntity.Focus();
                return;
            }
            else if (cmbPlugins.SelectedIndex < 0)
            {
                MessageBox.Show("Plugin was not specified. This a required field.", "Step Registration",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cmbPlugins.Focus();
                return;
            }
            else if (cmbUsers.SelectedIndex < 0)
            {
                MessageBox.Show("User was not specified. This a required field.", "Step Registration",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cmbUsers.Focus();
                return;
            }
            else if (txtName.TextLength == 0)
            {
                txtName.Text = GenerateDescription();
            }
            else if (isDeploymentOfflineChecked &&
                     txtSecureConfig.TextLength != 0 && txtSecureConfig.Text.Trim().Length != 0)
            {
                MessageBox.Show(this, "Secure Configuration is not supported for Steps deployed Offline.",
                                "Registration", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            CrmPlugin plugin = (CrmPlugin)cmbPlugins.SelectedItem;

            if (cmbServiceEndpoint.Visible)
            {
                if ((radModeSync.Checked))
                {
                    MessageBox.Show("Only asynchronous steps are supported for Service Endpoint plug-ins.",
                                    "Step Registration", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                else if (cmbServiceEndpoint.SelectedIndex < 0)
                {
                    MessageBox.Show("Service Endpoint must be selected for Service Endpoint plug-ins.",
                                    "Step Registration", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            step.MessageId           = Message.MessageId;
            step.MessageEntityId     = MessageEntity.MessageEntityId;
            step.AssemblyId          = plugin.AssemblyId;
            step.FilteringAttributes = crmFilteringAttributes.Attributes;
            step.PluginId            = plugin.PluginId;
            step.ImpersonatingUserId = ((CrmUser)cmbUsers.SelectedItem).UserId;
            step.Name = txtName.Text;
            step.UnsecureConfiguration = txtUnsecureConfiguration.Text;
            step.Description           = txtDescription.Text;

            if (txtSecureConfig.Visible)
            {
                step.SecureConfiguration = txtSecureConfig.Text;
            }

            if (cmbServiceEndpoint.Visible)
            {
                step.ServiceBusConfigurationId = ((CrmServiceEndpoint)cmbServiceEndpoint.SelectedItem).ServiceEndpointId;
            }
            else
            {
                step.ServiceBusConfigurationId = Guid.Empty;
            }

            step.Rank = int.Parse(txtRank.Text);
            step.Mode = (radModeAsync.Checked ? CrmPluginStepMode.Asynchronous : CrmPluginStepMode.Synchronous);

            if (radStagePreValidation.Checked)
            {
                step.Stage = CrmPluginStepStage.PreValidation;
            }
            else if (radStagePreOperation.Checked)
            {
                step.Stage = CrmPluginStepStage.PreOperation;
            }
            else if (radStagePostOperation.Checked)
            {
                step.Stage = CrmPluginStepStage.PostOperation;
            }
            else if (radStagePostOperationDeprecated.Checked)
            {
                step.Stage = CrmPluginStepStage.PostOperationDeprecated;
            }
            else
            {
                throw new NotImplementedException("Unkown Plug-in Stage checked");
            }

            if (null != m_currentStep)
            {
                step.Enabled = m_currentStep.Enabled;
            }

            if (isDeploymentServerChecked && isDeploymentOfflineChecked)
            {
                step.Deployment = CrmPluginStepDeployment.Both;
            }
            else if (isDeploymentOfflineChecked)
            {
                step.Deployment = CrmPluginStepDeployment.OfflineOnly;
            }
            else
            {
                step.Deployment = CrmPluginStepDeployment.ServerOnly;
            }

            if (grpInvocation.Enabled)
            {
                step.InvocationSource = (radInvocationParent.Checked ? CrmPluginStepInvocationSource.Parent : CrmPluginStepInvocationSource.Child);
            }
            else
            {
                step.InvocationSource = null;
            }

            if (step.Mode == CrmPluginStepMode.Asynchronous)
            {
                step.DeleteAsyncOperationIfSuccessful = chkDeleteAsyncOperationIfSuccessful.Checked;
            }
            else
            {
                step.DeleteAsyncOperationIfSuccessful = false;
            }

            if (plugin.IsProfilerPlugin)
            {
                //step.ProfilerStepId = step.StepId;
                //step.UnsecureConfiguration = OrganizationHelper.UpdateWithStandaloneConfiguration(step).ToString();
            }
            else if (null != m_currentStep)
            {
                step.ProfilerOriginalStepId = m_currentStep.ProfilerOriginalStepId;
                step.ProfilerStepId         = m_currentStep.ProfilerStepId;
            }

            #endregion Extract Information

            #region Register the Step

            bool rankChanged = false;
            try
            {
                if (m_currentStep != null)
                {
                    Guid?secureConfigurationId = m_currentStep.SecureConfigurationId;
                    if (m_currentStep.SecureConfigurationRecordIdInvalid)
                    {
                        if (m_secureConfigurationIdIsInvalid)
                        {
                            secureConfigurationId = null;
                        }
                        else
                        {
                            secureConfigurationId = Guid.Empty;
                        }
                    }

                    // If the message has changed, the images may need to change as well
                    List <CrmPluginImage> updateImages = null;
                    if (m_currentStep.MessageId != step.MessageId)
                    {
                        // Add the images for the current step to the list
                        updateImages = new List <CrmPluginImage>(m_currentStep.Images.Count);
                        updateImages.AddRange(m_currentStep.Images.Values);
                    }

                    step.StepId = m_currentStep.StepId;
                    if (!RegistrationHelper.UpdateStep(m_org, step, secureConfigurationId, updateImages))
                    {
                        DialogResult = System.Windows.Forms.DialogResult.None;
                        return;
                    }

                    ////Refresh the profiler step to have the same settings
                    //if (step.IsProfiled)
                    //{
                    //    OrganizationHelper.RefreshProfilerStep(step);
                    //}

                    rankChanged = (m_currentStep.Rank != step.Rank);

                    m_currentStep.SecureConfigurationRecordIdInvalid = m_secureConfigurationIdIsInvalid;
                    m_currentStep.Deployment          = step.Deployment;
                    m_currentStep.Name                = step.Name;
                    m_currentStep.ImpersonatingUserId = step.ImpersonatingUserId;
                    m_currentStep.InvocationSource    = step.InvocationSource;
                    m_currentStep.MessageEntityId     = step.MessageEntityId;
                    m_currentStep.MessageId           = step.MessageId;
                    m_currentStep.FilteringAttributes = step.FilteringAttributes;
                    m_currentStep.Mode                = step.Mode;
                    m_currentStep.Rank                = step.Rank;
                    m_currentStep.DeleteAsyncOperationIfSuccessful = step.DeleteAsyncOperationIfSuccessful;
                    if (txtSecureConfig.Visible)
                    {
                        m_currentStep.SecureConfiguration   = step.SecureConfiguration;
                        m_currentStep.SecureConfigurationId = step.SecureConfigurationId;
                    }
                    m_currentStep.Stage = step.Stage;
                    m_currentStep.UnsecureConfiguration = step.UnsecureConfiguration;
                    m_currentStep.Description           = step.Description;
                    m_currentStep.ProfilerStepId        = step.ProfilerStepId;

                    List <ICrmEntity> stepList = new List <ICrmEntity>(new ICrmEntity[] { step });
                    OrganizationHelper.UpdateDates(m_org, stepList);

                    if (m_currentStep.PluginId != step.PluginId)
                    {
                        m_orgControl.RemoveStep(step.NodeId);
                        m_org.Assemblies[m_currentStep.AssemblyId][m_currentStep.PluginId].RemoveStep(step.StepId);

                        m_currentStep.AssemblyId = step.AssemblyId;
                        m_currentStep.PluginId   = step.PluginId;
                        m_org.Assemblies[step.AssemblyId][step.PluginId].AddStep(step);
                        m_orgControl.AddStep(step);
                    }
                    else if (m_currentStep.ServiceBusConfigurationId != step.ServiceBusConfigurationId)
                    {
                        m_orgControl.RemoveStep(step.NodeId);
                        m_org.Assemblies[m_currentStep.AssemblyId][m_currentStep.PluginId].RemoveStep(step.StepId);

                        m_currentStep.ServiceBusConfigurationId = step.ServiceBusConfigurationId;
                        m_org.Assemblies[step.AssemblyId][step.PluginId].AddStep(step);
                        m_orgControl.AddStep(step);
                    }
                    else
                    {
                        m_orgControl.RefreshStep(m_currentStep);
                    }

                    step = m_currentStep;
                }
                else
                {
                    step.StepId = RegistrationHelper.RegisterStep(m_org, step);

                    List <ICrmEntity> stepList = new List <ICrmEntity>(new ICrmEntity[] { step });
                    OrganizationHelper.UpdateDates(m_org, stepList);

                    plugin.AddStep(step);
                    m_orgControl.AddStep(step);
                    OrganizationHelper.RefreshStep(m_org, step);
                }
            }
            catch (Exception ex)
            {
                ErrorMessageForm.ShowErrorMessageBox(this, "Error occurred while registering the step", "Registration Error", ex);
                return;
            }

            #endregion Register the Step

            DialogResult = DialogResult.OK;
            Close();
        }
Exemplo n.º 10
0
        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);
        }
        public static void SetupAssemblyPlugins(
            this CrmPluginAssembly pluginAssembly,
            Assembly assembly,
            IReadOnlyCollection <XElement> unsecureConfigItems,
            IEnumerable <SdkMessage> messages,
            IEnumerable <SdkMessageFilter> messageFilters)
        {
            Version sdkVersion = null;
            var     types      =
                assembly
                .GetExportedTypes()
                .Where(
                    t =>
                    !t.IsAbstract &&
                    t.IsClass &&
                    (t.Name.EndsWith("Plugin") || t.Name.EndsWith("Activity")));

            foreach (var t in types)
            {
                CrmPluginType       type;
                CrmPluginIsolatable isolatable;

                var xrmPlugin = t.GetInterface(typeof(IPlugin).FullName);
                if (xrmPlugin != null)
                {
                    type       = CrmPluginType.Plugin;
                    isolatable = CrmPluginIsolatable.Yes;
                    if (sdkVersion == null)
                    {
                        sdkVersion = xrmPlugin.Assembly.GetName().Version;
                        pluginAssembly.SdkVersion = new Version(xrmPlugin.Assembly.GetName().Version.Major, xrmPlugin.Assembly.GetName().Version.Minor);
                    }

                    pluginAssembly.SdkVersion = new Version(sdkVersion.Major, sdkVersion.Minor);
                }
                else if (t.IsSubclassOf(typeof(Activity)))
                {
                    type       = CrmPluginType.WorkflowActivity;
                    isolatable = CrmPluginIsolatable.No;
                }
                else
                {
                    throw new Exception("Class is not plugin or workflow");
                }

                var plugin =
                    new CrmPlugin
                {
                    TypeName     = t.FullName,
                    PluginType   = type,
                    AssemblyId   = pluginAssembly.AssemblyId,
                    AssemblyName = pluginAssembly.Name,
                    Isolatable   = isolatable,
                    FriendlyName = Guid.NewGuid().ToString()
                };

                if (type == CrmPluginType.WorkflowActivity)
                {
                    var attr = t.GetCustomAttribute <WorkflowActivityAttribute>();
                    plugin.WorkflowActivityGroupName = " " + attr.WorkflowActivityGroupName;
                    plugin.Name = " " + attr.Name;
                }

                var pluginEntityType = t.BaseType?.GetGenericArguments().LastOrDefault();
                if (pluginEntityType == null)
                {
                    // note: be sure - it is workflow:)
                    pluginAssembly.AddPlugin(plugin);
                    continue;
                }

                var splitted = t.FullName?.Split('.').Reverse().Take(2).ToArray();
                var typeName = splitted?[0].Replace("Plugin", string.Empty);
                plugin.Name = $" {splitted?[1]}: {typeName}";

                var stepMethods = t.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(m => m.DeclaringType == t).ToArray();
                foreach (var stepMethod in stepMethods)
                {
                    var pluginStepAttrs     = stepMethod.GetCustomAttributes <PluginStepAttribute>();
                    var filteringAttributes = stepMethod.GetCustomAttribute <FilteringAttributesAttribute>();
                    foreach (var pluginStepAttr in pluginStepAttrs)
                    {
                        var step =
                            new CrmPluginStep
                        {
                            AssemblyId = plugin.AssemblyId,
                            PluginId   = plugin.Id,
                            DeleteAsyncOperationIfSuccessful = pluginStepAttr.DeleteAsyncOperationIfSuccessful,
                            Deployment = CrmPluginStepDeployment.ServerOnly,
                            Enabled    = pluginStepAttr.Enabled,
                            Name       = RegistrationHelper.GenerateStepName(typeName, pluginStepAttr.PluginMessageName, pluginStepAttr.EntityLogicalName.ToLowerInvariant(), null),
                            Rank       = pluginStepAttr.Rank,
                            Stage      = (CrmPluginStepStage)pluginStepAttr.Stage,
                            Mode       = pluginStepAttr.ExecutionMode == PluginExecutionMode.Asynchronous ? CrmPluginStepMode.Asynchronous : CrmPluginStepMode.Synchronous,
                            MessageId  = messages.First(m => m.Name == pluginStepAttr.PluginMessageName).Id
                        };
                        var filter =
                            messageFilters.FirstOrDefault(
                                f =>
                                f.SdkMessageId.Id == step.MessageId &&
                                f.PrimaryEntityLogicalName == pluginStepAttr.EntityLogicalName.ToLowerInvariant());
                        if (filter == null)
                        {
                            throw new Exception($"{pluginStepAttr.EntityLogicalName} entity doesn't registered yet");
                        }

                        step.MessageEntityId = filter.Id;
                        if (filteringAttributes != null)
                        {
                            step.FilteringAttributes = filteringAttributes.ToString();
                        }

                        var unsecureItem = unsecureConfigItems.FirstOrDefault(it => it.Attribute("key").Value == pluginStepAttr.UnsecureConfig);
                        if (unsecureItem != null)
                        {
                            var value = unsecureItem.Attribute("value").Value;
                            step.UnsecureConfiguration = value == $"#{{{pluginStepAttr.UnsecureConfig}}}" ? unsecureItem.Attribute("default").Value : value;
                        }

                        foreach (var p in stepMethod.GetParameters().Where(p => p.ParameterType == pluginEntityType))
                        {
                            var imageParameters = p.GetCustomAttribute <ImageParametersAttribute>();
                            if (imageParameters == null)
                            {
                                continue;
                            }

                            CrmPluginImage image;
                            switch (p.Name)
                            {
                            case "preEntityImage":
                                image = CreateImage(step, imageParameters.ToString(), pluginStepAttr.PluginMessageName, CrmPluginImageType.PreImage);
                                step.AddImage(image);
                                break;

                            case "postEntityImage":
                                image = CreateImage(step, imageParameters.ToString(), pluginStepAttr.PluginMessageName, CrmPluginImageType.PostImage);
                                step.AddImage(image);
                                break;
                            }
                        }

                        plugin.AddStep(step);
                    }
                }

                pluginAssembly.AddPlugin(plugin);
            }
        }
        public static void SetupAssemblyPlugins(
            this CrmPluginAssembly pluginAssembly,
            Version sdkVersion,
            XDocument config,
            IEnumerable <SdkMessage> messages,
            IEnumerable <SdkMessageFilter> messageFilters)
        {
            XNamespace ns             = "http://schemas.microsoft.com/crm/2011/tools/pluginregistration";
            var        pluginElements = config.Root.Element(ns + "Solutions").Element(ns + "Solution").Element(ns + "PluginTypes").Elements(ns + "Plugin");

            foreach (var pluginElement in pluginElements)
            {
                CrmPluginType       type;
                CrmPluginIsolatable isolatable;

                var typeName = pluginElement.Attribute("TypeName").Value;
                if (typeName.EndsWith("Plugin"))
                {
                    type       = CrmPluginType.Plugin;
                    isolatable = CrmPluginIsolatable.Yes;
                    if (sdkVersion != null)
                    {
                        pluginAssembly.SdkVersion = new Version(sdkVersion.Major, sdkVersion.Minor);
                    }
                }
                else if (typeName.EndsWith("Activity"))
                {
                    type       = CrmPluginType.WorkflowActivity;
                    isolatable = CrmPluginIsolatable.No;
                }
                else
                {
                    throw new Exception("Class is not plugin or workflow");
                }

                var plugin =
                    new CrmPlugin
                {
                    TypeName     = typeName,
                    PluginType   = type,
                    AssemblyId   = pluginAssembly.AssemblyId,
                    AssemblyName = pluginAssembly.Name,
                    Isolatable   = isolatable,
                    FriendlyName = pluginElement.Attribute("FriendlyName").Value
                };

                if (type == CrmPluginType.WorkflowActivity)
                {
                    plugin.WorkflowActivityGroupName = " " + pluginElement.Attribute("FriendlyName").Value;
                    plugin.Name = " " + pluginElement.Attribute("Name").Value;
                    pluginAssembly.AddPlugin(plugin);
                    continue;
                }

                var splitted   = typeName.Split('.').Reverse().Take(2).ToArray();
                var pluginName = splitted[0].Replace("Plugin", string.Empty);
                plugin.Name = $" {splitted[1]}: {pluginName}";

                foreach (var pluginStepEl in pluginElement.Element(ns + "Steps").Elements(ns + "Step"))
                {
                    var step =
                        new CrmPluginStep
                    {
                        AssemblyId = plugin.AssemblyId,
                        PluginId   = plugin.Id,
                        DeleteAsyncOperationIfSuccessful = false, // ToDo: implement for ugly config
                        Deployment  = CrmPluginStepDeployment.ServerOnly,
                        Enabled     = true,                       // ToDo: implement for ugly config
                        Name        = pluginStepEl.Attribute("Name").Value,
                        Rank        = int.Parse(pluginStepEl.Attribute("Rank").Value),
                        Stage       = pluginStepEl.Attribute("Stage").Value == "PreInsideTransaction" ? CrmPluginStepStage.PreOperation : CrmPluginStepStage.PostOperation,   // ToDo: CrmPluginStepStage.PreValidation
                        Mode        = pluginStepEl.Attribute("Mode").Value == PluginExecutionMode.Asynchronous.ToString().ToLowerInvariant() ? CrmPluginStepMode.Asynchronous : CrmPluginStepMode.Synchronous,
                        MessageId   = messages.First(m => m.Name == pluginStepEl.Attribute("MessageName").Value).Id,
                        Description = pluginStepEl.Attribute("Description").Value
                    };
                    var filter =
                        messageFilters.FirstOrDefault(
                            f =>
                            f.SdkMessageId.Id == step.MessageId &&
                            f.PrimaryEntityLogicalName == pluginStepEl.Attribute("PrimaryEntityName").Value.ToLowerInvariant());
                    if (filter == null)
                    {
                        throw new Exception($"{pluginStepEl.Attribute("PrimaryEntityName").Value} entity doesn't registered yet");
                    }

                    step.MessageEntityId = filter.Id;
                    var attr = pluginStepEl.Attribute("FilteringAttributes");
                    if (!string.IsNullOrEmpty(attr?.Value))
                    {
                        step.FilteringAttributes = attr.Value;
                    }

                    var unsecureItem = pluginStepEl.Attribute("CustomConfiguration").Value;
                    if (!string.IsNullOrEmpty(unsecureItem))
                    {
                        step.UnsecureConfiguration = unsecureItem;
                    }

                    foreach (var imageEl in pluginStepEl.Element(ns + "Images").Elements(ns + "Image"))
                    {
                        var image = CreateImage(step, imageEl, pluginStepEl);
                        if (image != null)
                        {
                            step.AddImage(image);
                        }
                    }

                    plugin.AddStep(step);
                }

                pluginAssembly.AddPlugin(plugin);
            }
        }
Exemplo n.º 13
0
        public ImageRegistrationForm(CrmOrganization org, MainControl orgControl,
                                     ICrmTreeNode[] rootNodes, CrmPluginImage image, Guid selectNodeId)
        {
            if (org == null)
            {
                throw new ArgumentNullException("org");
            }
            else if (orgControl == null)
            {
                throw new ArgumentNullException("orgControl");
            }
            else if (rootNodes == null)
            {
                throw new ArgumentNullException("rootNodes");
            }
            m_org          = org;
            m_orgControl   = orgControl;
            m_currentImage = image;

            InitializeComponent();

            crmParameters.Organization = org;

            trvPlugins.CrmTreeNodeSorter = orgControl.CrmTreeNodeSorter;

            trvPlugins.AutoExpand = m_orgControl.IsAutoExpanded;
            trvPlugins.LoadNodes(rootNodes);

            if (image != null)
            {
                if (trvPlugins.HasNode(image.StepId))
                {
                    trvPlugins.SelectedNode = trvPlugins[image.StepId];
                }

                txtEntityAlias.Text = image.EntityAlias;
                txtName.Text        = image.Name;

                CrmPluginStep step = m_org[image.AssemblyId][image.PluginId][image.StepId];
                if (step.MessageEntityId == Guid.Empty)
                {
                    crmParameters.EntityName = "none";
                    crmParameters.Enabled    = false;
                }
                else
                {
                    crmParameters.EntityName = m_org.Messages[step.MessageId][step.MessageEntityId].PrimaryEntity;
                    crmParameters.Attributes = image.Attributes;
                }

                switch (image.ImageType)
                {
                case CrmPluginImageType.Both:
                    chkImageTypePost.Checked = true;
                    chkImageTypePre.Checked  = true;
                    break;

                case CrmPluginImageType.PostImage:
                    chkImageTypePost.Checked = true;
                    chkImageTypePre.Checked  = false;
                    break;

                case CrmPluginImageType.PreImage:
                    chkImageTypePost.Checked = false;
                    chkImageTypePre.Checked  = true;
                    break;

                default:
                    throw new NotImplementedException("ImageType = " + image.ImageType.ToString());
                }

                Text             = "Update Existing Image";
                btnRegister.Text = "Update";

                trvPlugins.Visible = false;

                int difference = grpEntityAlias.Top - grpSteps.Top;

                grpSteps.Visible = false;
                Height          -= difference;

                crmParameters.Enabled = true;
                btnRegister.Enabled   = true;
            }
            else if (trvPlugins.HasNode(selectNodeId))
            {
                trvPlugins.SelectedNode = trvPlugins[selectNodeId];
            }
            else
            {
                crmParameters.Attributes = null;
            }
        }
        public StepRegistrationForm(CrmOrganization org, MainControl orgControl, CrmPlugin plugin, CrmPluginStep step, CrmServiceEndpoint serviceEndpoint)
        {
            if (org == null)
            {
                throw new ArgumentNullException("org");
            }
            else if (orgControl == null)
            {
                throw new ArgumentNullException("control");
            }

            InitializeComponent();

            m_org         = org;
            m_orgControl  = orgControl;
            m_currentStep = step;

            crmFilteringAttributes.Organization = org;

            //Initialize the auto-complete on the Message field
            AutoCompleteStringCollection msgList = new AutoCompleteStringCollection();

            foreach (CrmMessage msg in org.Messages.Values)
            {
                msgList.Add(msg.Name);
            }
            txtMessageName.AutoCompleteCustomSource = msgList;

            //Check whether system plugins should be added to the list
            if (step != null && org[step.AssemblyId][step.PluginId].IsSystemCrmEntity && (!OrganizationHelper.AllowStepRegistrationForPlugin(plugin)))
            {
                cmbPlugins.Enabled = false;
            }
            else if ((plugin != null) && (!OrganizationHelper.AllowStepRegistrationForPlugin(plugin)))
            {
                plugin = null;
            }

            //Add the plugins
            CrmPlugin selectPlugin = null;

            foreach (CrmPluginAssembly assembly in org.Assemblies.Values)
            {
                foreach (CrmPlugin pluginType in assembly.Plugins.Values)
                {
                    if (pluginType.PluginType == CrmPluginType.Plugin &&
                        OrganizationHelper.AllowStepRegistrationForPlugin(pluginType))
                    {
                        if (serviceEndpoint == null && pluginType.TypeName == CrmServiceEndpoint.ServiceBusPluginName && pluginType.CustomizationLevel == 0)
                        {
                            continue;
                            // Donot add OOB Service Bus plugin to the list when it it is not a Service Bus Step
                        }
                        else
                        {
                            if (plugin != null && plugin.PluginId == pluginType.PluginId)
                            {
                                selectPlugin = pluginType;
                                cmbPlugins.Items.Add(pluginType);
                            }
                            else
                            {
                                cmbPlugins.Items.Add(pluginType);
                            }
                        }
                    }
                }
            }

            if (cmbPlugins.Items.Count != 0)
            {
                if (selectPlugin == null)
                {
                    cmbPlugins.SelectedIndex = 0;
                }
                else
                {
                    cmbPlugins.SelectedItem = selectPlugin;
                }
            }

            //Create a user that represents the current user
            CrmUser callingUser = new CrmUser(org);

            callingUser.UserId  = Guid.Empty;
            callingUser.Name    = "Calling User";
            callingUser.Enabled = true;
            cmbUsers.Items.Add(callingUser);

            //Add the users. We do not want to sort because the users list is sorted already and then the calling user
            //will not be at the beginning of the list
            cmbUsers.Sorted = false;
            foreach (CrmUser user in org.Users.Values)
            {
                // Added this check to to prevent OutofMemoryExcetion - When an org is imported, the administrator
                // does not have a name associated with it, Adding Null Names to ComboBox throws OutofMemoryExcetion
                if (null != user && user.Enabled == true && user.Name != null)
                {
                    cmbUsers.Items.Add(user);
                }
                // Special case to add System user
                if (user.Name == "SYSTEM" && user.Enabled == false)
                {
                    cmbUsers.Items.Add(user);
                }
            }

            if (cmbUsers.Items.Count != 0)
            {
                cmbUsers.SelectedIndex = 0;
            }

            CrmServiceEndpoint selectServiceEndpoint = null;

            foreach (CrmServiceEndpoint currentServiceEndpoint in org.ServiceEndpoints.Values)
            {
                if (serviceEndpoint != null && serviceEndpoint.ServiceEndpointId == currentServiceEndpoint.ServiceEndpointId)
                {
                    selectServiceEndpoint = currentServiceEndpoint;
                }
                cmbServiceEndpoint.Items.Add(currentServiceEndpoint);
            }

            if (selectServiceEndpoint != null)
            {
                cmbServiceEndpoint.SelectedItem = selectServiceEndpoint;
            }
            else
            {
                if (cmbServiceEndpoint.Items.Count != 0)
                {
                    cmbServiceEndpoint.SelectedIndex = 0;
                }
            }

            if (serviceEndpoint != null)
            {
                UpdatePluginEventHandlerControls(true);
            }
            else
            {
                UpdatePluginEventHandlerControls(false);
            }

            if (m_currentStep != null)
            {
                txtMessageName.Text = m_org.Messages[m_currentStep.MessageId].Name;

                if (org.MessageEntities.ContainsKey(m_currentStep.MessageEntityId))
                {
                    CrmMessageEntity msgEntity = Message[m_currentStep.MessageEntityId];
                    txtPrimaryEntity.Text   = msgEntity.PrimaryEntity;
                    txtSecondaryEntity.Text = msgEntity.SecondaryEntity;
                }
                else
                {
                    txtPrimaryEntity.Text   = "none";
                    txtSecondaryEntity.Text = "none";
                }

                cmbPlugins.SelectedItem = m_org[m_currentStep.AssemblyId][m_currentStep.PluginId];

                if (m_currentStep.ServiceBusConfigurationId != Guid.Empty)
                {
                    cmbServiceEndpoint.SelectedItem = m_org.ServiceEndpoints[m_currentStep.ServiceBusConfigurationId];
                }

                if (m_currentStep.ImpersonatingUserId == Guid.Empty)
                {
                    cmbUsers.SelectedIndex = 0;
                }
                else
                {
                    cmbUsers.SelectedItem = m_org.Users[m_currentStep.ImpersonatingUserId];
                }
                txtRank.Text = m_currentStep.Rank.ToString();
                switch (m_currentStep.Stage)
                {
                case CrmPluginStepStage.PreValidation:
                    radStagePreValidation.Checked = true;
                    break;

                case CrmPluginStepStage.PreOperation:
                    radStagePreOperation.Checked = true;
                    break;

                case CrmPluginStepStage.PostOperation:
                    radStagePostOperation.Checked = true;
                    break;

                case CrmPluginStepStage.PostOperationDeprecated:
                    radStagePostOperationDeprecated.Checked = true;
                    break;

                default:
                    throw new NotImplementedException("CrmPluginStepStage = " + m_currentStep.Stage.ToString());
                }

                switch (m_currentStep.Mode)
                {
                case CrmPluginStepMode.Asynchronous:

                    radModeAsync.Checked = true;
                    break;

                case CrmPluginStepMode.Synchronous:

                    radModeSync.Checked = true;
                    break;

                default:
                    throw new NotImplementedException("Mode = " + m_currentStep.Mode.ToString());
                }

                switch (m_currentStep.Deployment)
                {
                case CrmPluginStepDeployment.Both:

                    chkDeploymentOffline.Checked = true;
                    chkDeploymentServer.Checked  = true;
                    break;

                case CrmPluginStepDeployment.ServerOnly:

                    chkDeploymentOffline.Checked = false;
                    chkDeploymentServer.Checked  = true;
                    break;

                case CrmPluginStepDeployment.OfflineOnly:

                    chkDeploymentOffline.Checked = true;
                    chkDeploymentServer.Checked  = false;
                    break;

                default:
                    throw new NotImplementedException("Deployment = " + m_currentStep.Deployment.ToString());
                }

                switch (m_currentStep.InvocationSource)
                {
                case null:
                case CrmPluginStepInvocationSource.Parent:

                    radInvocationParent.Checked = true;
                    break;

                case CrmPluginStepInvocationSource.Child:

                    radInvocationChild.Checked = true;
                    break;

                default:
                    throw new NotImplementedException("InvocationSource = " + m_currentStep.InvocationSource.ToString());
                }

                txtDescription.Text = m_currentStep.Description;

                txtSecureConfig.Text = m_currentStep.SecureConfiguration;

                string stepName;
                //if (this.m_currentStep.IsProfiled && org.Plugins[this.m_currentStep.PluginId].IsProfilerPlugin)
                //{
                //    //If the current step is a profiler step, the form that is displayed should use the configuration from the original step.
                //    // ProfilerConfiguration profilerConfig = OrganizationHelper.RetrieveProfilerConfiguration(this.m_currentStep);
                //    // stepName = profilerConfig.OriginalEventHandlerName;
                //    // txtUnsecureConfiguration.Text = profilerConfig.Configuration;
                //}
                //else
                //{
                txtUnsecureConfiguration.Text = m_currentStep.UnsecureConfiguration;
                stepName = m_currentStep.Name;
                //}

                if (stepName == GenerateDescription())
                {
                    m_stepName = GenerateDescription();
                }
                else
                {
                    m_stepName   = null;
                    txtName.Text = stepName;
                }

                if (MessageEntity != null)
                {
                    crmFilteringAttributes.EntityName = MessageEntity.PrimaryEntity;
                }

                crmFilteringAttributes.Attributes           = m_currentStep.FilteringAttributes;
                chkDeleteAsyncOperationIfSuccessful.Checked = m_currentStep.DeleteAsyncOperationIfSuccessful;
                chkDeleteAsyncOperationIfSuccessful.Enabled = (m_currentStep.Mode == CrmPluginStepMode.Asynchronous);

                Text             = "Update Existing Step";
                btnRegister.Text = "Update";

                CheckAttributesSupported();
            }
            else if (!radStagePostOperation.Enabled && radStagePostOperationDeprecated.Enabled)
            {
                radStagePostOperationDeprecated.Checked = true;
            }

            //Check if permissions for the secure configuration was denied
            if (org.SecureConfigurationPermissionDenied)
            {
                picAccessDenied.Visible = true;
                lblAccessDenied.Visible = true;
                txtSecureConfig.Visible = false;

                picAccessDenied.Image = CrmResources.LoadImage("AccessDenied");

                lblAccessDenied.Left = picAccessDenied.Right;

                int groupLeft = (grpSecureConfiguration.ClientSize.Width - (lblAccessDenied.Right - picAccessDenied.Left)) / 2;
                int groupTop  = (grpSecureConfiguration.ClientSize.Height - lblAccessDenied.Height) / 2;

                picAccessDenied.Top = groupTop;
                lblAccessDenied.Top = groupTop;

                picAccessDenied.Left = groupLeft;
                lblAccessDenied.Left = picAccessDenied.Right;
            }
            else if (null != step && step.SecureConfigurationRecordIdInvalid)
            {
                picInvalidSecureConfigurationId.Visible = true;
                lblInvalidSecureConfigurationId.Visible = true;
                lnkInvalidSecureConfigurationId.Visible = true;
                txtSecureConfig.Visible = false;

                picInvalidSecureConfigurationId.Image = CrmResources.LoadImage("AccessDenied");
                lblInvalidSecureConfigurationId.Left  = picInvalidSecureConfigurationId.Right;

                int groupLeft = (grpSecureConfiguration.ClientSize.Width - (lblInvalidSecureConfigurationId.Right - picInvalidSecureConfigurationId.Left)) / 2;
                int groupTop  = (grpSecureConfiguration.ClientSize.Height - (lnkInvalidSecureConfigurationId.Bottom - picInvalidSecureConfigurationId.Top)) / 2;

                picInvalidSecureConfigurationId.Top = groupTop;
                lblInvalidSecureConfigurationId.Top = groupTop;
                lnkInvalidSecureConfigurationId.Top = lblInvalidSecureConfigurationId.Bottom + 6;

                picInvalidSecureConfigurationId.Left = groupLeft;
                lblInvalidSecureConfigurationId.Left = picAccessDenied.Right;
                lnkInvalidSecureConfigurationId.Left = lblInvalidSecureConfigurationId.Left;

                m_secureConfigurationIdIsInvalid = true;
            }

            LoadEntities();
            CheckDeploymentSupported();
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            ITracingService tracer = executionContext.GetExtension <ITracingService>();

            tracer.Trace("Inicialize context");
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            //Create an Organization Service
            tracer.Trace("Inicialize serviceFactory");
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();

            tracer.Trace("Inicialize orgService");
            IOrganizationService orgService = serviceFactory.CreateOrganizationService(context.InitiatingUserId);

            //Registered Step Guid
            var pluginStepGuid = Guid.Empty;

            try
            {
                //Plugin Step object
                tracer.Trace("Inicialize pluginStep");
                CrmPluginStep pluginStep = new CrmPluginStep();

                pluginStep.PrimaryEntity = PrimaryEntity.Get <string>(executionContext);
                tracer.Trace("PrimaryEntity: " + pluginStep.PrimaryEntity);

                pluginStep.PluginAssemblyName = AssemblyName.Get <string>(executionContext);
                tracer.Trace("PluginAssemblyName: " + pluginStep.PluginAssemblyName);

                pluginStep.EventHandler = EventHandler.Get <string>(executionContext);
                tracer.Trace("EventHandler: " + pluginStep.EventHandler);

                pluginStep.Mode = Mode.Get <int>(executionContext);
                tracer.Trace("Mode: " + pluginStep.Mode);

                pluginStep.Rank = Rank.Get <int>(executionContext);
                tracer.Trace("Rank: " + pluginStep.Rank);

                pluginStep.FilteringAttributes = FilteringAttributes.Get <string>(executionContext);
                tracer.Trace("FilteringAttributes: " + pluginStep.FilteringAttributes);

                pluginStep.InvocationSource = InvocationSource.Get <int>(executionContext);
                tracer.Trace("InvocationSource: " + pluginStep.InvocationSource);

                pluginStep.Stage = Stage.Get <int>(executionContext);
                tracer.Trace("Stage: " + pluginStep.Stage);

                pluginStep.Deployment = Deployment.Get <int>(executionContext);
                tracer.Trace("Deployment: " + pluginStep.Deployment);

                pluginStep.Message = Message.Get <string>(executionContext);
                tracer.Trace("Message: " + pluginStep.Message);

                pluginStep.Name = pluginStep.EventHandler + ": " + pluginStep.Message + " of " + pluginStep.PrimaryEntity;
                tracer.Trace("Name: " + pluginStep.Name);

                pluginStep.tracer = tracer;

                tracer.Trace("--- Register Plugin Step --- ");
                //Register Step
                pluginStepGuid = pluginStep.RegisterPluginStep(ref orgService);

                tracer.Trace("pluginStepGuid: " + pluginStepGuid);
                PluginStepGuid.Set(executionContext, pluginStepGuid.ToString());
            }
            catch (Exception e)
            {
                throw new InvalidPluginExecutionException("(RegisterPluginStep) Error! " + e.Message);
            }
        }