-
Notifications
You must be signed in to change notification settings - Fork 0
/
CIU - 110.cs
422 lines (363 loc) · 21.3 KB
/
CIU - 110.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
using System;
using System.Text;
using System.Collections.Generic;
using System.Data;
using System.Data.Odbc;
using Hyland.Unity;
namespace UnityScripts
{
/// <summary>
/// Assigns the appropriate Processing Unit and Load Balanced User to App Processing queues
/// 1. Gets Trans Code and License Type from Application document type
/// 2. Perform lookup to SQL DB for user assignment and Processing Unit and assign as keywords
/// REMOVED 3. Update last_user and last_assigned with last assigned user / datetime (load balance)
/// 3. (11/23/2010-TT) Unknown change time, but script actually does a "least # documents assigned across
/// lifecycle" assignment - see getNextUser() function
/// (11/23/2010-TT) Modified the "getNextUser()" function's SQL call to better reflect actual workload of users
/// </summary>
public class DBPR_UnityScript_110 : IWorkflowScript
{
#region User-Configurable Script Settings
// Script name for diagnostics logging
private const string ScriptName = "110 CIU-RULE-Assign App Proc Load Balance User from DB";
// Diagnostics logging level - set to Verbose for testing, Error for production
private const Diagnostics.DiagnosticsLevel DiagLevel = Diagnostics.DiagnosticsLevel.Verbose;
// Workflow property where error message will be stored
private const string ErrorMessageProperty = "UnityError";
// If true, errors will be added to document history
private const bool WriteErrorsToHistory = true;
// Date/Time format for diagnostics logging
private const string DateTimeFormat = "MM-dd-yyyy HH:mm:ss.fff";
private const string gParamLicType = "License Type"; // Key Number 104
private const string gParamTranCode = "Tran Code"; // Key Number 106
private const string gSaveToAssignedProcUnit = "Assigned Processing Unit";
private const string gSaveToAssignedProc = "Assigned Processor";
private const string gLCNUM = "102";
private const string gLCNUM2 = "319";
private StringBuilder strSql = new StringBuilder();
#endregion
/***********************************************
* USER/SE: PLEASE DO NOT EDIT BELOW THIS LINE *
***********************************************/
#region Private Globals
// Active workflow document
private Document _currentDocument;
#endregion
#region IWorkflowScript
/// <summary>
/// Implementation of <see cref="IWorkflowScript.OnWorkflowScriptExecute" />.
/// <seealso cref="IWorkflowScript" />
/// This script assigns the appropriate Processing Unit and Load Balanced User to App Processing queues
/// 1. Gets Trans Code and License Type from Application document type
/// 2. Perform lookup to SQL DB for user assignment and Processing Unit and assign as keywords
/// REMOVED 3. Update last_user and last_assigned with last assigned user / datetime (load balance)
/// 3. (11/23/2010-TT) Unknown change time, but script actually does a
/// "least # documents assigned across lifecycle" assignment - see getNextUser() function
/// (11/23/2010-TT) Modified the "getNextUser()" function's SQL call to better reflect actual workload of users
/// </summary>
/// <param name="app">Unity Application object</param>
/// <param name="args">Workflow event arguments</param>
public void OnWorkflowScriptExecute(Application app, WorkflowEventArgs args)
// public void OnWorkflowScriptExecute(Application app, WorkflowEventArgs args=null)
{
try
{
// Initialize global settings
IntializeScript(ref app, ref args);
KeywordType ktwTranCode = _currentDocument.DocumentType.KeywordRecordTypes.FindKeywordType(gParamTranCode);
string strTranCode = "";
if (ktwTranCode != null)
{
KeywordRecord keyRecTranCode = _currentDocument.KeywordRecords.Find(ktwTranCode);
if (keyRecTranCode != null)
{
Keyword kwdTranCode = keyRecTranCode.Keywords.Find(ktwTranCode);
if (kwdTranCode != null)
strTranCode = kwdTranCode.ToString();
}
}
KeywordType ktwLicType = _currentDocument.DocumentType.KeywordRecordTypes.FindKeywordType(gParamLicType);
string strLicType = "";
if (ktwLicType != null)
{
KeywordRecord keyRecLicType = _currentDocument.KeywordRecords.Find(ktwLicType);
if (keyRecLicType != null)
{
Keyword kwdLicType = keyRecLicType.Keywords.Find(ktwLicType);
if (kwdLicType != null)
strLicType = kwdLicType.ToString();
}
}
if (strLicType == "" || strTranCode == "")
{
throw new Exception(string.Format("{0} or {1} is blank.", gParamLicType, gParamTranCode));
}
//access Config Item for OnBase User
string gUSER = "";
if (app.Configuration.TryGetValue("OnBaseUser", out gUSER))
{
}
//access Config Item for OnBase Password
string gPASS = "";
if (app.Configuration.TryGetValue("OnBasePassword", out gPASS))
{
}
/* COMMENT THIS SECTION OUT WHEN MOVING TO PROD */
//access Config Item for OnBase UAT ODBC
string gODBCMISC = "";
if (app.Configuration.TryGetValue("CIUOnbaseMISC", out gODBCMISC))
{
}
string gODBCOnBase = "";
if (app.Configuration.TryGetValue("OnBaseUAT", out gODBCOnBase))
{
}
/* UNCOMMENT THIS SECTION WHEN MOVING TO PROD
//access Config Item for OnBase PROD ODBC
string gODBCOnBase = "";
if (app.Configuration.TryGetValue("OnBasePROD", out gODBCOnBase))
{
}
*/
// **************
// Get Routing Values - This query gets the Proc Unit, Users and LastUser from SQL
strSql.Append(@"SELECT users AS USER, proc_unit AS UNIT ");
strSql.Append(@" FROM dbo.tbl_ccb ");
strSql.Append(@" WHERE license_type = '");
strSql.Append(strLicType);
strSql.Append(@"' AND tran_code = '");
strSql.Append(strTranCode);
strSql.Append(@"'");
string connectionString = string.Format("DSN={0};Uid={1};Pwd={2};", gODBCMISC, gUSER, gPASS);
app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("Sql Query: {0}", strSql.ToString()));
using (OdbcConnection con = new OdbcConnection(connectionString))
{
try
{
con.Open();
using (OdbcCommand command = new OdbcCommand(strSql, con))
using (OdbcDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
string strUnit = "";
List<string> lstUser = new List<string>();
lstUser.Add(reader["USER"].ToString());
strUnit = reader["UNIT"].ToString();
string strSQLUsers = "";
foreach (string result in lstUser)
{
if (result != "" && strSQLUsers == "")
{
strSQLUsers = "'" + strSQLUsers + result + "'";
}
else if (result != "" && strSQLUsers != "")
{
strSQLUsers = strSQLUsers + ",'" + result + "'";
}
}
strSql.Append(@"select CT1.username, sum(CT1.DocCount) as DocCount from ((select ua.username, count(ilcu.usernum) as DocCount ");
strSql.Append(@" from hsi.useraccount ua left outer join (select usernum,itemnum from hsi.itemlcxuser where hsi.itemlcxuser.lcnum= ");
strSql.Append(gLCNUM);
strSql.Append(@" or hsi.itemlcxuser.lcnum=");
strSql.Append(gLCNUM2);
strSql.Append(@" ) ilcu on ua.usernum = ilcu.usernum inner join hsi.itemlc il on il.itemnum = ilcu.itemnum ");
strSql.Append(@" inner join hsi.itemdata id on ilcu.itemnum = id.itemnum inner join hsi.lcstate lcs on il.statenum = lcs.statenum where ua.username in( ");
strSql.Append(strSQLUsers);
strSql.Append(@") and id.status=0 and (lcs.statename like 'CIU-Application Processing%' or lcs.statename like 'DDC - Application Processing%')");
strSql.Append(@" and lcs.statename not like 'CIU-Application Processing Routing Exceptions' and lcs.statename not like 'DDC - Application Processing Routing Exceptions' ");
strSql.Append(@" and lcs.statename not like 'DDC - Application Processing - Pending Info' group by ua.username ) UNION ( select ua.username, 0 as DocCount from hsi.useraccount ua where ua.username in ( ");
strSql.Append(strSQLUsers);
strSql.Append(@") ) ) CT1 group by CT1.username order by DocCount asc");
app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("2nd Sql Query: {0}", strSql.ToString()));
string connectionStringOnBase = string.Format("DSN={0};Uid={1};Pwd={2};", gODBCOnBase, gUSER, gPASS);
app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("Connection string: {0}", connectionStringOnBase));
string strNextUser = "";
using (OdbcConnection conOnBase = new OdbcConnection(connectionStringOnBase))
{
try
{
conOnBase.Open();
using (OdbcCommand command = new OdbcCommand(strSql, conOnBase))
using (OdbcDataReader readerOnBase = command.ExecuteReader())
{
if (readerOnBase.HasRows)
{
while (readerOnBase.Read())
{
strNextUser = readerOnBase[0].ToString();
}
}
}
}
catch (Exception ex)
{
throw new ApplicationException("Error during database operations!", ex);
}
finally
{
if (conOnBase.State == ConnectionState.Open) conOnBase.Close();
}
}
Keyword kwdUser = null;
if (!String.IsNullOrEmpty(strNextUser))
{
KeywordType kwtUser = app.Core.KeywordTypes.Find(gSaveToAssignedProc);
if (kwtUser != null)
kwdUser = CreateKeywordHelper(kwtUser, strNextUser);
}
Keyword kwdUnit = null;
if (!String.IsNullOrEmpty(strUnit))
{
KeywordType kwtUnit = app.Core.KeywordTypes.Find(gSaveToAssignedProcUnit);
if (kwtUnit != null)
kwdUnit = CreateKeywordHelper(kwtUnit, strUnit);
}
using (DocumentLock documentLock = _currentDocument.LockDocument())
{
// Ensure lock was obtained
if (documentLock.Status != DocumentLockStatus.LockObtained)
{
throw new Exception("Document lock not obtained");
}
// Create keyword modifier object to hold keyword changes
KeywordModifier keyModifier = _currentDocument.CreateKeywordModifier();
// Add update keyword call to keyword modifier object
//Note Overloads available for use
//(I.E.): keyModifier.AddKeyword(keywordTypeName,keywordValue)
if (kwdUnit != null) keyModifier.AddKeyword(kwdUnit);
if (kwdUser != null) keyModifier.AddKeyword(kwdUser);
// Apply keyword change to the document
keyModifier.ApplyChanges();
string output = String.Format("Keyword: '{0}' Value: '{1}', {3}added to Document {2}.",
gSaveToAssignedProcUnit, strUnit, _currentDocument.ID, Environment.NewLine);
//Output the results to the OnBase Diagnostics Console
app.Diagnostics.WriteIf(Hyland.Unity.Diagnostics.DiagnosticsLevel.Verbose, output);
string output2 = String.Format("Keyword: '{0}' Value: '{1}', {3}added to Document {2}.",
gSaveToAssignedProc, strWFUser, _currentDocument.ID, Environment.NewLine);
app.Diagnostics.WriteIf(Hyland.Unity.Diagnostics.DiagnosticsLevel.Verbose, output2);
}
}
else
{
throw new Exception(string.Format("No records found in database for {0}='{1}'", gParamBatchType, strBatchType));
}
}
}
catch (Exception ex)
{
throw new ApplicationException("Error during database operations!", ex);
}
finally
{
if (con.State == ConnectionState.Open) con.Close();
}
}
}
catch (Exception ex)
{
// Handle exceptions and log to Diagnostics Console and document history
HandleException(ex, ref app, ref args);
}
finally
{
// Log script execution end
app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Info,
string.Format("End Script - [{0}]", ScriptName));
}
#endregion
#region Helper Functions
/// <summary>
/// Initialize global settings
/// </summary>
/// <param name="app">Unity Application object</param>
/// <param name="args">Workflow event arguments</param>
private void IntializeScript(ref Application app, ref WorkflowEventArgs args)
{
// Set the specified diagnostics level
app.Diagnostics.Level = DiagLevel;
// Log script execution start
app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Info,
string.Format("{0} - Start Script - [{1}]", DateTime.Now.ToString(DateTimeFormat), ScriptName));
// Capture active document as global
_currentDocument = args.Document;
// _currentDocument = app.Core.GetDocumentByID(TestDocId);
// If an error was stored in the property bag from a previous execution, clear it
if (args.SessionPropertyBag.ContainsKey(ErrorMessageProperty)) args.SessionPropertyBag.Remove(ErrorMessageProperty);
// Set ScriptResult = true for workflow rules (will become false if an error is caught)
args.ScriptResult = true;
}
/// <summary>
/// Handle exceptions and log to Diagnostics Console and document history
/// </summary>
/// <param name="ex">Exception</param>
/// <param name="app">Unity Application object</param>
/// <param name="args">Workflow event arguments</param>
/// <param name="otherDocument">Document on which to update history if not active workflow document</param>
private void HandleException(Exception ex, ref Application app, ref WorkflowEventArgs args, Document otherDocument = null)
{
var history = app.Core.LogManagement;
bool isInner = false;
// Cycle through all inner exceptions
while (ex != null)
{
// Construct error text to store to workflow property
string propertyError = string.Format("{0}{1}: {2}",
isInner ? "Inner " : "",
ex.GetType().Name,
ex.Message);
// Construct error text to store to document history
string historyError = propertyError.Replace(ex.GetType().Name, "Unity Script Error");
// Construct error text to log to diagnostics console
string diagnosticsError = string.Format("{0} - ***ERROR***{1}{2}{1}{1}Stack Trace:{1}{3}",
DateTime.Now.ToString(DateTimeFormat),
Environment.NewLine,
propertyError,
ex.StackTrace);
// Add error message to document history (on current or specified document)
var document = otherDocument ?? _currentDocument;
if (document != null && WriteErrorsToHistory) history.CreateDocumentHistoryItem(document, historyError);
// Write error message to Diagnostcs Consonle
app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Error, diagnosticsError);
// Store the original (inner) exception message to error workflow property
if (ex.InnerException == null) args.SessionPropertyBag.Set(ErrorMessageProperty, ex.Message);
// Move on to next inner exception
ex = ex.InnerException;
isInner = true;
}
// Set ScriptResult = false for workflow rules
args.ScriptResult = false;
}
private Keyword CreateKeywordHelper(KeywordType Keytype, string Value)
{
Keyword key = null;
switch (Keytype.DataType)
{
case KeywordDataType.Currency:
case KeywordDataType.Numeric20:
decimal decVal = decimal.Parse(Value);
key = Keytype.CreateKeyword(decVal);
break;
case KeywordDataType.Date:
case KeywordDataType.DateTime:
DateTime dateVal = DateTime.Parse(Value);
key = Keytype.CreateKeyword(dateVal);
break;
case KeywordDataType.FloatingPoint:
double dblVal = double.Parse(Value);
key = Keytype.CreateKeyword(dblVal);
break;
case KeywordDataType.Numeric9:
long lngVal = long.Parse(Value);
key = Keytype.CreateKeyword(lngVal);
break;
default:
key = Keytype.CreateKeyword(Value);
break;
}
return key;
}
#endregion
}
}