//starting a workflow sample public static void StartWorkflowSamples() { //you must open a K2 connection first. We will wrap the K2 connection into a using statement to ensure that it is closed using (Connection K2Conn = new Connection()) { K2Conn.Open("[servername]"); //first, create a new process instance. This only loads the process into memory, it does not start it yet. //Note: if the user does not have rights to start the workflow, an error will be thrown here ProcessInstance K2Proc = K2Conn.CreateProcessInstance(@"[ProjectName]\[Workflow Name]"); //specify the full name of the workflow //now that we have the process as an object in memory, we can set some properties before starting the process K2Proc.Folio = "[ProcessFolio]"; K2Proc.Priority = 1; //datafields should be accessed by name. Be aware of data types when setting values, and ensure that the data field names are spelled correctly! K2Proc.DataFields["[String DataField Name]"].Value = "[somevalue]"; K2Proc.DataFields["[Integer Datafield Name]"].Value = 1; K2Proc.DataFields["[Date Datafield Name]"].Value = DateTime.Now; //XML fields are set using an XML-formatted string XmlDocument xmlDoc = new XmlDocument(); //TODO: set up the XML document as required, or construct a valid XML string somehow K2Proc.XmlFields["[XML DataField Name]"].Value = xmlDoc.ToString(); //once you have set all the necessary values, start the process K2Conn.StartProcessInstance(K2Proc); //you can also start a process synchronously with the Sync override. This approach is used when you need to wait for the //first client event/wait-state in the workflow before returning the StartProcessInstance call, most commonly with //page-flow solutions or with automated testing code. This does take longer to return, so don't use it unless you have a specific reason to wait for the first wait-state or client event K2Conn.StartProcessInstance(K2Proc, true); } }
public void RunInspectors() { var _processFolio = "Compliance Application Populate Inspectors"; //the default label var connection = new Connection(); try { //open connection to K2 server connection.Open(this.serverName, this.connectionString.ToString()); //create process instance var processInstance = connection.CreateProcessInstance(_processFolio); //set process folio processInstance.Folio = _processFolio + DateTime.Now; //start the process connection.StartProcessInstance(processInstance, false); } catch { throw; } finally { // close the connection connection.Close(); } }
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"); } }
/// <summary> /// strat process instance /// </summary> /// <param name="processName">process full name</param> /// <param name="folio">process folio</param> /// <param name="nvcDataFields">process data fields</param> /// <returns>start process instance successfully or not</returns> public static bool StartProcess(string processName, string folio, NameValueCollection nvcDataFields) { using (Connection conn = new Connection()) { bool result = false; try { conn.Open(K2ServerName, GetConnString()); conn.RevertUser(); conn.ImpersonateUser(CurrentUser); ProcessInstance procInst = conn.CreateProcessInstance(processName); if (nvcDataFields != null) { for (int i = 0; i < nvcDataFields.Count; i++) { procInst.DataFields[nvcDataFields.GetKey(i)].Value = nvcDataFields[i]; } } procInst.Folio = folio; conn.StartProcessInstance(procInst); result = true; } catch { throw; } finally { conn.Close(); } return(result); } }
public void SetDataFieldsStartProcess(int?applicationId, string complianceApplicationId, string orgName, string processName, string userName) { //the default label var connection = new Connection(); try { //open connection to K2 server connection.Open(this.serverName, this.connectionString.ToString()); //create process instance var processInstance = connection.CreateProcessInstance(processName); //populate data fields //processInstance.DataFields["ApplicationID"].Value = applicationId; processInstance.DataFields["ComplianceApplicationID"].Value = complianceApplicationId; processInstance.DataFields["Submitter"].Value = userName; //set process folio processInstance.Folio = complianceApplicationId; //start the process connection.StartProcessInstance(processInstance, false); } catch { throw; } finally { // close the connection connection.Close(); } }
/// <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); } }
public virtual int StartProcessInstance(string folio) { ProcessInstance pi = _conn.CreateProcessInstance(ProcessName); pi.Folio = folio; foreach (KeyValuePair <string, object> pair in DataFields) { pi.DataFields[pair.Key].Value = pair.Value; } _conn.StartProcessInstance(pi); return(pi.ID); }
/// <summary> /// Start specific process instance /// Return [ProcInstId] /// </summary> /// <param name="instance">The process instance</param> public int StartProcessInstance(InstParam instance) { int procInstId = 0; if (instance == null) { throw new ArgumentException("Process Instance parameter is null object."); } using (Connection conn = GetWorkflowClient()) { var procInst = CreateInstance(instance.ProcName, instance.Folio, instance.DataFields, instance.Priority); conn.StartProcessInstance(procInst); procInstId = procInst.ID; } return(procInstId); }
/// <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(); } } }
/// <summary> /// 发起流程 /// </summary> /// <param name="processName">流程名称:Project\Process1</param> /// <param name="folio">流程编码</param> /// <param name="nvcDataFields">流程变量</param> /// <returns>流程实例ID</returns> public static int StartProcess(string processName, string currentUser, string folio, CDataFields dataFields) { using (Connection conn = new Connection()) { int procInstID = -1; try { ConnectionSetup conSetup = GetConnectionSetup(); conn.Open(conSetup); conn.RevertUser(); conn.ImpersonateUser(currentUser); ProcessInstance procInst = conn.CreateProcessInstance(processName); SetDataFields(procInst, dataFields); if (string.IsNullOrEmpty(folio)) { folio = System.DateTime.Now.ToString(); } procInst.Folio = folio; conn.StartProcessInstance(procInst); procInstID = procInst.ID; } catch { throw; } finally { try { conn.RevertUser(); } catch { } if (conn != null) { conn.Close(); } } return(procInstID); } }
public int StartProcessInstance(string procFullPath, string folio, IDictionary <string, object> dataFields, int priority) { if (string.IsNullOrEmpty(procFullPath) || string.IsNullOrEmpty(folio)) { return(0); } var procInst = _connection.CreateProcessInstance(procFullPath); string commentKey = null; procInst.Folio = folio; procInst.Priority = priority; foreach (DataField dataField in procInst.DataFields) { commentKey = _commentKeys.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 && _commentKeys.Contains(key)) { procInst.DataFields[commentKey].Value = dataFields[key]; } else { procInst.DataFields[key].Value = dataFields[key]; } }); } _connection.StartProcessInstance(procInst); return(procInst.ID); }
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; } }
public ResultModel StartProcess(string processName, int loginId, string objectId, string folio, Dictionary<string, string> dataFields,out int procInstId) { Connection k2Connect = null; WorklistItem workList = null; ResultModel jr = new ResultModel() { Code = ResultCode.Fail }; procInstId = 0; try { k2Connect = new Connection(); k2Connect.Open(ConfigurationManager.AppSettings["K2Server"], ConfigurationManager.AppSettings["K2LoginString"]); k2Connect.ImpersonateUser(SecurityLable(loginId.ToString())); //创建实例 ProcessInstance ProcessInst = k2Connect.CreateProcessInstance(processName); if (!string.IsNullOrEmpty(folio)) { ProcessInst.Folio = folio; } #region //赋值datafields foreach (string key in dataFields.Keys) { if (ProcessInst.DataFields[key] != null) { ProcessInst.DataFields[key].Value = dataFields[key]; } } #endregion k2Connect.StartProcessInstance(ProcessInst); procInstId = ProcessInst.ID; jr.Code = ResultCode.Sucess; jr.Msg = procInstId.ToString(); } catch (Exception ex) { jr.Msg = ex.Message; } finally { if (workList != null) { if (workList.Status == WorklistStatus.Open) { try { k2Connect.RevertUser(); workList.Release(); } catch { } } } if (k2Connect != null) k2Connect.Close(); } return jr; //var result = (new K2Service.K2Service()).StartProcess(processCode, loginId, objectId, folio, jsonData, ConfigurationManager.AppSettings["APIKEY"]); }
public ContinuationAction MessageReceived(ListenerContext e) { // You can inherit from MessageExtendedInformation if you wish, // the likely scenario for this is if you support plugins yourself. var extended = e.ReceivedInformation.Message.GetExtendedInformation <MessageExtendedInformation>(); var replyExtended = extended.Invert(null); string workflowName; if (extended.Message.Title.StartsWith("START: ", StringComparison.OrdinalIgnoreCase)) { workflowName = extended.Message.Title.Substring(7).Trim(); } else { return(ContinuationAction.Continue); // Allow other plugins to execute. } // Get the message body. string body; try { using (var bodyStream = e.ReceivedInformation.Message.OpenView(new ContentType("text/plain"))) { if (bodyStream != null) { // Another plugin may have moved the position within the stream. bodyStream.Seek(0, System.IO.SeekOrigin.Begin); using (var sr = new StreamReader(bodyStream)) { body = sr.ReadToEnd().Trim(); } } else { body = string.Empty; } } } catch { // TODO: Logging etc. return(ContinuationAction.Continue); // Allow other plugins to execute. } // TODO: Get data from the body somehow. // You can also look into attachments for e.g. InfoPath forms: // e.ReceivedInformation.Message.Attachments try { var con = new Connection(); var cs = new ConnectionSetup(); cs.ParseConnectionString(_k2ServerConnectionString); try { Exception lastException = null; con.Open(cs); // AlternateIdentities are identities with the same email // address, most likely due badly configured claims. for (var i = 0; i < e.AlternateIdentities.Length; i++) { var alt = e.AlternateIdentities[i]; string fqn; // Search for a FQN in the identity. if (alt.TryGetValue("Fqn", out fqn)) { try { con.RevertUser(); con.ImpersonateUser(fqn); var pi = con.CreateProcessInstance(workflowName); // TODO: Set data in the workflow. con.StartProcessInstance(pi); // Tell the user the workflow was started. _destination.ReplyTo(e.ReceivedInformation.Message, new MessageBodyReader("text/plain", "Workflow started"), replyExtended); e.ReceivedInformation.Commit(); // Indicate we were able to handle the message. return(ContinuationAction.Halt); // Stop other plugins from executing. } catch (Exception ex) { // TODO: Logging etc. // This isn't nessecarily a complete failure, // one of the other alternate identities may be // able to action this. lastException = ex; } } } string message; if (lastException != null) { // Identities exist, but the user likely doesn't have rights. message = lastException.ToString(); } else { // No identities exist. message = "Could not find a K2 user for your email address."; } message = "The workflow could not be started: " + message; // Respond with the error. _destination.ReplyTo(e.ReceivedInformation.Message, new MessageBodyReader("text/plain", message), replyExtended); e.ReceivedInformation.Commit(); // Indicate we were able to handle the message. return(ContinuationAction.Halt); // Stop other plugins from executing. } finally { if (con != null) { con.Close(); con.Dispose(); } } } catch { // TODO: Logging etc. return(ContinuationAction.Continue); // Allow other plugins to execute. } }
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"); } }
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; } }
public ResultModel StartProcess(string processName, int loginId, string objectId, string folio, Dictionary <string, string> dataFields, out int procInstId) { Connection k2Connect = null; WorklistItem workList = null; ResultModel jr = new ResultModel() { Code = ResultCode.Fail }; procInstId = 0; try { k2Connect = new Connection(); k2Connect.Open(ConfigurationManager.AppSettings["K2Server"], ConfigurationManager.AppSettings["K2LoginString"]); k2Connect.ImpersonateUser(SecurityLable(loginId.ToString())); //创建实例 ProcessInstance ProcessInst = k2Connect.CreateProcessInstance(processName); if (!string.IsNullOrEmpty(folio)) { ProcessInst.Folio = folio; } #region //赋值datafields foreach (string key in dataFields.Keys) { if (ProcessInst.DataFields[key] != null) { ProcessInst.DataFields[key].Value = dataFields[key]; } } #endregion k2Connect.StartProcessInstance(ProcessInst); procInstId = ProcessInst.ID; jr.Code = ResultCode.Sucess; jr.Msg = procInstId.ToString(); } catch (Exception ex) { jr.Msg = ex.Message; } finally { if (workList != null) { if (workList.Status == WorklistStatus.Open) { try { k2Connect.RevertUser(); workList.Release(); } catch { } } } if (k2Connect != null) { k2Connect.Close(); } } return(jr); //var result = (new K2Service.K2Service()).StartProcess(processCode, loginId, objectId, folio, jsonData, ConfigurationManager.AppSettings["APIKEY"]); }