/// <summary>
        /// Open connection k2.
        /// </summary>
        /// <param name="model">The value for connect k2.</param>
        /// <param name="retry">The round of try to connect k2.</param>
        /// <returns></returns>
        private SourceCode.Workflow.Client.Connection Connection(K2ConnectModel model, int retry = 0)
        {
            var connection = new SourceCode.Workflow.Client.Connection();
            int retryNum   = retry;

            try
            {
                string connectionString = this.GetConnectionString(model);
                connection.Open(model.Url, connectionString);
                if (model.K2Profile.Impersonate)
                {
                    connection.ImpersonateUser(model.SecurityLabelName + ":" + model.K2Profile.ImpersonateUser);
                }
            }
            catch (System.Exception ex)
            {
                connection = null;
                retryNum++;

                if (retryNum == 2)
                {
                    throw new System.Exception("Unable to create connection (retry:" + retryNum.ToString() + ") : " + ex.ToString());
                }
                else
                {
                    System.Threading.Thread.Sleep(50);
                    return(Connection(model, retryNum));
                }
            }
            return(connection);
        }
Ejemplo n.º 2
0
        private void ListDataFields()
        {
            var procId = GetIntProperty(Constants.SoProperties.ProcessInstance.ProcInstId, true);

            ServiceBroker.Service.ServiceObjects[0].Properties.InitResultTable();
            var dt = ServiceBroker.ServicePackage.ResultTable;

            using (_wfClient = ServiceBroker.K2Connection.GetWorkflowClientConnection())
            {
                var pi = _wfClient.OpenProcessInstance(procId);
                foreach (client.DataField dataField in pi.DataFields)
                {
                    var dRow = dt.NewRow();
                    dRow[Constants.SoProperties.ProcessInstance.DataFieldName] = dataField.Name;
                    dRow[Constants.SoProperties.ProcessInstance.DataFieldType] = dataField.ValueType.ToString();
                    string dataFieldValue;
                    switch (dataField.ValueType)
                    {
                    case client.DataType.TypeBinary:
                        dataFieldValue = Convert.ToBase64String((byte[])dataField.Value);
                        break;

                    case client.DataType.TypeDate:
                        dataFieldValue = Convert.ToDateTime(dataField.Value).ToString("yyyy-MM-dd HH:mm:ss");
                        break;

                    default:
                        dataFieldValue = Convert.ToString(dataField.Value);
                        break;
                    }
                    dRow[Constants.SoProperties.ProcessInstance.DataFieldValue] = dataFieldValue;
                    dt.Rows.Add(dRow);
                }
            }
        }
 /// <summary>
 /// Reconnection k2.
 /// </summary>
 private void ReConnection()
 {
     if (_connection != null)
     {
         _connection.Close();
     }
     _connection = Connection(_model);
 }
Ejemplo n.º 4
0
        private void StartProcessInstance(bool startGeneric)
        {
            string processName = ServiceBroker.Service.ServiceObjects[0].Methods[0].Name;

            if (!startGeneric)
            {
                processName = GetStringProperty(Constants.SOProperties.ProcessInstanceClient.ProcessName, true);
            }
            int processVersion = GetIntProperty(Constants.SOProperties.ProcessInstanceClient.ProcessVersion);

            ServiceObject serviceObject = ServiceBroker.Service.ServiceObjects[0];

            serviceObject.Properties.InitResultTable();
            DataTable results = ServiceBroker.ServicePackage.ResultTable;


            using (CLIENT.Connection k2Con = new CLIENT.Connection())
            {
                k2Con.Open(K2ClientConnectionSetup);

                CLIENT.ProcessInstance pi;

                if (processVersion > 0)
                {
                    pi = k2Con.CreateProcessInstance(processName, processVersion);
                }
                else
                {
                    pi = k2Con.CreateProcessInstance(processName);
                }

                string folio = GetStringProperty(Constants.SOProperties.ProcessInstanceClient.ProcessFolio);
                if (!string.IsNullOrEmpty(folio))
                {
                    pi.Folio = folio;
                }


                if (startGeneric)
                {
                    MethodParameters mParams = ServiceBroker.Service.ServiceObjects[0].Methods[0].MethodParameters;
                    foreach (CLIENT.DataField df in pi.DataFields)
                    {
                        df.Value = GetDataFieldValue(mParams[df.Name].Value, df.ValueType);
                    }
                }

                k2Con.StartProcessInstance(pi, GetBoolProperty(Constants.SOProperties.ProcessInstanceClient.StartSync));

                DataRow dr = results.NewRow();
                dr[Constants.SOProperties.ProcessInstanceClient.ProcessInstanceId] = pi.ID;
                dr[Constants.SOProperties.ProcessInstanceClient.ProcessFolio]      = pi.Folio;
                results.Rows.Add(dr);

                k2Con.Close();
            }
        }
