public static Connection GetConnection(ServiceContext context) { Connection conn = new Connection(); ConnectionSetup conSetup = new ConnectionSetup(); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Host, context[SettingVariable.ServerName]); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.UserID, context[SettingVariable.LoginUser]); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Password, context[SettingVariable.LoginPassword]); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Port, context[SettingVariable.ClientPort]); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Authenticate, "true"); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.WindowsDomain, context[SettingVariable.WindowDomain]); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.IsPrimaryLogin, "true"); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.TimeOut, context[SettingVariable.ConnectionTimeout]); var label = context[SettingVariable.SecurityLabelName]; conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.SecurityLabelName, label); if (label.ToLower() != "k2") { conSetup.ConnectionParameters[ConnectionSetup.ParamKeys.Integrated] = "false"; } conn.Open(context[SettingVariable.ServerName], conSetup.ConnectionString); return conn; }
/// <summary> /// Get Workflow Client with impersonate user /// </summary> /// <returns>The worklist connection to K2 Workflow server</returns> public Connection GetWorkflowClient() { ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["WorkflowServer"]; if (_userAccount == null) { return(null); } if (setting == null) { return(null); } if (string.IsNullOrEmpty(setting.ConnectionString)) { return(null); } ConnectionSetup connectionSetup = new ConnectionSetup(); connectionSetup.ParseConnectionString(setting.ConnectionString); Connection connection = new Connection(); connection.Open(connectionSetup); if (connection.User == null || string.Compare(connection.User.Name, _userAccount, StringComparison.OrdinalIgnoreCase) != 0) { connection.ImpersonateUser(_userAccount); } return(connection); }
/// <summary> /// 更新流程变量 /// </summary> /// <param name="sn">流程实例ID</param> /// <param name="nvcDataFields">要获取的变量的List</param> /// <returns>变量的List</returns> public static void GetProcessDataFields(int procInstID, CDataFields dataFields) { using (Connection conn = new Connection()) { try { ConnectionSetup conSetup = GetConnectionSetup(); conn.Open(conSetup); ProcessInstance procInst = conn.OpenProcessInstance(procInstID); GetDataFields(procInst, dataFields); } catch { throw; } finally { try { conn.RevertUser(); } catch { } if (conn != null) { conn.Close(); } } } }
public static void Sleep(string sn, int second) { SourceCode.Workflow.Client.Connection con = new Connection(); try { ConnectionSetup conSetup = GetConnectionSetup(); con.Open(conSetup); con.ImpersonateUser(_CurrentUser); SourceCode.Workflow.Client.WorklistItem listItem = con.OpenWorklistItem(sn); listItem.Sleep(true, second); } catch (Exception ex) { // TODO: throw? throw ex; } finally { try { con.RevertUser(); } catch { throw; } if (con != null) { con.Close(); } } }
private void writeConnectionSetup(XmlWriter writer) { writer.WriteStartElement("ConnectionSetup"); ConnectionSetup connectionSetup = configuration.ConnectionSetup; writer.WriteStartAttribute("serverName"); writer.WriteValue(connectionSetup.ServerName); writer.WriteEndAttribute(); writer.WriteStartAttribute("windowsAuthentication"); writer.WriteValue(connectionSetup.UseWindowsAuthentication); writer.WriteEndAttribute(); writer.WriteStartAttribute("userName"); writer.WriteValue(connectionSetup.UserName); writer.WriteEndAttribute(); writer.WriteStartAttribute("password"); writer.WriteValue(connectionSetup.Password); writer.WriteEndAttribute(); writer.WriteStartAttribute("timeout"); writer.WriteValue(connectionSetup.Timeout); writer.WriteEndAttribute(); writer.WriteEndElement(); }
public ImportConfiguration(TableMapping[] tableMappings, ConnectionSetup connectionSetup, string databaseName, ErrorHandling errorHandling) { this.tableMappings = tableMappings; this.connectionSetup = connectionSetup; this.databaseName = databaseName; this.errorHandling = errorHandling; }
static void Main(string[] args) { c = new Client(new ClientListener(), new StreamContainer()); c.AddAction(typeof(string), DoSomethingWithString); c.Connect(ConnectionSetup.CreateProtocolClient(Protocols.Tcp), "127.0.0.1", 4444, new BinaryReader()); while (true) { int k; Int32.TryParse(Console.ReadLine(), out k); switch (k) { case (0): { c.Connect(ConnectionSetup.CreateProtocolClient(Protocols.Tcp), "127.0.0.1", 4444, new BinaryReader()); break; } case (1): { c.Send("Data"); break; } } } }
/// <summary> /// 获取流程变量 /// </summary> /// <param name="sn">流程SN</param> /// <param name="FieldNames">要获取的变量的List</param> /// <returns>变量的List</returns> public static void GetProcessDataFields(string sn, string currentUser, CDataFields dataFields) { using (Connection conn = new Connection()) { try { ConnectionSetup conSetup = GetConnectionSetup(); conn.Open(conSetup); conn.ImpersonateUser(currentUser); WorklistItem listItem = conn.OpenWorklistItem(sn); GetDataFields(listItem, dataFields); } catch { throw; } finally { try { conn.RevertUser(); } catch { } if (conn != null) { conn.Close(); } } } }
public Connection GetWorkflowClientConnection() { if (_workflowClientConnection == null) { lock (_wfconnectionlock) { if (_workflowClientConnection == null) { _workflowClientConnection = new Connection(); try { var connectionSetup = new ConnectionSetup(); connectionSetup.ParseConnectionString(_workflowConnectionString); _workflowClientConnection.Open(connectionSetup); } catch (Exception ex) { if (_workflowClientConnection != null) { _workflowClientConnection.Dispose(); } throw new Exception("Failed to create Connection to K2.", ex); } } } } return _workflowClientConnection; }
public Client(ClientOptions options) { streams = new Streams.StreamController(); clientOptions = options; connection = ConnectionSetup.CreateProtocolClient(clientOptions.protocol); writer = SerializerContructor.CreateWriterSerializer(clientOptions.seralizer); reader = SerializerContructor.CreateReaderSerializer(clientOptions.seralizer); }
private void OpenConnection() { ConnectionSetup connectSetup = new ConnectionSetup(); connectSetup.ConnectionString = _connectionString; _cnn = new Connection(); _cnn.Open(connectSetup); }
private ImportConfiguration getConfig() { string hostName = @"UNKIE\SQLExpress"; string dbTestName = "BATEST"; ConnectionSetup connectionSetup = new ConnectionSetup(hostName, "", "", true); return(new ImportConfiguration(null, connectionSetup, dbTestName, null)); }
public void NonWindowsLoginTest() { ConnectionSetup connectionSetup = new ConnectionSetup(hostName, "TestUser", "TestPass", false); connectionSetup.Timeout = 1; SQLServerConnector conn = new SQLServerConnector(connectionSetup); Assert.IsNotEmpty(conn.GetDatabaseNames()); }
public void Setup() { var helper = new Mock <IHelper>(); helper.Setup(h => h.GetDBContext(It.IsAny <int>())) .Returns(new RemoteDbContext(ConnectionSetup.GetConnection())); ConnectionSetup.DeployDatabase(helper.Object); documentQueueRepository = new DocumentQueueRepository(helper.Object); }
public void DatabaseExistsTest() { ConnectionSetup connectionSetup = new ConnectionSetup(hostName, "", "", true); connectionSetup.Timeout = 1; SQLServerConnector conn = new SQLServerConnector(connectionSetup); Assert.Contains(dbTestName, conn.GetDatabaseNames().ToList()); }
public void TimeoutTest() { string hostNameDoesntExist = "testest"; ConnectionSetup connectionSetup = new ConnectionSetup(hostNameDoesntExist, "", "", true); connectionSetup.Timeout = 1; SQLServerConnector conn = new SQLServerConnector(connectionSetup); conn.GetDatabaseNames(); }
private static ConnectionSetup GetConnectionSetup() { ConnectionSetup conSetup = new ConnectionSetup(); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Host, GetConfigValue <string>("K2ServerName", "Localhost")); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.UserID, GetConfigValue <string>("K2User", "")); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Password, GetConfigValue <string>("K2Password", "")); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Port, "5252"); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Authenticate, "true"); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.WindowsDomain, GetConfigValue <string>("Domain", "Contoso")); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.IsPrimaryLogin, "true"); return(conSetup); }
private static ConnectionSetup GetConnectionSetup() { ConnectionSetup conSetup = new ConnectionSetup(); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Host, K2ServerName); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.UserID, K2User); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Password, Password); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Port, "5252"); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Authenticate, "true"); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.WindowsDomain, K2Domain); conSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.IsPrimaryLogin, "true"); return(conSetup); }
public WorkflowItem GetWorkflowItemBySN(string serialNumber, String impersonateUser) { // if the serial number is null or empty we do not want to do any of this if (!string.IsNullOrEmpty(serialNumber)) { using (var k2Connection = new Connection()) { ConnectionSetup k2Setup = new ConnectionSetup(); k2Setup.ConnectionString = Properties.Settings.Default.WorkflowServerConnectionString; k2Connection.Open(k2Setup); if (!String.IsNullOrEmpty(impersonateUser)) { k2Connection.ImpersonateUser(impersonateUser); } var workCriteria = new WorklistCriteria { NoData = false, Platform = "ASP" }; if (!string.IsNullOrEmpty(serialNumber)) { workCriteria.AddFilterField(WCField.SerialNumber, WCCompare.Equal, serialNumber); } Worklist k2Worklist = k2Connection.OpenWorklist(workCriteria); WorkflowItem retItem = null; foreach (WorklistItem item in k2Worklist) { retItem = new WorkflowItem(item); } // now that we have the workflow item get the count of the related documents if ((retItem != null) && (!string.IsNullOrEmpty(retItem.PolicyID))) { using (DocumentService.DocumentServiceClient client = new DocumentService.DocumentServiceClient()) { retItem.RelatedDocumentCount = client.GetDocumentsCountForPolicy(retItem.PolicyID); } } return(retItem); } } return(null); }
public void TimeoutTest() { string hostNameDoesntExist = "testest"; ConnectionSetup connectionSetup = new ConnectionSetup(hostNameDoesntExist, "", "", true); connectionSetup.Timeout = 1; ImportConfiguration config = new ImportConfiguration(null, connectionSetup, "", null); ImportStatement[] statements = new ImportStatement[0]; SQLServerDataImporter importer = new SQLServerDataImporter(config); importer.ImportData(statements); }
private static string ConnectionFactory(ConnectionSetup connectionSetup) { string connectionString; if (string.IsNullOrEmpty(connectionSetup.UserName)) { connectionString = $"mongodb://{connectionSetup.HostInfo}:{connectionSetup.Port}/?readPreference=primary&appname=postal.code.api&ssl=false"; } else { connectionString = $"mongodb+srv://{connectionSetup.UserName}:{connectionSetup.UserPws}@{connectionSetup.HostInfo}/{connectionSetup.DataBaseAuth}?retryWrites=true&w=majority"; } return(connectionString); }
public K2ConnectionStringBuilder(string userID) { ConnSetup = new ConnectionSetup(); SCConnectionStringBuilder connectionString = new SCConnectionStringBuilder(); connectionString.Authenticate = true; connectionString.Integrated = false; connectionString.IsPrimaryLogin = true; connectionString.EncryptedPassword = false; connectionString.Host = K2Environments.Host; connectionString.Port = K2Environments.Port; connectionString.SecurityLabelName = K2Environments.SecurityLabelName; connectionString.UserID = userID; connectionString.Password = "******"; ConnSetup.ConnectionString = connectionString.ToString(); }
/// <summary> /// 审批流程 /// </summary> /// <param name="sn">流程SN,必选</param> /// <param name="action">流程操作,为空则默认执行第0个操作</param> /// <param name="folio">流程编码,可选</param> /// <param name="dataFields">流程变量,必选</param> public static void ExecuteProcess(string sn, string action, string folio, string currentUser, CDataFields dataFields) { using (Connection conn = new Connection()) { try { ConnectionSetup conSetup = GetConnectionSetup(); conn.Open(conSetup); conn.RevertUser(); conn.ImpersonateUser(currentUser); SourceCode.Workflow.Client.WorklistItem listItem = conn.OpenWorklistItem(sn); SetDataFields(listItem, dataFields); if (!string.IsNullOrEmpty(folio)) { listItem.ProcessInstance.Folio = folio; } if (!string.IsNullOrEmpty(action)) { listItem.Actions[action].Execute(); } else { listItem.Actions[0].Execute(); } } catch { // TODO: throw? throw; } finally { try { conn.RevertUser(); } catch { } if (conn != null) { conn.Close(); } } } }
public K2Client(string identity) { this.ManagedUser = identity.FQNWithK2Label(); if (_connection == null) { var setup = new ConnectionSetup(); var setting = ConfigurationManager.ConnectionStrings["WorkflowServer"]; setup.ParseConnectionString(setting.ConnectionString); _connection = new Connection(); _connection.Open(setup); if (_connection.User == null || string.Compare(_connection.User.Name, ManagedUser, StringComparison.OrdinalIgnoreCase) != 0) { _connection.ImpersonateUser(ManagedUser); } } }
private ConnectionSetup readConnectionSetup(XmlReader reader) { ConnectionSetup connnectionSetup = null; if (reader.ReadToFollowing("ConnectionSetup")) { string serverName = reader.GetAttribute("serverName"); bool windowsAuthentication = bool.Parse(reader.GetAttribute("windowsAuthentication")); string userName = reader.GetAttribute("userName"); string password = reader.GetAttribute("password"); int timeout = int.Parse(reader.GetAttribute("timeout")); connnectionSetup = new ConnectionSetup(serverName, userName, password, windowsAuthentication, timeout); } return(connnectionSetup); }
public void TablesExistsTest() { ConnectionSetup connectionSetup = new ConnectionSetup(hostName, "", "", true); connectionSetup.Timeout = 1; SQLServerConnector conn = new SQLServerConnector(connectionSetup); Database db = conn.GetDatabase(dbTestName); string[] tableNames = db.Tables.Select(t => t.Name).ToArray(); Assert.AreEqual(4, db.Tables.Count); Assert.Contains("Address", tableNames); Assert.Contains("Person", tableNames); Assert.Contains("ContactInfo", tableNames); Assert.Contains("ContactInfoType", tableNames); }
public K2ConnectionStringBuilder(string userID) { ConnSetup = new ConnectionSetup(); SCConnectionStringBuilder connectionString = new SCConnectionStringBuilder(); connectionString.Authenticate = true; connectionString.Integrated = false; connectionString.IsPrimaryLogin = true; connectionString.EncryptedPassword = false; connectionString.Host = K2Environments.Host; connectionString.Port = K2Environments.Port; connectionString.SecurityLabelName = K2Environments.SecurityLabelName; connectionString.UserID = userID; connectionString.Password = "******"; ConnSetup.ConnectionString = connectionString.ToString(); }
public void ColumnsExistsTest() { ConnectionSetup connectionSetup = new ConnectionSetup(hostName, "", "", true); connectionSetup.Timeout = 1; SQLServerConnector conn = new SQLServerConnector(connectionSetup); Database db = conn.GetDatabase(dbTestName); DBTable personTable = db.Tables.Where(t => t.Name == "Person").First(); string[] columnNames = personTable.Columns.Select(c => c.Name).ToArray(); Assert.Contains("p_id", columnNames); Assert.Contains("FirstName", columnNames); Assert.Contains("LastName", columnNames); Assert.Contains("a_id", columnNames); }
public static void Delegate(string sn, string targetUser) { SourceCode.Workflow.Client.Connection con = new Connection(); try { ConnectionSetup conSetup = GetConnectionSetup(); con.Open(conSetup); con.ImpersonateUser(_CurrentUser); SourceCode.Workflow.Client.WorklistItem listItem = con.OpenWorklistItem(sn); listItem.Release(); Destination dest = new Destination(); dest.DestinationType = DestinationType.User; for (int i = 0; i < listItem.Actions.Count; i++) { dest.AllowedActions.Add(listItem.Actions[i].Name); } dest.Name = targetUser; listItem.Delegate(dest); DBManager.AddWorkListLog(_CurrentUser, targetUser, listItem.SerialNumber, listItem.ProcessInstance.ID, listItem.ActivityInstanceDestination.ID, "Delegate", _CurrentUser); } catch (Exception ex) { // TODO: throw? throw ex; } finally { try { con.RevertUser(); } catch { throw; } if (con != null) { con.Close(); } } }
public Worklist GetWorklistItems(String searchTerm, Int32 skip, Int32 take, Dictionary <WCField, WCSortOrder> sorts, String impersonateUser) { using (var k2Connection = new Connection()) { ConnectionSetup k2Setup = new ConnectionSetup(); k2Setup.ConnectionString = Properties.Settings.Default.WorkflowServerConnectionString; k2Connection.Open(k2Setup); if (!String.IsNullOrEmpty(impersonateUser)) { k2Connection.ImpersonateUser("K2:" + impersonateUser); } var workCriteria = new WorklistCriteria { NoData = true, Platform = "ASP" }; if (!string.IsNullOrEmpty(searchTerm)) { String searchTermFormat = String.Format("%{0}%", searchTerm); workCriteria.AddFilterField(WCLogical.StartBracket, WCField.None, WCCompare.Equal, null); // ( workCriteria.AddFilterField(WCField.ActivityName, WCCompare.Like, searchTermFormat); // ... workCriteria.AddFilterField(WCLogical.Or, WCField.EventName, WCCompare.Like, searchTermFormat); // OR ... workCriteria.AddFilterField(WCLogical.Or, WCField.ProcessFolio, WCCompare.Like, searchTermFormat); // OR ... workCriteria.AddFilterField(WCLogical.EndBracket, WCField.None, WCCompare.Equal, null); // ) } // No AND required - seems like bug - this bit gets put in a different bit of the query K2 creates. // Hide allocated items like the SharePoint K2 worlist does by default. workCriteria.AddFilterField(WCField.WorklistItemStatus, WCCompare.NotEqual, WorklistStatus.Allocated); workCriteria.StartIndex = skip; workCriteria.Count = take; foreach (KeyValuePair <WCField, WCSortOrder> sort in sorts) { workCriteria.AddSortField(sort.Key, sort.Value); } Worklist k2Worklist = k2Connection.OpenWorklist(workCriteria); return(k2Worklist); } }
internal DataTable GetWorklistItems(Dictionary <string, object> properties, Dictionary <string, object> parameters) { try { DataTable dt = GetResultTable(); WorklistCriteria criteria = GetWorklistCriteria(properties); ConnectionSetup cnnSetup = new ConnectionSetup(); cnnSetup.ConnectionString = this._execSettings.ConnectionString; using (Connection cnn = new Connection()) { cnn.Open(cnnSetup); if (this._execSettings.UseImpersonation) { cnn.ImpersonateUser(this._execSettings.ImpersonateUser); } Worklist worklist; if ((criteria != null) && (criteria.Filters.GetLength(0) > 0)) { worklist = cnn.OpenWorklist(criteria); } else { worklist = cnn.OpenWorklist(); } foreach (WorklistItem item in worklist) { DataRow row = dt.NewRow(); PopulateDataRow(item, row); dt.Rows.Add(row); } cnn.Close(); } return(dt); } catch (Exception ex) { throw ex; } }
/// <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 Worklist GetWorklistItems(String searchTerm, Int32 skip, Int32 take, Dictionary<WCField, WCSortOrder> sorts, String impersonateUser) { using (var k2Connection = new Connection()) { ConnectionSetup k2Setup = new ConnectionSetup(); k2Setup.ConnectionString = Properties.Settings.Default.WorkflowServerConnectionString; k2Connection.Open(k2Setup); if (!String.IsNullOrEmpty(impersonateUser)) k2Connection.ImpersonateUser("K2:" + impersonateUser); var workCriteria = new WorklistCriteria { NoData = true, Platform = "ASP" }; if (!string.IsNullOrEmpty(searchTerm)) { String searchTermFormat = String.Format("%{0}%", searchTerm); //String searchTermFormat = String.Format("% / % / % / % / %{0}%", searchTerm); workCriteria.AddFilterField(WCLogical.StartBracket, WCField.None, WCCompare.Equal, null); // ( workCriteria.AddFilterField(WCField.ActivityName, WCCompare.Like, searchTermFormat); // ... workCriteria.AddFilterField(WCLogical.Or, WCField.EventName, WCCompare.Like, searchTermFormat); // OR ... workCriteria.AddFilterField(WCLogical.Or, WCField.ProcessFolio, WCCompare.Like, searchTermFormat); // OR ... workCriteria.AddFilterField(WCLogical.EndBracket, WCField.None, WCCompare.Equal, null); // ) //workCriteria.AddFilterField(WCField.ProcessFolio, WCCompare.Like, searchTermFormat); } // No AND required - seems like bug - this bit gets put in a different bit of the query K2 creates. // Hide allocated items like the SharePoint K2 worlist does by default. workCriteria.AddFilterField(WCField.WorklistItemStatus, WCCompare.NotEqual, WorklistStatus.Allocated); workCriteria.StartIndex = skip; workCriteria.Count = take; foreach (KeyValuePair<WCField,WCSortOrder> sort in sorts) { workCriteria.AddSortField(sort.Key, sort.Value); } Worklist k2Worklist = k2Connection.OpenWorklist(workCriteria); return k2Worklist; } }
internal DataTable GetWorklistItems(Dictionary<string, object> properties, Dictionary<string, object> parameters) { try { DataTable dt = GetResultTable(); WorklistCriteria criteria = GetWorklistCriteria(properties); ConnectionSetup cnnSetup = new ConnectionSetup(); cnnSetup.ConnectionString = this._execSettings.ConnectionString; using (Connection cnn = new Connection()) { cnn.Open(cnnSetup); if (this._execSettings.UseImpersonation) cnn.ImpersonateUser(this._execSettings.ImpersonateUser); Worklist worklist; if ((criteria != null) && (criteria.Filters.GetLength(0) > 0)) worklist = cnn.OpenWorklist(criteria); else worklist = cnn.OpenWorklist(); foreach (WorklistItem item in worklist) { DataRow row = dt.NewRow(); PopulateDataRow(item, row); dt.Rows.Add(row); } cnn.Close(); } return dt; } catch (Exception ex) { throw ex; } }
public void InitConn(ServiceContext context, string serverName) { InitConfigValue(context); this.k2conn = new Connection(); ConnectionSetup k2ConSetup = new ConnectionSetup(); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Host, serverName); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.UserID, k2User); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Password, k2PassWord); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Port, clientPort); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Authenticate, "true"); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.IsPrimaryLogin, "true"); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.SecurityLabelName, label); //k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.TimeOut, _timeoutNum); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.WindowsDomain, domain); if (label.ToLower() != "k2") k2ConSetup.ConnectionParameters[ConnectionSetup.ParamKeys.Integrated] = "false"; this.k2conn.Open(serverName, k2ConSetup.ConnectionString); this.TimeOfInit = DateTime.Now; this.K2ServerName += serverName + "[" + this.TimeOfInit.ToString("HH:mm:ss") + "],"; }
/// <summary> /// 查找可用server /// </summary> public void findAvailableServer() { for (int i = 0; i < serverNames.Length; i++) { this.currentServerIndex = i; ConnectionSetup k2ConSetup = new ConnectionSetup(); var serverName = this.serverNames[this.currentServerIndex]; k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Host, serverName); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.UserID, k2User); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Password, k2PassWord); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Port, clientPort); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Authenticate, "true"); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.IsPrimaryLogin, "true"); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.SecurityLabelName, label); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.WindowsDomain, domain); if (label.ToLower() != "k2") k2ConSetup.ConnectionParameters[ConnectionSetup.ParamKeys.Integrated] = "false"; Connection k2conn = new Connection(); try { k2conn.Open(serverName, k2ConSetup.ConnectionString); break; } catch (Exception e) { K2PoolLogger.logError("K2ConnnectionPool.findAvailableServer():" + e.Message + "\r\n" + e.StackTrace); } finally { try { k2conn.Close(); } catch (Exception) { } } } K2ServerProvider.availableServerName = this.serverNames[this.currentServerIndex]; }
public List<WorkflowItem> GetWorkflowItems(String searchTerm, Int32 skip, Int32 take, Dictionary<WCField, WCSortOrder> sorts, String impersonateUser, out Int32 count, out Int32 totalCount, List<Tuple<String, String, String>> extraFilters) { Tuple<String, String, String> cobEF = null; Tuple<String, String, String> yearEF = null; Tuple<String, String, String> descEF = null; Tuple<String, String, String> insdEF = null; Tuple<String, String, String> bkrEF = null; Tuple<String, String, String> uwrEF = null; Tuple<String, String, String> actEF = null; if (extraFilters != null) { cobEF = extraFilters.FirstOrDefault(f => f.Item1 == "COBId"); yearEF = extraFilters.FirstOrDefault(f => f.Item1 == "AccountYear"); descEF = extraFilters.FirstOrDefault(f => f.Item1 == "Description"); insdEF = extraFilters.FirstOrDefault(f => f.Item1 == "InsuredName"); bkrEF = extraFilters.FirstOrDefault(f => f.Item1 == "BrokerPseudonym"); uwrEF = extraFilters.FirstOrDefault(f => f.Item1 == "UnderwriterCode"); actEF = extraFilters.FirstOrDefault(f => f.Item1 == "Activity"); } String cobExtraFilter = cobEF == null ? String.Empty : cobEF.Item3; Int32 yearParse; Int32? yearExtraFilter = null; if (Int32.TryParse(yearEF == null ? String.Empty : yearEF.Item3, out yearParse)) yearExtraFilter = yearParse; String descExtraFilter = descEF == null ? String.Empty : descEF.Item3; String insdExtraFilter = insdEF == null ? String.Empty : insdEF.Item3; String bkrExtraFilter = bkrEF == null ? String.Empty : bkrEF.Item3; String uwrExtraFilter = uwrEF == null ? String.Empty : uwrEF.Item3; String actExtraFilter = actEF == null ? String.Empty : actEF.Item3; List<WorkflowItem> retArray = new List<WorkflowItem>(); using (var k2Connection = new Connection()) { ConnectionSetup k2Setup = new ConnectionSetup(); k2Setup.ConnectionString = Properties.Settings.Default.WorkflowServerConnectionString; k2Connection.Open(k2Setup); if (!String.IsNullOrEmpty(impersonateUser)) k2Connection.ImpersonateUser(impersonateUser); var workCriteria = new WorklistCriteria { NoData = true, Platform = "ASP" }; //String propertyFilter = String.Format("% / {0} / {1} / % / %{2}%", uwrExtraFilter, searchTerm); String propertyFilter = String.Format("% / {0} / {1}%{2} / % / {3}", String.IsNullOrEmpty(uwrExtraFilter) ? "%" : uwrExtraFilter, cobExtraFilter, yearExtraFilter == null ? String.Empty : yearExtraFilter.ToString().Substring(2), String.IsNullOrEmpty(insdExtraFilter) ? "%" : "%" + insdExtraFilter + "%"); if (!string.IsNullOrEmpty(searchTerm)) { String searchTermFormat = String.Format("%{0}%", searchTerm); //if (extraFilters.Count > 0) workCriteria.AddFilterField(WCLogical.StartBracket, WCField.None, WCCompare.Equal, null); // ( workCriteria.AddFilterField(WCLogical.StartBracket, WCField.None, WCCompare.Equal, null); // ( workCriteria.AddFilterField(WCField.ActivityName, WCCompare.Like, searchTermFormat); // ... workCriteria.AddFilterField(WCLogical.Or, WCField.ProcessData, "BPC", WCCompare.Equal, searchTerm); // OR ... workCriteria.AddFilterField(WCLogical.Or, WCField.EventName, WCCompare.Like, searchTermFormat); // OR ... workCriteria.AddFilterField(WCLogical.Or, WCField.ProcessFolio, WCCompare.Like, searchTermFormat); // OR ... workCriteria.AddFilterField(WCLogical.EndBracket, WCField.None, WCCompare.Equal, null); // ) if (extraFilters.Count > 0) { workCriteria.AddFilterField(WCLogical.And, WCField.None, WCCompare.Equal, null); // AND workCriteria.AddFilterField(WCLogical.StartBracket, WCField.None, WCCompare.Equal, null); // ( workCriteria.AddFilterField(WCField.ProcessFolio, WCCompare.Like, propertyFilter); // ... workCriteria.AddFilterField(WCLogical.EndBracket, WCField.None, WCCompare.Equal, null); // ) } if (!String.IsNullOrEmpty(actExtraFilter)) // TODO: OR event name? //workCriteria.AddFilterField(WCField.EventName, WCCompare.Equal, actExtraFilter); // ... workCriteria.AddFilterField(WCLogical.And, WCField.ActivityName, WCCompare.Equal, actExtraFilter); // ... //if (extraFilters.Count > 0) workCriteria.AddFilterField(WCLogical.EndBracket, WCField.None, WCCompare.Equal, null); // ) //workCriteria.AddFilterField(WCField., WCField.None, WCCompare.Equal, null); } else { if (extraFilters.Count > 0) { workCriteria.AddFilterField(WCField.ProcessFolio, WCCompare.Like, propertyFilter); } if (!String.IsNullOrEmpty(actExtraFilter)) workCriteria.AddFilterField(WCLogical.And, WCField.ActivityName, WCCompare.Equal , actExtraFilter); // ... } // No AND required - seems like bug - this bit gets put in a different bit of the query K2 creates. // Hide allocated items like the SharePoint K2 worlist does by default. // workCriteria.AddFilterField(WCField.WorklistItemStatus, WCCompare.NotEqual, WorklistStatus.Allocated); //workCriteria.AddSortField(WCField.ActivityStartDate, WCSortOrder.Descending); workCriteria.StartIndex = skip; workCriteria.Count = take; foreach (KeyValuePair<WCField, WCSortOrder> sort in sorts) { workCriteria.AddSortField(sort.Key, sort.Value); } Worklist k2Worklist = k2Connection.OpenWorklist(workCriteria); foreach (WorklistItem item in k2Worklist) { retArray.Add(new WorkflowItem(item)); } count = k2Worklist.TotalCount; // Total records before filter totalCount = k2Worklist.TotalCount; return retArray; } }
public WorkflowItem GetWorkflowItemBySN(string serialNumber, String impersonateUser) { using (var k2Connection = new Connection()) { ConnectionSetup k2Setup = new ConnectionSetup(); k2Setup.ConnectionString = Properties.Settings.Default.WorkflowServerConnectionString; k2Connection.Open(k2Setup); if (!String.IsNullOrEmpty(impersonateUser)) k2Connection.ImpersonateUser(impersonateUser); var workCriteria = new WorklistCriteria { NoData = true, Platform = "ASP" }; if (!string.IsNullOrEmpty(serialNumber)) { workCriteria.AddFilterField(WCField.SerialNumber, WCCompare.Equal, serialNumber); } Worklist k2Worklist = k2Connection.OpenWorklist(workCriteria); WorkflowItem retItem = null; foreach (WorklistItem item in k2Worklist) { retItem = new WorkflowItem(item); } // now that we have the workflow item get the count of the related documents if ((retItem!=null)&&(!string.IsNullOrEmpty(retItem.PolicyID))) { using (DocumentService.DocumentServiceClient client = new DocumentService.DocumentServiceClient()) { retItem.RelatedDocumentCount = client.GetDocumentsCountForPolicy(retItem.PolicyID); } } return retItem; } }
public WorklistItem GetWorklistItemBySN(string serialNumber, String impersonateUser) { using (var k2Connection = new Connection()) { ConnectionSetup k2Setup = new ConnectionSetup(); k2Setup.ConnectionString = Properties.Settings.Default.WorkflowServerConnectionString; k2Connection.Open(k2Setup); if (!String.IsNullOrEmpty(impersonateUser)) k2Connection.ImpersonateUser(impersonateUser); return k2Connection.OpenWorklistItem(serialNumber); } }
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; } }
private void OpenConnection() { ConnectionSetup connectSetup = new ConnectionSetup(); connectSetup.ConnectionString = _connectionString; _cnn = new Connection(); _cnn.Open(connectSetup); }
public WorklistItem GetWorklistItemBySN(string serialNumber, String impersonateUser) { // if the serial number is null or empty we do not want to do any of this if (!string.IsNullOrEmpty(serialNumber)) { using (var k2Connection = new Connection()) { ConnectionSetup k2Setup = new ConnectionSetup(); k2Setup.ConnectionString = Properties.Settings.Default.WorkflowServerConnectionString; k2Connection.Open(k2Setup); if (!String.IsNullOrEmpty(impersonateUser)) k2Connection.ImpersonateUser(impersonateUser); return k2Connection.OpenWorklistItem(serialNumber); } } return null; }
internal DataTable LoadWorklistItem(string serialNumber) { ConnectionSetup connectSetup = new ConnectionSetup(); connectSetup.ConnectionString = _connectionString; Connection cnn = new Connection(); DataTable dt = GetResultTable(); try { cnn.Open(connectSetup); WorklistItem item = cnn.OpenWorklistItem(serialNumber); DataRow row = dt.NewRow(); row["AllocatedUser"] = item.AllocatedUser; row["Data"] = item.Data; row["ID"] = item.ID; row["Link"] = "<hyperlink><link>" + HttpUtility.HtmlEncode(item.Data) + "</link><display>Open</display></hyperlink>"; row["SerialNumber"] = item.SerialNumber; row["Status"] = item.Status; row["ActivityID"] = item.ActivityInstanceDestination.ActID; row["ActivityInstanceID"] = item.ActivityInstanceDestination.ActInstID; row["ActivityName"] = item.ActivityInstanceDestination.Name; row["Priority"] = item.ActivityInstanceDestination.Priority; row["StartDate"] = item.EventInstance.StartDate; row["ActivityInstanceDestinationID"] = item.ActivityInstanceDestination.ID; row["ProcessInstanceID"] = item.ProcessInstance.ID; row["ProcessFullName"] = item.ProcessInstance.FullName; row["ProcessName"] = item.ProcessInstance.Name; row["Folio"] = item.ProcessInstance.Folio; row["EventInstanceName"] = item.EventInstance.Name; dt.Rows.Add(row); return dt; } catch (Exception ex) { throw ex; } finally { cnn.Close(); cnn.Dispose(); } }
public async Task<GetUserWorkflowItemsDto> GetWorkflowItemsAsync(String searchTerm, Int32 skip, Int32 take, Dictionary<WCField, WCSortOrder> sorts, String impersonateUser, List<Tuple<String, String, String>> extraFilters) { Tuple<String, String, String> cobEF = null; Tuple<String, String, String> yearEF = null; Tuple<String, String, String> insdEF = null; Tuple<String, String, String> uwrEF = null; Tuple<String, String, String> actEF = null; if (extraFilters != null) { cobEF = extraFilters.FirstOrDefault(f => f.Item1 == "COBId"); yearEF = extraFilters.FirstOrDefault(f => f.Item1 == "AccountYear"); insdEF = extraFilters.FirstOrDefault(f => f.Item1 == "InsuredName"); uwrEF = extraFilters.FirstOrDefault(f => f.Item1 == "UnderwriterCode"); actEF = extraFilters.FirstOrDefault(f => f.Item1 == "Activity"); } String cobExtraFilter = cobEF == null ? String.Empty : cobEF.Item3; Int32 yearParse; Int32? yearExtraFilter = null; if (Int32.TryParse(yearEF == null ? String.Empty : yearEF.Item3, out yearParse)) yearExtraFilter = yearParse; String insdExtraFilter = insdEF == null ? String.Empty : insdEF.Item3; String uwrExtraFilter = uwrEF == null ? String.Empty : uwrEF.Item3; String actExtraFilter = actEF == null ? String.Empty : actEF.Item3; List<WorkflowItem> retArray = new List<WorkflowItem>(); using (var k2Connection = new Connection()) { ConnectionSetup k2Setup = new ConnectionSetup(); k2Setup.ConnectionString = Properties.Settings.Default.WorkflowServerConnectionString; k2Connection.Open(k2Setup); if (!String.IsNullOrEmpty(impersonateUser)) k2Connection.ImpersonateUser(impersonateUser); var workCriteria = new WorklistCriteria { NoData = true, Platform = "ASP" }; String propertyFilter = String.Format("% / {0} / {1}%{2} / % / {3}", String.IsNullOrEmpty(uwrExtraFilter) ? "%" : uwrExtraFilter, cobExtraFilter, yearExtraFilter == null ? String.Empty : yearExtraFilter.ToString().Substring(2), String.IsNullOrEmpty(insdExtraFilter) ? "%" : "%" + insdExtraFilter + "%"); if (!string.IsNullOrEmpty(searchTerm)) { String searchTermFormat = String.Format("%{0}%", searchTerm); //if (extraFilters.Count > 0) workCriteria.AddFilterField(WCLogical.StartBracket, WCField.None, WCCompare.Equal, null); // ( workCriteria.AddFilterField(WCLogical.StartBracket, WCField.None, WCCompare.Equal, null); // ( workCriteria.AddFilterField(WCField.ActivityName, WCCompare.Like, searchTermFormat); // ... workCriteria.AddFilterField(WCLogical.Or, WCField.ProcessData, "BPC", WCCompare.Equal, searchTerm); // OR ... workCriteria.AddFilterField(WCLogical.Or, WCField.EventName, WCCompare.Like, searchTermFormat); // OR ... workCriteria.AddFilterField(WCLogical.Or, WCField.ProcessFolio, WCCompare.Like, searchTermFormat); // OR ... workCriteria.AddFilterField(WCLogical.EndBracket, WCField.None, WCCompare.Equal, null); // ) if (extraFilters != null && extraFilters.Count > 0) { workCriteria.AddFilterField(WCLogical.And, WCField.None, WCCompare.Equal, null); // AND workCriteria.AddFilterField(WCLogical.StartBracket, WCField.None, WCCompare.Equal, null); // ( workCriteria.AddFilterField(WCField.ProcessFolio, WCCompare.Like, propertyFilter); // ... workCriteria.AddFilterField(WCLogical.EndBracket, WCField.None, WCCompare.Equal, null); // ) } if (!String.IsNullOrEmpty(actExtraFilter)) // TODO: OR event name? //workCriteria.AddFilterField(WCField.EventName, WCCompare.Equal, actExtraFilter); // ... workCriteria.AddFilterField(WCLogical.And, WCField.ActivityName, WCCompare.Equal, actExtraFilter); // ... workCriteria.AddFilterField(WCLogical.EndBracket, WCField.None, WCCompare.Equal, null); // ) } else { if (extraFilters != null && extraFilters.Count > 0) { workCriteria.AddFilterField(WCField.ProcessFolio, WCCompare.Like, propertyFilter); } if (!String.IsNullOrEmpty(actExtraFilter)) workCriteria.AddFilterField(WCLogical.And, WCField.ActivityName, WCCompare.Equal, actExtraFilter); // ... } // No AND required - seems like bug - this bit gets put in a different bit of the query K2 creates. // Hide allocated items like the SharePoint K2 worlist does by default. // workCriteria.AddFilterField(WCField.WorklistItemStatus, WCCompare.NotEqual, WorklistStatus.Allocated); workCriteria.StartIndex = skip; workCriteria.Count = take; foreach (KeyValuePair<WCField, WCSortOrder> sort in sorts) { workCriteria.AddSortField(sort.Key, sort.Value); } var dto = new GetUserWorkflowItemsDto(); var task = new Task<GetUserWorkflowItemsDto> ( () => { var k2Worklist = k2Connection.OpenWorklist(workCriteria); retArray.AddRange(from WorklistItem item in k2Worklist select new WorkflowItem(item)); dto.WorkflowItemsArray = retArray.ToArray(); dto.TotalDisplayRecords = k2Worklist.TotalCount; dto.TotalRecords = k2Worklist.TotalCount; return dto; } ); // Start the task task.Start(); // Get the result from the task - analogous to // calling task.Result (without the thread blocking) var result = await task; return result; } }
public DataTable GetWorklistItems(Dictionary<string, object> properties, Dictionary<string, object> parameters) { bool impersonate = false; string impersonateUser = ""; ConnectionSetup connectSetup = new ConnectionSetup(); connectSetup.ConnectionString = _connectionString; if (properties.ContainsKey("UserName")) { if (!(string.IsNullOrEmpty(properties["UserName"].ToString()))) { connectSetup.ConnectionString = _connectionstringImpersonate; impersonateUser = properties["UserName"].ToString(); impersonate = true; } else connectSetup.ConnectionString = _connectionString; } WorklistCriteria criteria = null; if (properties.Count > 0) criteria = GetWorklistCriteria(properties); Connection cnn = new Connection(); try { cnn.Open(connectSetup); if (impersonate) cnn.ImpersonateUser(impersonateUser); DataTable dt = GetResultTable(); Worklist worklist; if ((criteria != null) && (criteria.Filters.GetLength(0) > 0)) worklist = cnn.OpenWorklist(criteria); else worklist = cnn.OpenWorklist(); foreach (WorklistItem item in worklist) { DataRow row = dt.NewRow(); row["AllocatedUser"] = item.AllocatedUser; row["Data"] = item.Data; row["ID"] = item.ID; row["Link"] = "<hyperlink><link>" + HttpUtility.HtmlEncode(item.Data) + "</link><display>Open</display></hyperlink>"; row["SerialNumber"] = item.SerialNumber; row["Status"] = item.Status; row["ActivityID"] = item.ActivityInstanceDestination.ActID; row["ActivityInstanceID"] = item.ActivityInstanceDestination.ActInstID; row["ActivityName"] = item.ActivityInstanceDestination.Name; row["Priority"] = item.ActivityInstanceDestination.Priority; row["StartDate"] = item.EventInstance.StartDate; row["ActivityInstanceDestinationID"] = item.ActivityInstanceDestination.ID; row["ProcessInstanceID"] = item.ProcessInstance.ID; row["ProcessFullName"] = item.ProcessInstance.FullName; row["ProcessName"] = item.ProcessInstance.Name; row["Folio"] = item.ProcessInstance.Folio; row["EventInstanceName"] = item.EventInstance.Name; dt.Rows.Add(row); } if (impersonate) cnn.RevertUser(); cnn.Close(); cnn.Dispose(); return dt; } catch (Exception ex) { throw ex; } }
//public K2ConnWrap() //{ // this.k2conn = new Connection(); // try // { // ConnectionSetup k2ConSetup = new ConnectionSetup(); // k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Host, k2Servers.getServerName()); // k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.UserID, k2User); // k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Password, k2PassWord); // k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Port, "5252"); // k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Authenticate, "true"); // k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.WindowsDomain, domain); // k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.IsPrimaryLogin, "true"); // //k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.TimeOut, _timeoutNum); // this.k2conn.Open(k2ConSetup); // this.status = 0; // } // catch (Exception e) // { // K2PoolLogger.logError("K2ConnnectionPool.K2ConnWrap():" + e.Message + "\r\n" + e.StackTrace); // throw e; // } // //this._connTime = DateTime.Now; //} public void ReTryConn(ServiceContext context) { this.k2Servers = new K2ServerProvider(context); try { this.k2conn.Close(); } catch (Exception) { } this.k2conn = new Connection(); try { ConnectionSetup k2ConSetup = new ConnectionSetup(); this.k2Servers.findAvailableServer(); string serverName = this.k2Servers.getServerName(); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Host, serverName); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.UserID, k2User); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Password, k2PassWord); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Port, clientPort); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.Authenticate, "true"); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.IsPrimaryLogin, "true"); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.SecurityLabelName, label); //k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.TimeOut, _timeoutNum); k2ConSetup.ConnectionParameters.Add(ConnectionSetup.ParamKeys.WindowsDomain, domain); if (label.ToLower() != "k2") k2ConSetup.ConnectionParameters[ConnectionSetup.ParamKeys.Integrated] = "false"; this.k2conn.Open(serverName, k2ConSetup.ConnectionString); this.K2ServerName += "Retry:" + serverName + "[" + DateTime.Now.ToString("HH:mm") + "],"; } catch (Exception e) { K2PoolLogger.logError("K2ConnnectionPool.ReTryConn():" + e.Message + "\r\n" + e.StackTrace); throw e; } //this.status = 0; //this._connTime = DateTime.Now; }
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. } }
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 } } } }
internal DataTable LoadWorklistItem(string serialNumber) { if (string.IsNullOrEmpty(serialNumber)) throw new ArgumentException("Value must not be null or empty.", "serialNumer"); try { DataTable dt = GetResultTable(); DataRow row = dt.NewRow(); ConnectionSetup cnnSetup = new ConnectionSetup(); cnnSetup.ConnectionString = this._execSettings.ConnectionString; using (Connection cnn = new Connection()) { cnn.Open(cnnSetup); if (this._execSettings.UseImpersonation) cnn.ImpersonateUser(this._execSettings.ImpersonateUser); WorklistItem item = cnn.OpenWorklistItem(serialNumber); if (item != null) { PopulateDataRow(item, row); dt.Rows.Add(row); } cnn.Close(); } return dt; } catch (Exception ex) { throw ex; } }
/// <summary> /// 设置K2的参数 /// pcithpx 20110728 [k2Init2] /// </summary> /// <param name="k2ConSetup">K2连接参数对象</param> /// <param name="key">键</param> /// <param name="value">值</param> private static void SetK2Param(ConnectionSetup k2ConSetup, string key, string value) { if (k2ConSetup.ConnectionParameters.ContainsKey(key)) { k2ConSetup.ConnectionParameters[key] = value; } else { k2ConSetup.ConnectionParameters.Add(key, value); } }
/// <summary> /// 连接池无空闲连接,获取新的连接 /// </summary> /// <returns></returns> private static Connection GetNewK2Conn(ServiceContext context) { InitConfigValue(context); Connection k2conn = new Connection(); ConnectionSetup k2ConSetup = new ConnectionSetup(); try { SetK2Param(k2ConSetup, ConnectionSetup.ParamKeys.Host, K2ServerProvider.AvailableServerName); SetK2Param(k2ConSetup, ConnectionSetup.ParamKeys.UserID, k2User); SetK2Param(k2ConSetup, ConnectionSetup.ParamKeys.Password, k2PassWord); SetK2Param(k2ConSetup, ConnectionSetup.ParamKeys.Port, clientPort); SetK2Param(k2ConSetup, ConnectionSetup.ParamKeys.Authenticate, "true"); SetK2Param(k2ConSetup, ConnectionSetup.ParamKeys.IsPrimaryLogin, "true"); SetK2Param(k2ConSetup, ConnectionSetup.ParamKeys.SecurityLabelName, label); SetK2Param(k2ConSetup, ConnectionSetup.ParamKeys.WindowsDomain, domain); if (label.ToLower() != "k2") SetK2Param(k2ConSetup, ConnectionSetup.ParamKeys.Integrated, "false"); k2conn.Open(K2ServerProvider.AvailableServerName, k2ConSetup.ConnectionString); lock (oLock) { noPoolConnCount++; } } catch (Exception ex) { K2PoolLogger.logError("得到新连接时出错K2ConnnectionPool.GetNewK2Conn(), \r\n " + "K2ServerProvider.AvailableServerName = " + K2ServerProvider.AvailableServerName + ", \r\n" + "ex.Messagee = " + ex.Message + "\r\n" + "ex.StackTrace = " + ex.StackTrace); //2012-2-14 pcitljw //得到新连接出错时 重新查找别的主机建立连接 K2ConnWrap wrap = new K2ConnWrap(); wrap.K2Conn = k2conn; wrap.ReTryConn(context); k2conn = wrap.K2Conn; //throw; } return k2conn; }