Пример #1
0
    public void UpdateDataFields(int procInstID, Dictionary <string, string> dict)
    {
        Connection k2Conn = new Connection();

        try
        {
            k2Conn.Open(K2ServerName, WorkflowHelper.GetConnString());

            SourceCode.Workflow.Client.ProcessInstance inst = k2Conn.OpenProcessInstance(procInstID);
            if (inst != null)
            {
                foreach (string s in dict.Keys)
                {
                    inst.DataFields[s].Value = dict[s];
                }
            }
            else
            {
                Response.Redirect("ProcessesManage_List.aspx", false);
            }
            inst.Update();

            k2Conn.Close();
        }
        catch
        {
            k2Conn.Close();
        }
    }
Пример #2
0
    /// <summary>
    /// 是否DataField
    /// </summary>
    /// <param name="procInstID"></param>
    /// <returns></returns>
    bool ExistDataField(int procInstID)
    {
        bool       flag   = false;
        Connection k2Conn = new Connection();

        try
        {
            k2Conn.Open(K2ServerName, WorkflowHelper.GetConnString());
            SourceCode.Workflow.Client.ProcessInstance inst = k2Conn.OpenProcessInstance(procInstID);
            if (inst != null)
            {
                foreach (DataField item in inst.DataFields)
                {
                    if (item.Name == "IsPass")
                    {
                        flag = true;
                        break;
                    }
                }
            }
            k2Conn.Close();
        }
        catch
        {
            k2Conn.Close();
        }
        return(flag);
    }
Пример #3
0
    /// <summary>
    /// 绑定默认DataFields
    /// </summary>
    /// <param name="procInstID"></param>
    private void LoadDataFields(int procInstID)
    {
        List <BPMListItem> items  = new List <BPMListItem>();
        Connection         k2Conn = new Connection();

        try
        {
            k2Conn.Open(K2ServerName, WorkflowHelper.GetConnString());
            SourceCode.Workflow.Client.ProcessInstance inst = k2Conn.OpenProcessInstance(procInstID);
            if (inst != null)
            {
                foreach (DataField df in inst.DataFields)
                {
                    items.Add(new BPMListItem {
                        Name = df.Name, Value = df.Value.ToString()
                    });
                }
                rptList.DataSource = items;
                rptList.DataBind();

                k2Conn.Close();
            }
            else
            {
                k2Conn.Close();
            }
        }
        catch (Exception ex)
        {
            k2Conn.Close();
            lblException.Text    = "异常信息:" + ex.Message;
            lblException.Visible = true;
        }
    }
Пример #4
0
        private void btnDuplicate_Click(object sender, EventArgs e)
        {
            try
            {
                Connection cnx = new Connection();
                cnx.Open(ConfigurationManager.AppSettings["K2ServerName"]);
                SourceCode.Workflow.Client.ProcessInstance pi = cnx.CreateProcessInstance(txtProcessFullName.Text);

                pi.Folio = txtFolio.Text;
                foreach (DataGridViewRow item in dgvDatafields.Rows)
                {
                    pi.DataFields[item.Cells[0].Value.ToString()].Value = item.Cells[1].Value.ToString();
                }

                cnx.StartProcessInstance(pi);
                int newProcId = pi.ID;

                cnx.Close();

                if (ddlActivities.SelectedIndex > 1)
                {
                    WorkflowManagementServer wms = new WorkflowManagementServer();
                    wms.CreateConnection();
                    wms.Connection.Open(ConfigurationManager.AppSettings["K2MgmCnxString"]);
                    wms.GotoActivity(newProcId, ddlActivities.SelectedItem.ToString());
                    wms.Connection.Close();
                }

                MessageBox.Show("L'instance à été dupliquée. (ID: " + newProcId.ToString() + ")", "PI Management");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "PI Manager eror");
            }
        }
Пример #5
0
    public static bool ModifyDataField(string sn, NameValueCollection dataFields)
    {
        Connection k2Conn = new Connection();

        try
        {
            k2Conn.Open(K2ServerName, WorkflowHelper.GetConnString());

            SourceCode.Workflow.Client.ProcessInstance inst = k2Conn.OpenProcessInstance(Convert.ToInt32(sn.Split('_')[0]));
            if (inst != null)
            {
                foreach (string s in dataFields)
                {
                    inst.DataFields[s].Value = dataFields[s];
                }

                inst.Update();
            }
            return(true);
        }
        catch (Exception ex)
        {
            return(false);
        }
        finally
        {
            k2Conn.Close();
        }
    }
