Exemplo n.º 1
0
        private string GenerateDescription()
        {
            //Retrieve metadata about the filter
            string messageName;
            string primaryEntity   = txtPrimaryEntity.Text;
            string secondaryEntity = txtSecondaryEntity.Text;

            if (Message == null)
            {
                messageName = txtMessageName.Text;
            }
            else
            {
                messageName = Message.Name;

                if (MessageEntity != null)
                {
                    primaryEntity   = MessageEntity.PrimaryEntity;
                    secondaryEntity = MessageEntity.SecondaryEntity;
                }
            }

            //Retrieve the name of the type
            string typeName;

            if (cmbServiceEndpoint.Visible)
            {
                if (null == cmbServiceEndpoint.SelectedItem)
                {
                    typeName = null;
                }
                else
                {
                    typeName = ((CrmServiceEndpoint)cmbServiceEndpoint.SelectedItem).Name;
                }
            }
            else
            {
                if (null == cmbPlugins.SelectedItem)
                {
                    typeName = null;
                }
                else
                {
                    CrmPlugin plugin = ((CrmPlugin)cmbPlugins.SelectedItem);
                    if (plugin.IsProfilerPlugin)
                    {
                        typeName = "Plug-in Profiler";
                    }
                    else
                    {
                        typeName = ((CrmPlugin)cmbPlugins.SelectedItem).TypeName;
                    }
                }
            }

            return(RegistrationHelper.GenerateStepDescription(typeName, messageName, primaryEntity, secondaryEntity));
        }
        public static Guid RegisterPlugin(CrmOrganization org, CrmPlugin plugin)
        {
            if (org == null)
            {
                throw new ArgumentNullException("org");
            }
            else if (plugin == null)
            {
                throw new ArgumentNullException("plugin");
            }

            PluginType pt = (PluginType)plugin.GenerateCrmEntities()[PluginType.EntityLogicalName];

            return(org.OrganizationService.Create(pt));
        }
        public static void UpdatePlugin(CrmOrganization org, CrmPlugin plugin)
        {
            if (org == null)
            {
                throw new ArgumentNullException("org");
            }
            else if (plugin == null)
            {
                throw new ArgumentNullException("plugin");
            }

            PluginType ptl = (PluginType)plugin.GenerateCrmEntities()[PluginType.EntityLogicalName];

            org.OrganizationService.Update(ptl);
            OrganizationHelper.RefreshPlugin(org, plugin);
        }
        private void cmbPlugins_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Determine the version of the SDK that this plug-in depends on
            Version   sdkVersion;
            CrmPlugin plugin = (CrmPlugin)cmbPlugins.SelectedItem;

            if (null == plugin)
            {
                sdkVersion = null;
            }
            else
            {
                sdkVersion = plugin.Organization.Assemblies[plugin.AssemblyId].SdkVersion;
            }

            //Determine what boxes to enable
            bool enableV4Controls   = true;
            bool enable2011Controls = true;

            if (null != sdkVersion)
            {
                switch (sdkVersion.Major)
                {
                case 4:
                    enable2011Controls = false;
                    break;

                case 5:
                    enableV4Controls = false;
                    break;
                }
            }

            //Enable the correct controls
            grpInvocation.Enabled                   = enableV4Controls;
            radStagePreOperation.Enabled            = enable2011Controls;
            radStagePostOperation.Enabled           = enable2011Controls;
            radStagePostOperationDeprecated.Enabled = enableV4Controls;
        }