Ejemplo n.º 5
0
        private void UpdateFolio()
        {
            var folio  = GetStringProperty(Constants.SoProperties.ProcessInstance.ProcessFolio, true);
            var procId = GetIntProperty(Constants.SoProperties.ProcessInstance.ProcInstId, true);

            using (_wfClient = ServiceBroker.K2Connection.GetWorkflowClientConnection())
            {
                var pi = _wfClient.OpenProcessInstance(procId);
                pi.Folio = folio;
                pi.Update();
            }
        }
 /// <summary>
 /// Initial for k2 connection.
 /// </summary>
 /// <param name="model"></param>
 public void Initial(K2ProfileModel model)
 {
     _model = this.SetValue(model.UserName, model.Password, model.ImpersonateUser);
     if (model.Management)
     {
         _connectionManagement = this.ConnectionManagement(_model);
     }
     else
     {
         _connection = this.Connection(_model);
     }
 }
Ejemplo n.º 7
0
        private void UpdateXmlField()
        {
            var xmlFieldName  = GetStringProperty(Constants.SoProperties.ProcessInstance.XmlFieldName, true);
            var xmlFieldValue = GetStringProperty(Constants.SoProperties.ProcessInstance.XmlFieldValue);
            var procId        = GetIntProperty(Constants.SoProperties.ProcessInstance.ProcInstId, true);

            using (_wfClient = ServiceBroker.K2Connection.GetWorkflowClientConnection())
            {
                var pi       = _wfClient.OpenProcessInstance(procId);
                var xmlField = pi.XmlFields[xmlFieldName];
                xmlField.Value = xmlFieldValue;
                pi.Update();
            }
        }
Ejemplo n.º 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();
            }
        }
Ejemplo n.º 9
0
        private void UpdateDataField()
        {
            var dataFieldName  = GetStringProperty(Constants.SoProperties.ProcessInstance.DataFieldName, true);
            var dataFieldValue = GetStringProperty(Constants.SoProperties.ProcessInstance.DataFieldValue);
            var procId         = GetIntProperty(Constants.SoProperties.ProcessInstance.ProcInstId, true);

            using (_wfClient = ServiceBroker.K2Connection.GetWorkflowClientConnection())
            {
                var pi        = _wfClient.OpenProcessInstance(procId);
                var dataField = pi.DataFields[dataFieldName];
                switch (dataField.ValueType)
                {
                case client.DataType.TypeBinary:
                    dataField.Value = Convert.FromBase64String(dataFieldValue);
                    break;

                case client.DataType.TypeBoolean:
                    dataField.Value = Convert.ToBoolean(dataFieldValue);
                    break;

                case client.DataType.TypeDate:
                    dataField.Value = Convert.ToDateTime(dataFieldValue);
                    break;

                case client.DataType.TypeDecimal:
                    dataField.Value = Convert.ToDecimal(dataFieldValue);
                    break;

                case client.DataType.TypeDouble:
                    dataField.Value = Convert.ToDouble(dataFieldValue);
                    break;

                case client.DataType.TypeInteger:
                    dataField.Value = Convert.ToInt32(dataFieldValue);
                    break;

                case client.DataType.TypeLong:
                    dataField.Value = Convert.ToInt64(dataFieldValue);
                    break;

                default:
                    dataField.Value = dataFieldValue;
                    break;
                }
                pi.Update();
            }
        }
Ejemplo n.º 10
0
        private void ListXmlFields()
        {
            var procId = GetIntProperty(Constants.SoProperties.ProcessInstance.ProcInstId, true);

            ServiceBroker.Service.ServiceObjects[0].Properties.InitResultTable();
            var dt = ServiceBroker.ServicePackage.ResultTable;

            using (_wfClient = ServiceBroker.K2Connection.GetWorkflowClientConnection())
            {
                var pi = _wfClient.OpenProcessInstance(procId);
                foreach (client.XmlField xmlField in pi.XmlFields)
                {
                    var dRow = dt.NewRow();
                    dRow[Constants.SoProperties.ProcessInstance.XmlFieldName]  = xmlField.Name;
                    dRow[Constants.SoProperties.ProcessInstance.XmlFieldValue] = xmlField.Value;
                    dt.Rows.Add(dRow);
                }
            }
        }
Ejemplo n.º 11
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++;
                }
            }
        }