Пример #6
0
        private void btnLoadPI_Click(object sender, EventArgs e)
        {
            try
            {
                Connection cnx = new Connection();
                cnx.Open(ConfigurationManager.AppSettings["K2ServerName"]);
                SourceCode.Workflow.Client.ProcessInstance pi = cnx.OpenProcessInstance(int.Parse(txtProcInstanceId.Text));
                txtFolio.Text           = pi.Folio;
                lblStatus.Text          = pi.Status1.ToString();
                txtProcessFullName.Text = pi.FullName;
                DataTable dt = new DataTable("Datafields");
                dt.Columns.Add("Name");
                dt.Columns.Add("Value");

                foreach (DataField df in pi.DataFields)
                {
                    dt.Rows.Add(new object[] { df.Name, df.Value });
                }

                displayActivity();

                dgvDatafields.DataSource = dt;
                dgvDatafields.Refresh();
                dgvDatafields.AutoResizeColumn(0);
                dgvDatafields.Columns[0].ReadOnly = true;
                dgvDatafields.AutoResizeColumn(1);

                cnx.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "PI Manager eror");
            }
        }
Пример #7
0
 /// <summary>
 /// Start specific process instance
 /// </summary>
 /// <param name="instance">The process instance</param>
 public void CreateStartProcessInstance(K2.ProcessInstance instance)
 {
     if (instance == null)
     {
         throw new ArgumentException("Process Instance parameter is null object.");
     }
     using (Connection conn = GetWorkflowClient())
     {
         conn.StartProcessInstance(instance);
     }
 }
Пример #8
0
        private void SetFolio()
        {
            ServiceObject serviceObject = ServiceBroker.Service.ServiceObjects[0];

            string folio  = base.GetStringProperty(Constants.SOProperties.ProcessInstanceClient.ProcessFolio, false);
            int    procId = base.GetIntProperty(Constants.SOProperties.ProcessInstanceClient.ProcessInstanceId, true);

            using (CLIENT.Connection k2Con = this.ServiceBroker.K2Connection.GetWorkflowClientConnection())
            {
                CLIENT.ProcessInstance pi = k2Con.OpenProcessInstance(procId);
                pi.Folio = folio;
                pi.Update();
                k2Con.Close();
            }
        }
Пример #9
0
    /// <summary>
    /// 是否存在实例
    /// </summary>
    /// <param name="procInstID"></param>
    /// <returns></returns>
    bool ExistprocInst(int procInstID)
    {
        Connection k2Conn = new Connection();

        try
        {
            k2Conn.Open(K2ServerName, WorkflowHelper.GetConnString());
            SourceCode.Workflow.Client.ProcessInstance inst = k2Conn.OpenProcessInstance(procInstID);
            k2Conn.Close();
            return(inst != null);
        }
        catch
        {
            k2Conn.Close();
            return(false);
        }
    }
Пример #10
0
        /// <summary>
        /// 发起新的流程实例
        /// </summary>
        /// <param name="WorkflowTypeName">流程类型</param>
        /// <param name="dicDataFields">流程参数集合</param>
        /// <param name="Folio">流程单号</param>
        /// <param name="Sync">发起流程是否异步(默认否)</param>
        /// <returns></returns>
        public static void StartProcessInstance(string WorkflowTypeName, Dictionary <string, object> dicDataFields, string ApplyUserInfoString, bool Sync = false)
        {
            Connection connection = GetK2Connection();//创建K2 链接

            try
            {
                string ProcessInstanceName = GetWorkflowName(WorkflowTypeName);//获取流程全称

                //创建新的流程实例
                SourceCode.Workflow.Client.ProcessInstance pi = connection.CreateProcessInstance(ProcessInstanceName);
                var PIDataFields = pi.DataFields;

                //循环赋值流程参数
                foreach (var dic in dicDataFields)
                {
                    PIDataFields[dic.Key].Value = dic.Value;
                }
                ApplyUserInfo applyUserInfo = ApplyUserInfoString.ToObject <ApplyUserInfo>();

                pi.Folio = CreateFolio(WorkflowTypeName, applyUserInfo);

                //添加审批历史
                string ApprovalResultXML = string.Empty;
                ApprovalResultXML = XMLApproval.ToResultXML(ApprovalResultXML);
                XMLApproval xmlApproval = new XMLApproval();
                xmlApproval.LoadFromXML(ApprovalResultXML);
                xmlApproval.AddApproval(applyUserInfo.ApplyUserName, applyUserInfo.ApplyUserId, "发起", string.Empty, "发起流程");
                pi.XmlFields["ApprovalResult"].Value = xmlApproval.ToXML();

                //发起流程实例
                connection.StartProcessInstance(pi, Sync);
            }
            catch (Exception ex)
            {
                throw new K2Exception(ex.ToString());
            }
            finally
            {
                // 关闭连接
                if (connection != null)
                {
                    connection.Close();
                }
            }
        }