Exemplo n.º 5
0
 private void AddPluginType(CrmPlugin crmPlugin)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 6
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.º 7
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();
        }
        private void btnRegister_Click(object sender, EventArgs e)
        {
            const string ERROR_CAPTION = "Registration Error";
            string       ERROR_MESSAGE;

            if (m_currentAssembly == null)
            {
                ERROR_MESSAGE = "There was an error while registering the selected plugins. Please check the Registration Log for more information.";
            }
            else
            {
                ERROR_MESSAGE = "There was an error while updating the selected plugins. Please check the Registration Log for more information.";
            }

            #region Extract Plugin Registration Information
            m_progRegistration.Complete(true); //Just in case it has incorrect information

            //Determine the source type. If we are talking about an assembly on disk, verify that it exists
            if (GetAssemblySourceType() == CrmAssemblySourceType.Disk)
            {
                if (string.IsNullOrEmpty(txtServerFileName.Text.Trim()))
                {
                    MessageBox.Show("If the Registration Location is Disk, the \"File Name on Server\" must be specified",
                                    "Missing Information", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    m_progRegistration.Complete(false);
                    return;
                }
            }

            //Create a list of currently selected plugins
            bool assemblyCanBeIsolated = true;
            Dictionary <string, CrmPlugin> checkedPluginList = new Dictionary <string, CrmPlugin>();
            foreach (ICrmTreeNode node in trvPlugins.CheckedNodes)
            {
                if (node.NodeType == CrmTreeNodeType.Plugin || node.NodeType == CrmTreeNodeType.WorkflowActivity)
                {
                    CrmPlugin plugin = (CrmPlugin)node;
                    if (CrmPluginIsolatable.No == plugin.Isolatable)
                    {
                        assemblyCanBeIsolated = false;
                    }

                    checkedPluginList.Add(plugin.TypeName, plugin);
                }
            }

            //Check if there are any plugins selected
            if (checkedPluginList.Count == 0)
            {
                MessageBox.Show("No plugins have been selected from the list. Please select at least one and try again.",
                                "No Plugins Selected", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //Verify that a valid isolation mode has been selected
            if (radIsolationSandbox.Checked && !assemblyCanBeIsolated)
            {
                MessageBox.Show("Since some of the plug-ins cannot be isolated, the assembly cannot be marked as Isolated.",
                                "Isolation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //Reload the assembly
            string            assemblyPath = AssemblyPathControl.FileName;
            CrmPluginAssembly assembly;
            if (string.IsNullOrEmpty(assemblyPath))
            {
                //Clone the existing assembly
                assembly = (CrmPluginAssembly)m_currentAssembly.Clone(false);
            }
            else
            {
                assembly = RegistrationHelper.RetrievePluginsFromAssembly(assemblyPath);

                //Retrieve the source type and determine if the
                assembly.SourceType = GetAssemblySourceType();
                if (CrmAssemblySourceType.Disk != assembly.SourceType)
                {
                    assembly.ServerFileName = null;
                }
                else
                {
                    assembly.ServerFileName = txtServerFileName.Text;
                }
            }

            // Ensure the checked items were all found in the assembly
            var registerPluginList = new List <CrmPlugin>();
            var pluginList         = new List <CrmPlugin>();
            var removedPluginList  = new List <CrmPlugin>();
            var missingPluginList  = new List <CrmPlugin>();

            try
            {
                Parallel.ForEach(assembly.Plugins.Values, (currentPlugin) => {
                    var foundPlugin    = m_registeredPluginList.Where(x => x.TypeName.ToLowerInvariant() == currentPlugin.TypeName.ToLowerInvariant()).FirstOrDefault();
                    var alreadyExisted = (m_registeredPluginList != null && foundPlugin != null);

                    if (alreadyExisted)
                    {
                        currentPlugin.AssemblyId = m_currentAssembly.AssemblyId;
                        currentPlugin.PluginId   = foundPlugin.PluginId;
                    }

                    if (checkedPluginList.ContainsKey(currentPlugin.TypeName))
                    {
                        registerPluginList.Add(currentPlugin);

                        if (currentPlugin.PluginType == CrmPluginType.Plugin)
                        {
                            pluginList.Add(currentPlugin);
                        }
                    }
                    else if (alreadyExisted)
                    {
                        removedPluginList.Add(currentPlugin);
                    }
                });

                if (m_registeredPluginList != null)
                {
                    Parallel.ForEach(m_registeredPluginList, (currentRecord) => {
                        if (!assembly.Plugins.Values.ToList().Any(x => x.TypeName.ToLowerInvariant() == currentRecord.TypeName.ToLowerInvariant()))
                        {
                            missingPluginList.Add(currentRecord);
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                ErrorMessageForm.ShowErrorMessageBox(this, "Unable to load the specified Plugin Assembly", "Plugins", ex);
                return;
            }

            //Update the assembly with the information specified by the user
            assembly.IsolationMode = GetIsolationMode();

            if (missingPluginList.Count != 0)
            {
                var list = missingPluginList.Select(x => x.TypeName).Aggregate((name01, name02) => name01 + "\n" + name02);

                MessageBox.Show($"Following plugin are missing in the assembly:\n\n{list}\n\nRegistration cannot continue!",
                                "Plugins are missing", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //An assembly with plugins must be strongly signed
            if (pluginList.Count != 0)
            {
                if (string.IsNullOrEmpty(assembly.PublicKeyToken))
                {
                    MessageBox.Show("Assemblies containing Plugins must be strongly signed. Sign the Assembly using a KeyFile.",
                                    "Strong Names Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            //Check if there are any plugins selected that were in the assembly.
            if (registerPluginList.Count == 0)
            {
                MessageBox.Show("No plugins have been selected from the list. Please select at least one and try again.",
                                "No Plugins Selected", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else
            {
                assembly.ClearPlugins();
            }

            //If we are doing an Update, do some special processing
            if (m_currentAssembly != null)
            {
                assembly.AssemblyId = m_currentAssembly.AssemblyId;
            }
            #endregion

            #region Register Plugin
            m_progRegistration.Initialize(registerPluginList.Count + removedPluginList.Count, "Preparing Registration");

            int  registeredAssemblies = 0;
            int  ignoredAssemblies    = 0;
            int  updatedAssemblies    = 0;
            bool createAssembly;

            //Check whether the plugin exists. If it exists, should we use the existing one?
            var retrieveDateList = new List <ICrmEntity>();
            try
            {
                Guid pluginAssemblyId = Guid.Empty;
                if (m_currentAssembly != null)
                {
                    if (chkUpdateAssembly.Checked)
                    {
                        string originalGroupName = RegistrationHelper.GenerateDefaultGroupName(m_currentAssembly.Name, new Version(m_currentAssembly.Version));
                        string newGroupName      = RegistrationHelper.GenerateDefaultGroupName(assembly.Name, new Version(assembly.Version));

                        var updateGroupNameList = new List <PluginType>();
                        foreach (var plugin in m_currentAssembly.Plugins)
                        {
                            if (plugin.PluginType == CrmPluginType.WorkflowActivity && string.Equals(plugin.WorkflowActivityGroupName, originalGroupName))
                            {
                                updateGroupNameList.Add(new PluginType()
                                {
                                    Id = plugin.PluginId,
                                    WorkflowActivityGroupName = newGroupName
                                });
                            }
                        }

                        //Do the actual update to the assembly
                        RegistrationHelper.UpdateAssembly(m_org, assemblyPath, assembly, updateGroupNameList.ToArray());

                        m_currentAssembly.Name               = assembly.Name;
                        m_currentAssembly.Culture            = assembly.Culture;
                        m_currentAssembly.CustomizationLevel = assembly.CustomizationLevel;
                        m_currentAssembly.PublicKeyToken     = assembly.PublicKeyToken;
                        m_currentAssembly.ServerFileName     = assembly.ServerFileName;
                        m_currentAssembly.SourceType         = assembly.SourceType;
                        m_currentAssembly.Version            = assembly.Version;
                        m_currentAssembly.IsolationMode      = assembly.IsolationMode;

                        retrieveDateList.Add(m_currentAssembly);

                        foreach (var type in updateGroupNameList)
                        {
                            var plugin = m_currentAssembly.Plugins[type.Id];

                            plugin.WorkflowActivityGroupName = type.WorkflowActivityGroupName;
                            retrieveDateList.Add(plugin);
                        }

                        updatedAssemblies++;
                    }
                    else if (!chkUpdateAssembly.Visible && assembly.IsolationMode != m_currentAssembly.IsolationMode)
                    {
                        var updateAssembly = new PluginAssembly()
                        {
                            Id            = assembly.AssemblyId,
                            IsolationMode = new OptionSetValue((int)assembly.IsolationMode)
                        };

                        m_org.OrganizationService.Update(updateAssembly);

                        m_currentAssembly.ServerFileName = assembly.ServerFileName;
                        m_currentAssembly.SourceType     = assembly.SourceType;
                        m_currentAssembly.IsolationMode  = assembly.IsolationMode;

                        retrieveDateList.Add(m_currentAssembly);

                        updatedAssemblies++;
                    }

                    assembly = m_currentAssembly;

                    createAssembly = false;
                    m_progRegistration.Increment();

                    m_orgControl.RefreshAssembly(m_currentAssembly, false);
                }
                else
                {
                    createAssembly = true;
                    m_progRegistration.Increment();
                }
            }
            catch (Exception ex)
            {
                m_progRegistration.Increment("ERROR: Occurred while checking whether the assembly exists");

                ErrorMessageForm.ShowErrorMessageBox(this, ERROR_MESSAGE, ERROR_CAPTION, ex);

                m_progRegistration.Complete(false);
                return;
            }

            //Register the assembly (if needed)
            if (createAssembly)
            {
                try
                {
                    assembly.AssemblyId   = RegistrationHelper.RegisterAssembly(m_org, assemblyPath, assembly);
                    assembly.Organization = m_org;

                    retrieveDateList.Add(assembly);
                }
                catch (Exception ex)
                {
                    m_progRegistration.Increment("ERROR: Error occurred while registering the assembly");

                    ErrorMessageForm.ShowErrorMessageBox(this, ERROR_MESSAGE, ERROR_CAPTION, ex);

                    m_progRegistration.Complete(false);
                    return;
                }

                registeredAssemblies++;
                m_progRegistration.Increment("SUCCESS: Plugin Assembly was registered");
            }
            else if (m_currentAssembly == null)
            {
                ignoredAssemblies++;
                m_progRegistration.Increment("INFORMATION: Assembly was not registered");
            }
            else
            {
                if (chkUpdateAssembly.Checked)
                {
                    m_progRegistration.Increment("SUCCESS: Assembly was updated");
                }
                else
                {
                    m_progRegistration.Increment("INFORMATION: Assembly was not updated");
                }
            }

            //Check to see if the assembly needs to be added to the list
            if (!m_org.Assemblies.ContainsKey(assembly.AssemblyId))
            {
                m_org.AddAssembly(assembly);

                //Update the Main Form
                try
                {
                    m_orgControl.AddAssembly(assembly);
                    m_progRegistration.Increment();
                }
                catch (Exception ex)
                {
                    m_progRegistration.Increment("ERROR: Error occurred while updating the Main form for the assembly");

                    ErrorMessageForm.ShowErrorMessageBox(this, ERROR_MESSAGE, ERROR_CAPTION, ex);

                    m_progRegistration.Complete(false);
                    return;
                }
            }
            else
            {
                m_progRegistration.Increment();
            }

            // Register the Plugin
            bool createPlugin;
            int  registeredPlugins = 0;
            int  ignoredPlugins    = 0;
            int  errorsPlugins     = 0;

            foreach (var currentPlugin in registerPluginList)
            {
                currentPlugin.AssemblyId = assembly.AssemblyId;

                //Check if the plugin exists
                bool pluginUpdate = m_registeredPluginList != null && m_registeredPluginList.Any(x => x.TypeName.ToLowerInvariant() == currentPlugin.TypeName.ToLowerInvariant());
                try
                {
                    Guid pluginTypeId = Guid.Empty;

                    if (pluginUpdate || (!createAssembly && RegistrationHelper.PluginExists(m_org, currentPlugin.TypeName, assembly.AssemblyId, out pluginTypeId)))
                    {
                        if (pluginUpdate)
                        {
                            createPlugin = false;
                        }
                        else
                        {
                            m_progRegistration.AppendText(string.Format("INFORMATION: Plugin Type Name is already being used by PluginType {0}.", pluginTypeId));

                            switch (MessageBox.Show(string.Format("The specified name \"{0}\" is already registered. Skip the registration of this plugin?\n\nPlease note the plugins may not be the same.", currentPlugin.TypeName),
                                                    "Plugin Already Exists", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
                            {
                            case DialogResult.Yes:
                                createPlugin = false;

                                currentPlugin.PluginId     = pluginTypeId;
                                currentPlugin.Organization = assembly.Organization;
                                break;

                            case DialogResult.No:
                                createPlugin = true;
                                break;

                            case DialogResult.Cancel:
                                m_progRegistration.AppendText("ABORTED: Plugin Registration has been aborted by the user.");
                                m_progRegistration.Complete(false);
                                return;

                            default:
                                throw new NotImplementedException();
                            }
                        }

                        m_progRegistration.Increment();
                    }
                    else
                    {
                        createPlugin = true;
                        m_progRegistration.Increment();
                    }
                }
                catch (Exception ex)
                {
                    m_progRegistration.Increment(string.Format("ERROR: Occurred while checking if {0} is already registered.",
                                                               currentPlugin.TypeName));

                    ErrorMessageForm.ShowErrorMessageBox(this, ERROR_MESSAGE, ERROR_CAPTION, ex);

                    m_progRegistration.Complete(false);
                    return;
                }

                //Create the plugin (if necessary)
                if (createPlugin)
                {
                    try
                    {
                        Guid pluginId = currentPlugin.PluginId;
                        currentPlugin.PluginId     = RegistrationHelper.RegisterPlugin(m_org, currentPlugin);
                        currentPlugin.Organization = m_org;

                        if (pluginId != currentPlugin.PluginId && assembly.Plugins.ContainsKey(pluginId))
                        {
                            assembly.RemovePlugin(pluginId);
                        }

                        retrieveDateList.Add(currentPlugin);

                        m_progRegistration.Increment(string.Format("SUCCESS: Plugin {0} was registered.",
                                                                   currentPlugin.TypeName));

                        registeredPlugins++;
                    }
                    catch (Exception ex)
                    {
                        m_progRegistration.Increment(2, string.Format("ERROR: Occurred while registering {0}.",
                                                                      currentPlugin.TypeName));

                        ErrorMessageForm.ShowErrorMessageBox(this, ERROR_MESSAGE, ERROR_CAPTION, ex);

                        errorsPlugins++;
                        continue;
                    }
                }
                else
                {
                    if (!pluginUpdate)
                    {
                        ignoredPlugins++;
                    }

                    m_progRegistration.Increment();
                }

                //Check if the plugin needs to be added to the list
                if (!assembly.Plugins.ContainsKey(currentPlugin.PluginId))
                {
                    assembly.AddPlugin(currentPlugin);

                    //Update the main form
                    try
                    {
                        m_orgControl.AddPlugin(currentPlugin);
                        m_progRegistration.Increment();
                    }
                    catch (Exception ex)
                    {
                        m_progRegistration.Increment(string.Format("ERROR: Occurred while updating the Main form for {0}.",
                                                                   currentPlugin.TypeName));

                        ErrorMessageForm.ShowErrorMessageBox(this, ERROR_MESSAGE, ERROR_CAPTION, ex);

                        m_progRegistration.Complete(false);
                        return;
                    }
                }
                else
                {
                    m_progRegistration.Increment();
                }
            }

            // Unregister plugins that were unchecked
            int updatedPlugins = 0;
            foreach (var currectPlugin in removedPluginList)
            {
                //Check if the plugin exists
                try
                {
                    RegistrationHelper.Unregister(m_org, currectPlugin);
                    m_progRegistration.Increment(3, string.Format("SUCCESS: Plugin {0} was unregistered.", currectPlugin.TypeName));
                    m_orgControl.RemovePlugin(currectPlugin.PluginId);

                    updatedPlugins++;
                }
                catch (Exception ex)
                {
                    m_progRegistration.Increment(3, string.Format("ERROR: Occurred while unregistering {0}.", currectPlugin.TypeName));

                    ErrorMessageForm.ShowErrorMessageBox(this, ERROR_MESSAGE, ERROR_CAPTION, ex);

                    errorsPlugins++;
                }
            }

            //Update the entities whose Created On / Modified On dates changed
            try
            {
                OrganizationHelper.UpdateDates(m_org, retrieveDateList);
                m_progRegistration.Increment("SUCCESS: Created On / Modified On dates updated");
            }
            catch (Exception ex)
            {
                m_progRegistration.Increment("ERROR: Unable to update Created On / Modified On dates");

                ErrorMessageForm.ShowErrorMessageBox(this, "Unable to update Created On / Modified On dates", "Update Error", ex);
            }
            #endregion

            m_progRegistration.AppendText("SUCCESS: Selected Plugins have been registered");
            m_progRegistration.Complete(false);

            MessageBox.Show(string.Format("The selected Plugins have been registered.\n{0} Assembly Registered\n{1} Assembly Ignored\n{2} Assembly Updated\n{3} Plugin(s) Registered\n{4} Plugin(s) Ignored\n{5} Plugin(s) Encountered Errors\n{6} Plugin(s) Removed",
                                          registeredAssemblies, ignoredAssemblies, updatedAssemblies, registeredPlugins, ignoredPlugins, errorsPlugins, updatedPlugins),
                            "Registered Plugins", MessageBoxButtons.OK, MessageBoxIcon.Information);

            if (errorsPlugins == 0)
            {
                Close();
            }
        }
        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.º 11
0
        public CrmPluginAssembly RetrievePluginsFromAssembly(string path)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            else if (!File.Exists(path))
            {
                throw new ArgumentException("Path does not point to an existing file");
            }

            //Load the assembly
            var assembly         = LoadAssembly(path);
            var assemblyName     = assembly.GetName();
            var defaultGroupName = RegistrationHelper.GenerateDefaultGroupName(assemblyName.Name, assemblyName.Version);

            //Retrieve the assembly properties
            var pluginAssembly = RetrieveAssemblyProperties(assembly, path);

            //Loop through each type and process it
            var errorList = new List <string>();

            foreach (var t in assembly.GetExportedTypes())
            {
                //Plugins and Workflow Activities must be non-abstract classes
                if (t.IsAbstract || !t.IsClass)
                {
                    continue;
                }

                // Plugins must implement the IPlugin interface
                string              errorMessage = null;
                CrmPluginType       type;
                CrmPluginIsolatable isolatable;

                //Retrieve the two interface types
                Type xrmPlugin = t.GetInterface(typeof(IPlugin).FullName);
                var  v4Plugin  = t.GetInterface("Microsoft.Crm.Sdk.IPlugin");

                var workflowGroupName = defaultGroupName;
                var pluginName        = t.FullName;

                Version sdkVersion = null;
                if (null != xrmPlugin)
                {
                    type       = CrmPluginType.Plugin;
                    isolatable = CrmPluginIsolatable.Yes;
                    sdkVersion = xrmPlugin.Assembly.GetName().Version;
                }
                else if (null != v4Plugin)
                {
                    type       = CrmPluginType.Plugin;
                    isolatable = CrmPluginIsolatable.No;
                }
                else if (t.IsSubclassOf(typeof(CodeActivity)) || t.IsSubclassOf(typeof(Activity)))
                {
                    type       = CrmPluginType.WorkflowActivity;
                    isolatable = CrmPluginIsolatable.Yes;
                }
                else
                {
                    continue;
                }

                if (errorMessage != null)
                {
                    errorList.Add(errorMessage);
                }
                else
                {
                    var plugin = new CrmPlugin(null)
                    {
                        TypeName     = t.FullName,
                        Name         = pluginName,
                        PluginType   = type,
                        PluginId     = Guid.NewGuid(),
                        AssemblyId   = pluginAssembly.AssemblyId,
                        AssemblyName = pluginAssembly.Name,
                        Isolatable   = isolatable
                    };

                    if (type == CrmPluginType.WorkflowActivity && !string.IsNullOrWhiteSpace(workflowGroupName))
                    {
                        plugin.WorkflowActivityGroupName = workflowGroupName;
                    }

                    pluginAssembly.AddPlugin(plugin);
                }
            }

            return(pluginAssembly);
        }
        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();
        }