Ejemplo n.º 12
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;
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Method to check K2 for process errors since the last scheduled internal.
        /// </summary>
        public void RetrieveNewErrors()
        {
            k2Mgnt.WorkflowManagementServer server = new k2Mgnt.WorkflowManagementServer();
            server.Connection = server.CreateConnection();
            server.Connection.Open(connectionString);

            // client connection to K2 server.
            k2Client.Connection k2Conn = new k2Client.Connection();

            try
            {
                // Search for new process errors in the specified profile and update the error list.
                k2Mgnt.ErrorLogs els = server.GetErrorLogs(server.GetErrorProfile(_errorProfileName).ID);

                // Open client connection to K2 server.

                string host = Regex.Replace(connectionString, @"(.+)(Host\=)(.+)(;)(.+)", "$3");

                k2Conn.Open(host);

                // check every error in the error log
                foreach (k2Mgnt.ErrorLog el in els)
                {
                    Update(el, k2Conn);
                }

                if (ErrorsToBeReported.Count > 0)
                {
                    //
                    // Pull in the related tasks into the error collection.
                    //
                    k2Mgnt.WorklistItems worklistItems =
                        server.GetWorklistItems(
                            new DateTime(1900, 1, 1),
                            DateTime.Now,
                            string.Empty,
                            string.Empty,
                            string.Empty,
                            string.Empty,
                            string.Empty);

                    foreach (SourceCode.Workflow.Management.WorklistItem worklistItem in worklistItems)
                    {
                        if (worklistItem.ProcessInstanceStatus == k2Mgnt.ProcessInstanceStatus.Error)
                        {
                            Update(worklistItem);
                        }
                    }
                }

                //Finally, prune the errors collection.
                Prune(k2Conn, server);
            }
            finally
            {
                if (server.Connection != null)
                {
                    server.Connection.Close();
                }

                if (k2Conn != null)
                {
                    k2Conn.Close();
                }
            }
        }
        private void StartProcessInstance()
        {
            string processName = base.GetStringProperty(Constants.SOProperties.ProcessInstanceManagement.ProcessName, true);
            int processVersion = base.GetIntProperty(Constants.SOProperties.ProcessInstanceManagement.ProcessVersion, false);

            ServiceObject serviceObject = base.ServiceBroker.Service.ServiceObjects[0];
            serviceObject.Properties.InitResultTable();
            DataTable results = base.ServiceBroker.ServicePackage.ResultTable;

            using (CLIENT.Connection k2Con = new CLIENT.Connection())
            {
                k2Con.Open(base.K2ClientConnectionSetup);

                CLIENT.ProcessInstance pi;

                if (processVersion > 0)
                {
                    pi = k2Con.CreateProcessInstance(processName, processVersion);
                }
                else
                {
                    pi = k2Con.CreateProcessInstance(processName);
                }

                string folio = base.GetStringProperty(Constants.SOProperties.ProcessInstanceManagement.ProcessFolio);
                if (string.IsNullOrEmpty(folio))
                {
                    pi.Folio = folio;
                }

                k2Con.StartProcessInstance(pi, base.GetBoolProperty(Constants.SOProperties.ProcessInstanceManagement.StartSync));

                DataRow dr = results.NewRow();
                dr[Constants.SOProperties.ProcessInstanceManagement.ProcessInstanceId] = pi.ID;
                dr[Constants.SOProperties.ProcessInstanceManagement.ProcessFolio] = pi.Folio;

                results.Rows.Add(dr);

            }
        }
        private void StartProcessInstance(bool startGeneric)
        {
            string processName = ServiceBroker.Service.ServiceObjects[0].Methods[0].Name;
            if (!startGeneric)
            {
                processName = GetStringProperty(Constants.SOProperties.ProcessInstanceClient.ProcessName, true);
            }
            int processVersion = GetIntProperty(Constants.SOProperties.ProcessInstanceClient.ProcessVersion);

            ServiceObject serviceObject = ServiceBroker.Service.ServiceObjects[0];
            serviceObject.Properties.InitResultTable();
            DataTable results = ServiceBroker.ServicePackage.ResultTable;

            using (CLIENT.Connection k2Con = new CLIENT.Connection())
            {
                k2Con.Open(K2ClientConnectionSetup);

                CLIENT.ProcessInstance pi;

                if (processVersion > 0)
                {
                    pi = k2Con.CreateProcessInstance(processName, processVersion);
                }
                else
                {
                    pi = k2Con.CreateProcessInstance(processName);
                }

                string folio = GetStringProperty(Constants.SOProperties.ProcessInstanceClient.ProcessFolio);
                if (!string.IsNullOrEmpty(folio))
                {
                    pi.Folio = folio;
                }

                if (startGeneric)
                {
                    MethodParameters mParams = ServiceBroker.Service.ServiceObjects[0].Methods[0].MethodParameters;
                    foreach (CLIENT.DataField df in pi.DataFields)
                    {
                        df.Value = GetDataFieldValue(mParams[df.Name].Value, df.ValueType);
                    }
                }

                k2Con.StartProcessInstance(pi, GetBoolProperty(Constants.SOProperties.ProcessInstanceClient.StartSync));

                DataRow dr = results.NewRow();
                dr[Constants.SOProperties.ProcessInstanceClient.ProcessInstanceId] = pi.ID;
                dr[Constants.SOProperties.ProcessInstanceClient.ProcessFolio] = pi.Folio;
                results.Rows.Add(dr);

                k2Con.Close();
            }
        }
Ejemplo n.º 16
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
                    }
                }
            }
        }
        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

                    }
                }
            }
        }
Ejemplo n.º 18
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;
            }
        }