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();
            }
        }
示例#2
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();
        }
示例#3
0
        private void btnRegister_Click(object sender, EventArgs e)
        {
            CrmPluginImage image = new CrmPluginImage(m_org);

            #region Extract Information

            if (trvPlugins.SelectedNode == null ||
                (m_currentImage == null && trvPlugins.SelectedNode.NodeType != CrmTreeNodeType.Step))
            {
                MessageBox.Show("A Step must be selected when registering an image",
                                "Registration", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (!chkImageTypePost.Checked && !chkImageTypePre.Checked)
            {
                MessageBox.Show("At least one Image Type must be specified. This field is required.",
                                "Registration", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (txtEntityAlias.TextLength == 0 || txtEntityAlias.Text.Trim().Length == 0)
            {
                MessageBox.Show("You must enter an alias for this Image. This is a required field.", "Registration",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (!crmParameters.HasAttributes)
            {
                MessageBox.Show("You must specify at least one attribute. This is a required field", "Registration",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //Retrieve the step for this image
            CrmPluginStep step;
            if (m_currentImage == null)
            {
                step = (CrmPluginStep)trvPlugins.SelectedNode;

                //Verify that the step is not a system item
                if (step.IsSystemCrmEntity)
                {
                    m_orgControl.ShowSystemItemError("Cannot register image on this step");
                    return;
                }
            }
            else
            {
                step = m_org[m_currentImage.AssemblyId][m_currentImage.PluginId][m_currentImage.StepId];
            }

            //Retrieve the message
            CrmMessage message = m_org.Messages[step.MessageId];

            //Verify that this step can have images
            if (0 == message.ImageMessagePropertyNames.Count)
            {
                //Create a list of the messages that can have images
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Only steps registered on the following messages can have images:");
                foreach (CrmMessage item in m_org.Messages.Values)
                {
                    if (0 != item.ImageMessagePropertyNames.Count)
                    {
                        sb.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, "- {0}{1}",
                                        item.Name, Environment.NewLine);
                    }
                }

                sb.AppendLine();
                sb.Append("Please select a different step and try again.");

                MessageBox.Show(sb.ToString(), "Invalid Step Selected", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //Start populating the image that will be used
            image.AssemblyId          = step.AssemblyId;
            image.PluginId            = step.PluginId;
            image.StepId              = step.StepId;
            image.Attributes          = crmParameters.Attributes;
            image.EntityAlias         = txtEntityAlias.Text.Trim();
            image.Name                = txtName.Text.Trim();
            image.MessagePropertyName = MessagePropertyNameForm.SelectMessagePropertyName(message);
            if (null == image.MessagePropertyName)
            {
                return;
            }

            if (chkImageTypePre.Checked && chkImageTypePost.Checked)
            {
                image.ImageType = CrmPluginImageType.Both;
            }
            else if (chkImageTypePre.Checked)
            {
                image.ImageType = CrmPluginImageType.PreImage;
            }
            else
            {
                image.ImageType = CrmPluginImageType.PostImage;
            }

            #endregion Extract Information

            #region Register the Image

            try
            {
                if (m_currentImage == null)
                {
                    image.ImageId = RegistrationHelper.RegisterImage(m_org, image);

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

                    step.AddImage(image);
                    m_orgControl.AddImage(image);
                }
                else
                {
                    image.ImageId = m_currentImage.ImageId;
                    RegistrationHelper.UpdateImage(m_org, image);

                    m_currentImage.AssemblyId          = step.AssemblyId;
                    m_currentImage.PluginId            = step.PluginId;
                    m_currentImage.StepId              = step.StepId;
                    m_currentImage.ImageId             = image.ImageId;
                    m_currentImage.Attributes          = image.Attributes;
                    m_currentImage.EntityAlias         = image.EntityAlias;
                    m_currentImage.MessagePropertyName = image.MessagePropertyName;
                    m_currentImage.ImageType           = image.ImageType;

                    image = m_currentImage;

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

                    m_orgControl.RefreshImage(m_currentImage);
                }
            }
            catch (Exception ex)
            {
                ErrorMessageForm.ShowErrorMessageBox(this, "Unable to register the Image due to an error.", "Registration", ex);
                return;
            }

            #endregion Register the Image

            DialogResult = DialogResult.OK;
            Close();
        }