Пример #11
0
        /// <summary>
        /// Create new Workflow instance
        /// </summary>
        /// <param name="fullProccessName">The full path of workflow process name</param>
        /// <param name="folio">The process instance folio</param>
        /// <param name="dataFields">The process instance data fields</param>
        /// <param name="priority">The process instance priority</param>
        /// <returns>The worklist item's process instance</returns>
        public SourceCode.Workflow.Client.ProcessInstance CreateInstance(string fullProccessName, string folio, IDictionary <string, object> dataFields, Priority priority)
        {
            if (string.IsNullOrEmpty(fullProccessName))
            {
                return(null);
            }
            if (string.IsNullOrEmpty(folio))
            {
                return(null);
            }

            using (Connection conn = GetWorkflowClient()) {
                SourceCode.Workflow.Client.ProcessInstance instance = conn.CreateProcessInstance(fullProccessName);
                instance.Folio    = folio;
                instance.Priority = Convert.ToInt16(priority);

                string commentKey = null;

                foreach (K2.DataField dataField in instance.DataFields)
                {
                    commentKey = _comments.SingleOrDefault(p => p == dataField.Name);
                    if (commentKey != null)
                    {
                        break;
                    }
                }

                if (dataFields != null && dataFields.Count > 0)
                {
                    List <string> keys = dataFields.Keys.ToList();
                    keys.ForEach((key) => {
                        if (commentKey != null && _comments.Contains(key))
                        {
                            instance.DataFields[commentKey].Value = dataFields[key];
                        }
                        else
                        {
                            instance.DataFields[key].Value = dataFields[key];
                        }
                    });
                }
                return(instance);
            }
        }
Пример #12
0
        /// <summary>
        /// Create new worklist item process instance
        /// </summary>
        /// <param name="fullProccessName">The full workflow process name</param>
        /// <param name="folio">The worklist item's folio</param>
        /// <param name="dataFields">The process instance data fields</param>
        /// <param name="priority">The worklist item's priority</param>
        /// <param name="xmlFields">The process instance's xml fields</param>
        /// <returns>The worklist item's process instance</returns>
        public SourceCode.Workflow.Client.ProcessInstance CreateInstance(string fullProccessName, string folio, IDictionary <string, object> dataFields, Priority priority, IDictionary <string, string> xmlFields)
        {
            if (xmlFields == null || xmlFields.Count == 0)
            {
                return(null);
            }

            SourceCode.Workflow.Client.ProcessInstance instance = CreateInstance(fullProccessName, folio, dataFields, priority);

            if (instance == null)
            {
                return(null);
            }

            List <string> keys = xmlFields.Keys.ToList();

            keys.ForEach((key) => {
                instance.XmlFields[key].Value = xmlFields[key];
            });
            return(instance);
        }
Пример #13
0
        /// <summary>
        /// Method to prune collection by removing errors for process instances that are not in error state anymore.
        /// </summary>
        /// <param name="client">K2 Client connection for retreiving specific process instances.</param>
        public void Prune(k2Client.Connection client, k2Mgnt.WorkflowManagementServer server)
        {
            int i = 0;

            while (i < Count)
            {
                bool found  = false;
                bool remove = false;
                k2Client.ProcessInstance procInst = null;

                // check if the process instance still exists and is not deleted
                if (ProcessInstanceExists(this[i].ProcInstId, server))
                {
                    // get the process instance that's logged
                    procInst = client.OpenProcessInstance(this[i].ProcInstId);
                    // process instance is still alive!
                    found = true;

                    // now determine whether or not the process instance is still in an error state.
                    // if it is no longer in an error state, flag that it can be removed from the error collection.
                    if (procInst.Status1 != k2Client.ProcessInstance.Status.Error)
                    {
                        remove = true;
                    }
                }

                // if the associated process instance is no longer in an error state OR it has since been
                // 'fixed and completed' or simply deleted, remove the error item from the error collection.
                if ((!found) || remove)
                {
                    RemoveAt(i);
                    _isDirty = true;
                }
                else
                {
                    i++;
                }
            }
        }
Пример #14
0
        /// <summary>
        /// Method to update the error collection using the specified process instance object.
        /// </summary>
        /// <param name="processInstance"></param>
        public void Update(k2Mgnt.ErrorLog el, k2Client.Connection client)
        {
            // check if this error is logged / or if the same error ID if already logged
            if (!Exists(el.ID))
            {
                // get the process instance for the originator and startdate details
                k2Client.ProcessInstance procInst = client.OpenProcessInstance(el.ProcInstID);

                base.Add(
                    new K2ProcessError(
                        el.ID,
                        el.ProcInstID,
                        el.ProcessName,
                        el.Folio,
                        el.ErrorItemName,
                        el.Description,
                        el.ErrorDate,
                        procInst.StartDate,
                        procInst.Originator.FQN));

                _isDirty = true;
            }
        }
Пример #15
0
        public void Execute(IServiceProvider serviceProvider)
        {
            //Create the context
            IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            SourceCode.Workflow.Client.Connection      conn     = null;
            SourceCode.Workflow.Client.ProcessInstance procInst = null;
            string K2EntityIdDataField   = string.Empty;
            string K2EntityNameDataField = string.Empty;
            string K2ContextXMLDataField = string.Empty;
            Entity currentEntity         = new Entity();

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                // Obtain the target business entity from the input parameters.
                currentEntity = (Entity)context.InputParameters["Target"];
            }

            if (context.OutputParameters.Contains("id"))
            {
                EntityID = new Guid(context.OutputParameters["id"].ToString());
            }
            else if (currentEntity.Id != null)
            {
                EntityID = currentEntity.Id;
            }

            // Get K2 Associations
            #region K2 Associations

            string K2AssociationsFetchXML = Resources.K2AssociationsFetchXML.Replace("[startoption]", context.MessageName);
            K2AssociationsFetchXML = K2AssociationsFetchXML.Replace("[entityname]", currentEntity.LogicalName.ToLower());
            EntityCollection k2associations = service.RetrieveMultiple(new FetchExpression(K2AssociationsFetchXML));

            #endregion

            // if an K2 Association is found then get K2 Settings and start K2 process for each association
            if (k2associations.Entities.Count > 0)
            {
                // Get K2 Settings
                #region K2 Settings
                //Get Connection Settings

                EntityCollection k2settings = service.RetrieveMultiple(new FetchExpression(Resources.K2SettingsFetchXML));

                foreach (Entity setting in k2settings.Entities)
                {
                    string name  = setting["k2_name"].ToString();
                    string value = setting["k2_value"].ToString();

                    switch (name)
                    {
                    case "WorkflowServerConnectionString":
                        K2WorkflowServerConnectionString = value;
                        break;

                    case "HostServerConnectionString":
                        K2HostServerConnectionString = value;
                        break;

                    case "K2ServerName":
                        K2Server = value;
                        break;
                    }
                }
                #endregion K2 Settings

                bool StartProcess = false;

                // start process for each association returned
                foreach (Entity entity in k2associations.Entities)
                {
                    StartProcess = MustStartForMessage(entity["k2_startoption"].ToString(), context.MessageName);
                    if (StartProcess)
                    {
                        if (entity.Contains("k2_processfullname"))
                        {
                            K2ProcessName = entity["k2_processfullname"].ToString();
                        }
                        if (entity.Contains("k2_entityiddatafield"))
                        {
                            K2EntityIdDataField = entity["k2_entityiddatafield"].ToString();
                        }
                        if (entity.Contains("k2_entitynamedatafield"))
                        {
                            K2EntityNameDataField = entity["k2_entitynamedatafield"].ToString();
                        }
                        if (entity.Contains("k2_contextxmldatafield"))
                        {
                            K2ContextXMLDataField = entity["k2_contextxmldatafield"].ToString();
                        }


                        #region Create XML Context
                        XmlDocument EntityDoc  = null;
                        ColumnSet   allColumns = new ColumnSet(true);

                        //Entity currentEntity = service.Retrieve(CRMEntityName, EntityID, allColumns);

                        Entity originatorUserEntity = service.Retrieve("systemuser", context.InitiatingUserId, allColumns);

                        XmlDocument inputDataDoc = new XmlDocument();

                        //Create instantiation data for Entity
                        EntityDoc = new XmlDocument();
                        XmlElement EntElement = EntityDoc.CreateElement("CRMContext");

                        //Create Item element
                        XmlElement xmlItem = EntityDoc.CreateElement("Context");

                        //Create Name Element
                        XmlElement xmlName = EntityDoc.CreateElement("EntityId");
                        xmlName.InnerText = EntityID.HasValue ? EntityID.Value.ToString() : "";
                        xmlItem.AppendChild(xmlName);

                        xmlName           = EntityDoc.CreateElement("EntityType");
                        xmlName.InnerText = currentEntity.LogicalName;
                        xmlItem.AppendChild(xmlName);

                        XmlElement xmlOrgName = EntityDoc.CreateElement("Organization");
                        xmlOrgName.InnerText = context.OrganizationName;
                        xmlItem.AppendChild(xmlOrgName);

                        xmlName           = EntityDoc.CreateElement("CRMUserId");
                        xmlName.InnerText = context.InitiatingUserId.ToString();
                        xmlItem.AppendChild(xmlName);

                        xmlName           = EntityDoc.CreateElement("UserFQN");
                        xmlName.InnerText = originatorUserEntity["domainname"] != null ? originatorUserEntity["domainname"].ToString() : "";
                        xmlItem.AppendChild(xmlName);

                        xmlName           = EntityDoc.CreateElement("UserDisplayName");
                        xmlName.InnerText = originatorUserEntity["fullname"] != null ? originatorUserEntity["fullname"].ToString() : "";
                        xmlItem.AppendChild(xmlName);

                        //Add Item to main doc
                        EntElement.AppendChild(xmlItem);

                        EntityDoc.AppendChild(EntElement);

                        EntElement = null;
                        xmlName    = null;

                        #endregion Create XML Context

                        #region Start K2 Process

                        conn = new SourceCode.Workflow.Client.Connection();

                        try
                        {
                            //Open connection to K2 Server
                            ConnectionSetup connectSetup = new ConnectionSetup();
                            connectSetup.ConnectionString = K2WorkflowServerConnectionString;

                            conn.Open(connectSetup);

                            // impersonate as originators if domainname retrieved from CRM systemuser
                            if (originatorUserEntity != null && originatorUserEntity.Contains("domainname"))
                            {
                                if (!string.IsNullOrEmpty(originatorUserEntity["domainname"].ToString()))
                                {
                                    conn.ImpersonateUser(originatorUserEntity["domainname"].ToString());
                                }
                            }

                            //Create new process instance
                            procInst = conn.CreateProcessInstance(K2ProcessName);

                            //Set CRM context field value
                            if (!string.IsNullOrEmpty(K2ContextXMLDataField))
                            {
                                try
                                {
                                    procInst.XmlFields[K2ContextXMLDataField].Value = EntityDoc.OuterXml.ToString();
                                }
                                catch (Exception ex)
                                {
                                    System.Diagnostics.EventLog.WriteEntry("SourceCode.Logging.Extension.EventLogExtension", "K2 CRM Plugin - Entity Name - " + context.PrimaryEntityName.ToString() + " - " + "Error writing to XMLField " + K2ContextXMLDataField + " :::: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                                }
                            }
                            if (!string.IsNullOrEmpty(K2EntityIdDataField))
                            {
                                try
                                {
                                    procInst.DataFields[K2EntityIdDataField].Value = context.PrimaryEntityId;
                                }
                                catch (Exception ex)
                                {
                                    System.Diagnostics.EventLog.WriteEntry("SourceCode.Logging.Extension.EventLogExtension", "K2 CRM Plugin - Entity Name - " + context.PrimaryEntityName.ToString() + " - " + "Error writing to DataField " + K2EntityIdDataField + " :::: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                                }
                            }
                            if (!string.IsNullOrEmpty(K2EntityNameDataField))
                            {
                                try
                                {
                                    procInst.DataFields[K2EntityNameDataField].Value = context.PrimaryEntityName.ToLower();
                                }
                                catch (Exception ex)
                                {
                                    System.Diagnostics.EventLog.WriteEntry("SourceCode.Logging.Extension.EventLogExtension", "K2 CRM Plugin - Entity Name - " + context.PrimaryEntityName.ToString() + " - " + "Error writing to DataField " + K2EntityNameDataField + " :::: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                                }
                            }

                            conn.StartProcessInstance(procInst);
                            try
                            {
                                System.Diagnostics.EventLog.WriteEntry("SourceCode.Logging.Extension.EventLogExtension", "Process Started: " + K2ProcessName, System.Diagnostics.EventLogEntryType.Information);
                            }
                            catch { }
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.EventLog.WriteEntry("SourceCode.Logging.Extension.EventLogExtension", "Entity Name - " + context.PrimaryEntityName.ToString() + " - " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                            throw;
                        }
                        finally
                        {
                            if (service != null)
                            {
                                service = null;
                            }

                            if (conn != null)
                            {
                                conn.Dispose();
                            }
                            conn = null;

                            if (procInst != null)
                            {
                                procInst = null;
                            }
                            EntityDoc = null;
                        }


                        #endregion  Start K2 Process
                    }
                }
            }
        }
Пример #16
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            SourceCode.Workflow.Client.Connection      conn     = null;
            SourceCode.Workflow.Client.ProcessInstance procInst = null;
            XmlDocument EntityDoc             = null;
            string      K2EntityIdDataField   = string.Empty;
            string      K2EntityNameDataField = string.Empty;
            string      K2ContextXMLDataField = string.Empty;


            //Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            //Create the context
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            // get K2 configuration context
            // custom entity that stores core information for each entity and process

            EntityID      = context.PrimaryEntityId;
            CRMEntityName = context.PrimaryEntityName.ToLower();


            //Get Processes to Start from the K2 Assosiation entity in CRM
            // Workflow Activity gets these values from the WF configuration
            // Plugin retrieves these values from the K2 Associations entity instance

            K2ProcessName         = ProcessFullName.Get <string>(executionContext);
            K2EntityIdDataField   = EntityIdDataField.Get <string>(executionContext);
            K2EntityNameDataField = EntityNameDataField.Get <string>(executionContext);
            K2ContextXMLDataField = ContextXMLDataField.Get <string>(executionContext);

            // Get K2 Settings
            #region K2 Settings
            //Get Connection Settings

            // all users need read access to the K2 Settings and K2 Associations Entity
            // need to find a way to give all users access by default
            // TODO: revert to system user to read K2settings

            EntityCollection k2settings = service.RetrieveMultiple(new FetchExpression(Resources.K2SettingsFetchXML));

            foreach (Entity setting in k2settings.Entities)
            {
                string name  = setting["k2_name"].ToString();
                string value = setting["k2_value"].ToString();

                switch (name)
                {
                case "WorkflowServerConnectionString":
                    K2WorkflowServerConnectionString = value;
                    break;

                case "HostServerConnectionString":
                    K2HostServerConnectionString = value;
                    break;

                case "K2ServerName":
                    K2Server = value;
                    break;
                }
            }
            #endregion K2 Settings

            #region Create XML Context

            ColumnSet allColumns = new ColumnSet(true);

            Entity currentEntity = service.Retrieve(CRMEntityName, EntityID, allColumns);

            Entity originatorUserEntity = service.Retrieve("systemuser", context.UserId, allColumns);

            XmlDocument inputDataDoc = new XmlDocument();

            //Create instantiation data for Entity
            EntityDoc = new XmlDocument();
            XmlElement EntElement = EntityDoc.CreateElement("CRMContext");

            //Create Item element
            XmlElement xmlItem = EntityDoc.CreateElement("Context");

            //Create Name Element
            XmlElement xmlName = EntityDoc.CreateElement("EntityId");
            xmlName.InnerText = EntityID.ToString();
            xmlItem.AppendChild(xmlName);

            xmlName           = EntityDoc.CreateElement("EntityType");
            xmlName.InnerText = context.PrimaryEntityName;
            xmlItem.AppendChild(xmlName);

            XmlElement xmlOrgName = EntityDoc.CreateElement("Organization");
            xmlOrgName.InnerText = context.OrganizationName;
            xmlItem.AppendChild(xmlOrgName);

            xmlName           = EntityDoc.CreateElement("CRMUserId");
            xmlName.InnerText = context.UserId.ToString();
            xmlItem.AppendChild(xmlName);

            xmlName           = EntityDoc.CreateElement("UserFQN");
            xmlName.InnerText = originatorUserEntity["domainname"] != null ? originatorUserEntity["domainname"].ToString() : "";
            xmlItem.AppendChild(xmlName);

            xmlName           = EntityDoc.CreateElement("UserDisplayName");
            xmlName.InnerText = originatorUserEntity["fullname"] != null ? originatorUserEntity["fullname"].ToString() : "";
            xmlItem.AppendChild(xmlName);

            //Add Item to main doc
            EntElement.AppendChild(xmlItem);

            EntityDoc.AppendChild(EntElement);

            //Release node objects
            EntElement = null;
            xmlName    = null;

            #endregion Create XML Context

            conn = new Connection();
            //procInst = new ProcessInstance();

            try
            {
                ConnectionSetup connectSetup = new ConnectionSetup();
                connectSetup.ConnectionString = K2WorkflowServerConnectionString;

                conn.Open(connectSetup);

                if (originatorUserEntity != null && originatorUserEntity["domainname"] != null)
                {
                    conn.ImpersonateUser(originatorUserEntity["domainname"].ToString());
                }

                //Create new process instance
                procInst = conn.CreateProcessInstance(K2ProcessName);

                //Set CRM context field value
                if (!string.IsNullOrEmpty(K2ContextXMLDataField))
                {
                    try
                    {
                        procInst.XmlFields[K2ContextXMLDataField].Value = EntityDoc.OuterXml.ToString();
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.EventLog.WriteEntry("SourceCode.Logging.Extension.EventLogExtension", "K2 CRM Plugin - Entity Name - " + context.PrimaryEntityName.ToString() + " - " + "Error writing to XMLField " + K2ContextXMLDataField + " :::: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                    }
                }
                if (!string.IsNullOrEmpty(K2EntityIdDataField))
                {
                    try
                    {
                        procInst.DataFields[K2EntityIdDataField].Value = context.PrimaryEntityId;
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.EventLog.WriteEntry("SourceCode.Logging.Extension.EventLogExtension", "K2 CRM Plugin - Entity Name - " + context.PrimaryEntityName.ToString() + " - " + "Error writing to DataField " + K2EntityIdDataField + " :::: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                    }
                }
                if (!string.IsNullOrEmpty(K2EntityNameDataField))
                {
                    try
                    {
                        procInst.DataFields[K2EntityNameDataField].Value = context.PrimaryEntityName.ToLower();
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.EventLog.WriteEntry("SourceCode.Logging.Extension.EventLogExtension", "K2 CRM Plugin - Entity Name - " + context.PrimaryEntityName.ToString() + " - " + "Error writing to DataField " + K2EntityNameDataField + " :::: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                    }
                }
                // start the K2 process
                conn.StartProcessInstance(procInst);

                try
                {
                    System.Diagnostics.EventLog.WriteEntry("SourceCode.Logging.Extension.EventLogExtension", "Process Started: " + K2ProcessName, System.Diagnostics.EventLogEntryType.Information);
                }
                catch { }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("SourceCode.Logging.Extension.EventLogExtension", "Entity Name - " + context.PrimaryEntityName.ToString() + " - " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                throw;
            }
            finally
            {
                if (service != null)
                {
                    service = null;
                }

                if (conn != null)
                {
                    conn.Dispose();
                }
                conn = null;

                if (procInst != null)
                {
                    procInst = null;
                }
                EntityDoc = null;
            }
        }