source: Scheduling/trunk/cs/bsdx0200GUISourceCode/CGDocumentManager.cs@ 1104

Last change on this file since 1104 was 1104, checked in by Sam Habiel, 13 years ago

CGDocumentManager: Holiday SQL statement relied on Windows Date which is culture specific. Now sent as culture insensitive FM Date for query.

File size: 44.8 KB
Line 
1using System;
2using System.Windows.Forms;
3using System.Collections;
4using System.Data;
5using System.Diagnostics;
6using System.Threading;
7using IndianHealthService.BMXNet;
8using Mono.Options;
9using System.Runtime.InteropServices;
10
11namespace IndianHealthService.ClinicalScheduling
12{
13 /// <summary>
14 /// Main Worker. Handles sub-forms.
15 /// </summary>
16 public class CGDocumentManager //: System.Windows.Forms.Form
17 {
18 #region Member Variables
19
20 private static CGDocumentManager _current;
21 private Hashtable _views = new Hashtable(); //Returns the list of currently opened documents
22 private Hashtable m_AVViews = new Hashtable(); // List of currently opened CGAVViews
23 private string m_sWindowText = "Clinical Scheduling"; //Default Window Text
24 private bool m_bSchedManager = false; // Do you have the XUPROGMODE or BSDXZMGR?
25 private bool m_bExitOK = true; // Okay to exit program? Used to control Re-logins. Default true.
26 public string m_sHandle = "0"; // Not Used
27
28 //Connection variables (tied to command line parameters /a /v /s /p /e)
29 private string m_AccessCode="";
30 private string m_VerifyCode="";
31 private string m_Server="";
32 private int m_Port=0;
33 private string m_Encoding=""; //Encoding is "" by default;
34
35 //Data Access Layer
36 private DAL _dal = null;
37
38 //M Connection member variables
39 private DataSet m_dsGlobal = null; // Holds all user data
40 private BMXNetConnectInfo m_ConnectInfo = null; // Connection to VISTA object
41 private BMXNetConnectInfo.BMXNetEventDelegate CDocMgrEventDelegate; // Delegate to respond to messages from VISTA. Responds to event: BMXNetConnectInfo.BMXNetEvent
42
43 //Custom Printing
44 private CustomPrinting m_PrintingObject = null;
45 #endregion
46
47 #region Properties
48
49 /// <summary>
50 /// Returns the document manager's BMXNetConnectInfo member
51 /// </summary>
52 public BMXNetConnectInfo ConnectInfo
53 {
54 get
55 {
56 return m_ConnectInfo;
57 }
58 }
59
60 /// <summary>
61 /// True if the current user holds the BSDXZMGR or XUPROGMODE keys in RPMS
62 /// </summary>
63 public bool ScheduleManager
64 {
65 get
66 {
67 return m_bSchedManager;
68 }
69 }
70
71 /// <summary>
72 /// Holds the user and division
73 /// </summary>
74 public string WindowText
75 {
76 get
77 {
78 return m_sWindowText;
79 }
80 }
81
82 /// <summary>
83 /// This dataset contains tables used by the entire application
84 /// </summary>
85 public DataSet GlobalDataSet
86 {
87 get
88 {
89 return m_dsGlobal;
90 }
91 set
92 {
93 m_dsGlobal = value;
94 }
95 }
96
97 /// <summary>
98 /// Returns the single CGDocumentManager object
99 /// </summary>
100 public static CGDocumentManager Current
101 {
102 get
103 {
104 return _current;
105 }
106 }
107
108
109 /// <summary>
110 /// Returns the list of currently opened documents
111 /// </summary>
112 public Hashtable Views
113 {
114 get
115 {
116 return _views;
117 }
118 }
119
120 /// <summary>
121 /// Returns the list of currently opened CGAVViews
122 /// </summary>
123 public Hashtable AvailabilityViews
124 {
125 get
126 {
127 return this.m_AVViews;
128 }
129 }
130
131 public DAL DAL
132 {
133 get { return this._dal; }
134 }
135
136 public CustomPrinting PrintingObject
137 {
138 get
139 {
140 return this.m_PrintingObject;
141 }
142 }
143 #endregion
144
145 /// <summary>
146 /// Constructor. Does absolutely nothing at this point.
147 /// </summary>
148 public CGDocumentManager()
149 {
150 }
151
152
153#if DEBUG
154 //To write to the console
155 [DllImport("kernel32.dll")]
156 static extern bool AttachConsole(int dwProcessId);
157 private const int ATTACH_PARENT_PROCESS = -1;
158#endif
159 /// <summary>
160 /// Main Entry Point
161 /// </summary>
162 /// <param name="args">We accept the following Arguments:
163 /// /s or -s = Server ip address or name
164 /// /p or -p = port number (must be numeric)
165 /// /a or -a = Access Code
166 /// /v or -v = Verify Code
167 /// /e or -e = Encoding (name of encoding as known to windows, such as windows-1256)
168 /// </param>
169 /// <remarks>
170 /// Encoding decision is complex. This is the order of priority:
171 /// - If the M DB runs in UTF-8, that's what we are going to use.
172 /// - If that's not so, /e sets the default encoding. If /e is a non-existent encoding, move to next step.
173 /// - If /e is not supplied or is not recognized, the default encoding is the Windows default Encoding for the user.
174 /// </remarks>
175 [STAThread()]
176 static void Main(string[] args)
177 {
178#if DEBUG
179 // Print console messages to console if launched from console
180 // Note: Imported From kernel32.dll
181 AttachConsole(ATTACH_PARENT_PROCESS);
182#endif
183
184#if TRACE
185 DateTime startLoadTime = DateTime.Now;
186#endif
187
188 //Store a class instance of manager. Actual constructor does nothing.
189 _current = new CGDocumentManager();
190
191 //Get command line options; store in private class wide variables
192 var opset = new OptionSet() {
193 { "s=", s => _current.m_Server = s },
194 { "p=", p => _current.m_Port = int.Parse(p) },
195 { "a=", a => _current.m_AccessCode = a },
196 { "v=", v => _current.m_VerifyCode = v },
197 { "e=", e => _current.m_Encoding = e}
198 };
199
200 opset.Parse(args);
201
202 //Init app
203 bool isEverythingOkay = _current.InitializeApp();
204
205 //if an error occurred, break out.
206 if (!isEverythingOkay) return;
207
208 //Create the first empty document
209 //A document holds the resources, appointments, and availabilites
210 //SAM: Good place for break point
211 CGDocument doc = new CGDocument();
212 doc.DocManager = _current;
213
214 //Create new View
215 //A view is a specific arrangement of appointments and availabilites that constitute a document
216 CGView view = new CGView();
217 view.InitializeDocView(doc, _current, doc.StartDate, _current.WindowText);
218
219 //Handle BMX Event
220 Application.DoEvents();
221
222 //Application wide error handler for unhandled errors
223 Application.ThreadException += new ThreadExceptionEventHandler(App_ThreadException);
224
225#if TRACE
226 DateTime EndLoadTime = DateTime.Now;
227 TimeSpan LoadTime = EndLoadTime - startLoadTime;
228 Debug.Write("Load Time for GUI is " + LoadTime.Seconds + " s & " + LoadTime.Milliseconds + " ms\n");
229#endif
230
231 view.Show();
232 view.Activate();
233
234 Application.Run();
235 }
236
237 /// <summary>
238 /// Exception handler for application errors. TODO: Test
239 /// </summary>
240 /// <param name="sender"></param>
241 /// <param name="e"></param>
242 static void App_ThreadException(object sender, ThreadExceptionEventArgs e)
243 {
244 if (e.Exception is System.Net.Sockets.SocketException)
245 {
246 MessageBox.Show("Looks like we lost our connection with the server\nClick OK to terminate the application.");
247 Application.Exit();
248 }
249
250 string msg = "A problem has occured in this applicaton. \r\n\r\n" +
251 "\t" + e.Exception.Message + "\r\n\r\n" +
252 "Would you like to continue the application?";
253
254 DialogResult res = MessageBox.Show(msg, "Unexpected Error", MessageBoxButtons.YesNo);
255
256 if (res == DialogResult.Yes) return;
257 else Application.Exit();
258 }
259
260
261 #region BMXNet Event Handler
262 private void CDocMgrEventHandler(Object obj, BMXNet.BMXNetEventArgs e)
263 {
264 if (e.BMXEvent == "BSDX CALL WORKSTATIONS")
265 {
266 string sParam = "";
267 string sDelim="~";
268 sParam += this.m_ConnectInfo.UserName + sDelim;
269 sParam += this.m_sHandle + sDelim;
270 sParam += Application.ProductVersion + sDelim;
271 sParam += this._views.Count.ToString();
272 _current.m_ConnectInfo.RaiseEvent("BSDX WORKSTATION REPORT", sParam, true);
273 }
274 if (e.BMXEvent == "BSDX ADMIN MESSAGE")
275 {
276 string sMsg = e.BMXParam;
277 ShowAdminMsgDelegate samd = new ShowAdminMsgDelegate(ShowAdminMsg);
278 //this.Invoke(samd, new object [] {sMsg});
279 samd.Invoke(sMsg);
280 }
281 if (e.BMXEvent == "BSDX ADMIN SHUTDOWN")
282 {
283 string sMsg = e.BMXParam;
284 CloseAllDelegate cad = new CloseAllDelegate(CloseAll);
285 //this.Invoke(cad, new object [] {sMsg});
286 cad.Invoke(sMsg);
287 }
288 }
289
290 delegate void ShowAdminMsgDelegate(string sMsg);
291
292 private void ShowAdminMsg(string sMsg)
293 {
294 MessageBox.Show(sMsg, "Message from Scheduling Administrator", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
295 }
296
297 #endregion BMXNet Event Handler
298
299
300 #region Methods & Events
301
302 /// <summary>
303 /// See InitializeApp(bool) below
304 /// </summary>
305 private bool InitializeApp()
306 {
307 return InitializeApp(false);
308 }
309
310 /// <summary>
311 /// Does a million things:
312 /// 1. Starts Connection and displays log-in dialogs
313 /// 2. Starts Splash screen
314 /// 3. Loads data tables
315 /// </summary>
316 /// <param name="bReLogin">Is the User logging in again from a currently running instance?
317 /// If so, display a dialog to collect access and verify codes.</param>
318 private bool InitializeApp(bool bReLogin)
319 {
320 //Set M connection info
321 m_ConnectInfo = new BMXNetConnectInfo(m_Encoding); // Encoding is "" unless passed in command line
322 _dal = new DAL(m_ConnectInfo); // Data access layer
323 //m_ConnectInfo.bmxNetLib.StartLog(); //This line turns on logging of messages
324
325 //Create a delegate to process events raised by BMX.
326 CDocMgrEventDelegate = new BMXNetConnectInfo.BMXNetEventDelegate(CDocMgrEventHandler);
327 //Tie delegate to Events generated by BMX.
328 m_ConnectInfo.BMXNetEvent += CDocMgrEventDelegate;
329 //Disable polling (But does this really work???? I don't see how it gets disabled)
330 m_ConnectInfo.EventPollingEnabled = false;
331
332 //Show a splash screen while initializing; define delegates to remote thread
333 DSplash m_ds = new DSplash();
334 DSplash.dSetStatus setStatusDelegate = new DSplash.dSetStatus(m_ds.SetStatus);
335 DSplash.dAny closeSplashDelegate = new DSplash.dAny(m_ds.RemoteClose);
336 DSplash.dProgressBarSet setMaxProgressDelegate = new DSplash.dProgressBarSet(m_ds.RemoteProgressBarMaxSet);
337 DSplash.dProgressBarSet setProgressDelegate = new DSplash.dProgressBarSet(m_ds.RemoteProgressBarValueSet);
338
339 //Start new thread for the Splash screen.
340 Thread threadSplash = new Thread(new ParameterizedThreadStart(frm => ((DSplash)frm).ShowDialog()));
341 threadSplash.IsBackground = true; //expendable thread -- exit even if still running.
342 threadSplash.Name = "Splash Thread";
343 threadSplash.Start(m_ds); // pass form as parameter.
344
345 //There are 19 steps to load the application. That's max for the progress bar.
346 setMaxProgressDelegate(19);
347
348 // smh--not used: System.Configuration.ConfigurationManager.GetSection("appSettings");
349
350 setStatusDelegate("Connecting to VISTA");
351
352 //Try to connect using supplied values for Server and Port
353 //Why am I doing this? The library BMX net uses prompts for access and verify code
354 //whether you can connect or not. Not good. So I test first whether
355 //we can connect at all by doing a simple connection and disconnect.
356 //TODO: Make this more robust by sending a TCPConnect message and seeing if you get a response
357 if (m_Server != "" && m_Port != 0)
358 {
359 System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient();
360 try
361 {
362 tcpClient.Connect(m_Server, m_Port); // open it
363 tcpClient.Close(); // then close it
364 }
365 catch (System.Net.Sockets.SocketException)
366 {
367 MessageBox.Show("Cannot connect to VistA. Network Error");
368 return false;
369 }
370 }
371
372
373 bool bRetry = true;
374
375 // Do block is Log-in logic
376 do
377 {
378 // login crap
379 try
380 {
381 // Not my code
382 if (bReLogin == true)
383 {
384 //Prompt for Access and Verify codes
385 _current.m_ConnectInfo.LoadConnectInfo("", "");
386 }
387 // My code -- buts looks so ugly!
388 // Checks the passed parameters stored in the class variables
389 else
390 {
391 if (m_Server != String.Empty && m_Port != 0 && m_AccessCode != String.Empty
392 && m_VerifyCode != String.Empty)
393 {
394 m_ConnectInfo.LoadConnectInfo(m_Server, m_Port, m_AccessCode, m_VerifyCode);
395 }
396 else if (m_Server != String.Empty && m_Port != 0)
397 m_ConnectInfo.LoadConnectInfo(m_Server, m_Port, "", "");
398 else
399 m_ConnectInfo.LoadConnectInfo();
400 }
401 bRetry = false;
402 }
403 catch (System.Net.Sockets.SocketException)
404 {
405 MessageBox.Show("Cannot connect to VistA. Network Error");
406 }
407 catch (BMXNetException ex)
408 {
409 if (MessageBox.Show("Unable to connect to VistA. " + ex.Message, "Clinical Scheduling", MessageBoxButtons.RetryCancel) == DialogResult.Retry)
410 {
411 bRetry = true;
412 _current.m_ConnectInfo.ChangeServerInfo();
413 }
414 else
415 {
416 closeSplashDelegate();
417 bRetry = false;
418 return false; //tell main that it's a no go.
419 }
420 }
421 }while (bRetry == true);
422
423 //Printing
424
425 string DllLocation = string.Empty;
426 System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Application.StartupPath + @"\Printing\");
427 if (di.Exists)
428 {
429 System.IO.FileInfo[] rgFiles = di.GetFiles("*.dll");
430
431 foreach (System.IO.FileInfo fi in rgFiles)
432 {
433 DllLocation = fi.FullName;
434 }
435 }
436
437 PrintingCreator Creator = null;
438 if (DllLocation == string.Empty)
439 {
440 this.m_PrintingObject = new CustomPrinting();
441 }
442 else
443 {
444 System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(DllLocation);
445 foreach (Type type in assembly.GetTypes())
446 {
447 if (type.IsClass == true & type.BaseType == typeof(PrintingCreator))
448 {
449 Creator = (PrintingCreator)Activator.CreateInstance(type);
450 break;
451 }
452 }
453 this.m_PrintingObject = Creator.PrintFactory();
454 }
455
456 //Create global dataset
457 _current.m_dsGlobal = new DataSet("GlobalDataSet");
458
459 //Version info
460 // Table #1
461 setProgressDelegate(1);
462 setStatusDelegate("Getting Version Info from Server...");
463
464 DataTable ver = _dal.GetVersion("BSDX");
465 ver.TableName = "VersionInfo";
466 m_dsGlobal.Tables.Add(ver);
467
468 //How to extract the version numbers:
469 DataTable dtVersion = m_dsGlobal.Tables["VersionInfo"];
470 Debug.Assert(dtVersion.Rows.Count == 1);
471 DataRow rVersion = dtVersion.Rows[0];
472 string sMajor = rVersion["MAJOR_VERSION"].ToString();
473 string sMinor = rVersion["MINOR_VERSION"].ToString();
474 string sBuild = rVersion["BUILD"].ToString();
475 decimal fBuild = Convert.ToDecimal(sBuild);
476
477 //Make sure that the server is running the same version the client is.
478 Version x = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
479
480 //if version numbers mismatch, don't continue.
481 //TODO: For future: Include in v. 1.5
482 /*
483 if (!(x.Major.ToString() == sMajor && x.Minor.ToString() + x.Build.ToString() == sMinor))
484 {
485 MessageBox.Show(
486 "Server runs version " + sMajor + "." + sMinor + "\r\n" +
487 "You are running " + x.ToString() + "\r\n\r\n" +
488 "Major, Minor and Build versions must match",
489 "Version Mismatch");
490 m_ds.Close();
491 return;
492 }
493 */
494
495
496 //Change encoding
497 // Call #2
498 setProgressDelegate(2);
499 setStatusDelegate("Setting encoding...");
500
501 if (m_Encoding == String.Empty)
502 {
503 string utf8_server_support = m_ConnectInfo.bmxNetLib.TransmitRPC("BMX UTF-8", "");
504 if (utf8_server_support == "1")
505 m_ConnectInfo.bmxNetLib.Encoder = System.Text.UTF8Encoding.UTF8;
506 }
507
508 //Set application context
509 // Call #3
510 setProgressDelegate(3);
511 setStatusDelegate("Setting Application Context to BSDXRPC...");
512 m_ConnectInfo.AppContext = "BSDXRPC";
513
514 //Load global recordsets
515 string statusConst = "Loading VistA data tables...";
516 setStatusDelegate(statusConst);
517
518 string sCommandText;
519
520 //Schedule User Info
521 // Table #4
522 setProgressDelegate(4);
523 setStatusDelegate(statusConst + " Schedule User");
524 DataTable dtUser = _dal.GetUserInfo(m_ConnectInfo.DUZ);
525 dtUser.TableName = "SchedulingUser";
526 m_dsGlobal.Tables.Add(dtUser);
527 Debug.Assert(dtUser.Rows.Count == 1);
528
529 // Only one row and one column named "MANAGER". Set local var m_bSchedManager to true if Manager.
530 DataRow rUser = dtUser.Rows[0];
531 Object oUser = rUser["MANAGER"];
532 string sUser = oUser.ToString();
533 m_bSchedManager = (sUser == "YES") ? true : false;
534
535 //Get Access Types
536 // Table #5
537 setProgressDelegate(5);
538 setStatusDelegate(statusConst + " Access Types");
539 DataTable dtAccessTypes = _dal.GetAccessTypes();
540 dtAccessTypes.TableName = "AccessTypes";
541 m_dsGlobal.Tables.Add(dtAccessTypes);
542
543 //Get Access Groups
544 // Table #6
545 setProgressDelegate(6);
546 setStatusDelegate(statusConst + " Access Groups");
547 LoadAccessGroupsTable();
548
549 //Build Primary Key for AccessGroup table
550 DataTable dtGroups = m_dsGlobal.Tables["AccessGroup"];
551 DataColumn dcKey = dtGroups.Columns["ACCESS_GROUP"];
552 DataColumn[] dcKeys = new DataColumn[1];
553 dcKeys[0] = dcKey;
554 dtGroups.PrimaryKey = dcKeys;
555
556 //Get Access Group Types (Combines Access Types and Groups)
557 //Optimization Note: Can eliminate Access type and Access Group Table
558 // But they are heavily referenced throughout the code.
559 // Table #7
560 setProgressDelegate(7);
561 setStatusDelegate(statusConst + " Access Group Types");
562 LoadAccessGroupTypesTable();
563
564 //Build Primary Key for AccessGroupType table
565 DataTable dtAGTypes = m_dsGlobal.Tables["AccessGroupType"];
566 DataColumn dcGTKey = dtAGTypes.Columns["ACCESS_GROUP_TYPEID"];
567 DataColumn[] dcGTKeys = new DataColumn[1];
568 dcGTKeys[0] = dcGTKey;
569 dtAGTypes.PrimaryKey = dcGTKeys;
570
571 //Build Data Relationship between AccessGroupType and AccessTypes tables
572 DataRelation dr = new DataRelation("AccessGroupType", //Relation Name
573 m_dsGlobal.Tables["AccessGroup"].Columns["BMXIEN"], //Parent
574 m_dsGlobal.Tables["AccessGroupType"].Columns["ACCESS_GROUP_ID"]); //Child
575 m_dsGlobal.Relations.Add(dr);
576
577 //ResourceGroup Table (Resource Groups by User)
578 // Table #8
579 // What shows up on the tree. The groups the user has access to.
580 setProgressDelegate(8);
581 setStatusDelegate(statusConst + " Resource Groups By User");
582 LoadResourceGroupTable();
583
584 //Resources by user
585 // Table #9
586 // Individual Resources
587 setProgressDelegate(9);
588 setStatusDelegate(statusConst + " Resources By User");
589 LoadBSDXResourcesTable();
590
591 //Build Primary Key for Resources table
592 DataColumn[] dc = new DataColumn[1];
593 dc[0] = m_dsGlobal.Tables["Resources"].Columns["RESOURCEID"];
594 m_dsGlobal.Tables["Resources"].PrimaryKey = dc;
595
596 //GroupResources table
597 // Table #10
598 // Resource Groups and Indivdual Resources together
599 setProgressDelegate(10);
600 setStatusDelegate(statusConst + " Group Resources");
601 LoadGroupResourcesTable();
602
603 //Build Primary Key for ResourceGroup table
604 dc = new DataColumn[1];
605 dc[0] = m_dsGlobal.Tables["ResourceGroup"].Columns["RESOURCE_GROUP"];
606 m_dsGlobal.Tables["ResourceGroup"].PrimaryKey = dc;
607
608 //Build Data Relationships between ResourceGroup and GroupResources tables
609 dr = new DataRelation("GroupResource", //Relation Name
610 m_dsGlobal.Tables["ResourceGroup"].Columns["RESOURCE_GROUP"], //Parent
611 m_dsGlobal.Tables["GroupResources"].Columns["RESOURCE_GROUP"]); //Child
612
613 m_dsGlobal.Relations.Add(dr);
614
615 //HospitalLocation table
616 //Table #11
617 setProgressDelegate(11);
618 setStatusDelegate(statusConst + " Clinics");
619 //cmd.CommandText = "SELECT BMXIEN 'HOSPITAL_LOCATION_ID', NAME 'HOSPITAL_LOCATION', DEFAULT_PROVIDER, STOP_CODE_NUMBER, INACTIVATE_DATE, REACTIVATE_DATE FROM HOSPITAL_LOCATION";
620 sCommandText = "BSDX HOSPITAL LOCATION";
621 ConnectInfo.RPMSDataTable(sCommandText, "HospitalLocation", m_dsGlobal);
622 Debug.Write("LoadGlobalRecordsets -- HospitalLocation loaded\n");
623
624 //Build Primary Key for HospitalLocation table
625 dc = new DataColumn[1];
626 DataTable dtTemp = m_dsGlobal.Tables["HospitalLocation"];
627 dc[0] = dtTemp.Columns["HOSPITAL_LOCATION_ID"];
628 m_dsGlobal.Tables["HospitalLocation"].PrimaryKey = dc;
629
630 //Build Data Relationships between Resources and HospitalLocation tables
631 dr = new DataRelation("HospitalLocationResource", //Relation Name
632 m_dsGlobal.Tables["HospitalLocation"].Columns["HOSPITAL_LOCATION_ID"], //Parent
633 m_dsGlobal.Tables["Resources"].Columns["HOSPITAL_LOCATION_ID"], false); //Child
634 m_dsGlobal.Relations.Add(dr);
635
636 //Build ScheduleUser table
637 //Table #12
638 setProgressDelegate(12);
639 setStatusDelegate(statusConst + " Schedule User");
640 this.LoadScheduleUserTable();
641
642 //Build Primary Key for ScheduleUser table
643 dc = new DataColumn[1];
644 dtTemp = m_dsGlobal.Tables["ScheduleUser"];
645 dc[0] = dtTemp.Columns["USERID"];
646 m_dsGlobal.Tables["ScheduleUser"].PrimaryKey = dc;
647
648 //Build ResourceUser table
649 //Table #13
650 //Acess to Resources by [this] User
651 setProgressDelegate(13);
652 setStatusDelegate(statusConst + " Resource User");
653 this.LoadResourceUserTable();
654
655 //Build Primary Key for ResourceUser table
656 dc = new DataColumn[1];
657 dtTemp = m_dsGlobal.Tables["ResourceUser"];
658 dc[0] = dtTemp.Columns["RESOURCEUSER_ID"];
659 m_dsGlobal.Tables["ResourceUser"].PrimaryKey = dc;
660
661 //Create relation between BSDX Resource and BSDX Resource User tables
662 dr = new DataRelation("ResourceUser", //Relation Name
663 m_dsGlobal.Tables["Resources"].Columns["RESOURCEID"], //Parent
664 m_dsGlobal.Tables["ResourceUser"].Columns["RESOURCEID"]); //Child
665 m_dsGlobal.Relations.Add(dr);
666
667 //Build active provider table
668 //Table #14
669 //TODO: Lazy load the provider table; no need to load in advance.
670 setProgressDelegate(14);
671 setStatusDelegate(statusConst + " Providers");
672 sCommandText = "SELECT BMXIEN, NAME FROM NEW_PERSON WHERE INACTIVE_DATE = '' AND BMXIEN > 1";
673 ConnectInfo.RPMSDataTable(sCommandText, "Provider", m_dsGlobal);
674 Debug.Write("LoadGlobalRecordsets -- Provider loaded\n");
675
676 //Build the HOLIDAY table
677 //Table #15
678 setProgressDelegate(15);
679 setStatusDelegate(statusConst + " Holiday");
680 sCommandText = "SELECT NAME, DATE FROM HOLIDAY WHERE INTERNAL[DATE] > '" + FMDateTime.Create(DateTime.Today).DateOnly.FMDateString + "'";
681 ConnectInfo.RPMSDataTable(sCommandText, "HOLIDAY", m_dsGlobal);
682 Debug.Write("LoadingGlobalRecordsets -- Holidays loaded\n");
683
684
685 //Save the xml schema
686 //m_dsGlobal.WriteXmlSchema(@"..\..\csSchema20060526.xsd");
687 //----------------------------------------------
688
689 setStatusDelegate("Setting Receive Timeout");
690 _current.m_ConnectInfo.ReceiveTimeout = 30000; //30-second timeout
691
692#if DEBUG
693 _current.m_ConnectInfo.ReceiveTimeout = 600000; //longer timeout for debugging
694#endif
695 // Event Subsriptions
696 setStatusDelegate("Subscribing to Server Events");
697 //Table #16
698 setProgressDelegate(16);
699 _current.m_ConnectInfo.SubscribeEvent("BSDX SCHEDULE");
700 //Table #17
701 setProgressDelegate(17);
702 _current.m_ConnectInfo.SubscribeEvent("BSDX CALL WORKSTATIONS");
703 //Table #18
704 setProgressDelegate(18);
705 _current.m_ConnectInfo.SubscribeEvent("BSDX ADMIN MESSAGE");
706 //Table #19
707 setProgressDelegate(19);
708 _current.m_ConnectInfo.SubscribeEvent("BSDX ADMIN SHUTDOWN");
709
710 _current.m_ConnectInfo.EventPollingInterval = 5000; //in milliseconds
711 _current.m_ConnectInfo.EventPollingEnabled = true;
712 _current.m_ConnectInfo.AutoFire = 12; //AutoFire every 12*5 seconds
713
714 //Close Splash Screen
715 closeSplashDelegate();
716
717 return true;
718
719 }
720
721
722
723 public void LoadAccessGroupsTable()
724 {
725 string sCommandText = "SELECT * FROM BSDX_ACCESS_GROUP";
726 ConnectInfo.RPMSDataTable(sCommandText, "AccessGroup", m_dsGlobal);
727 Debug.Write("LoadGlobalRecordsets -- AccessGroups loaded\n");
728 }
729
730 public void LoadAccessGroupTypesTable()
731 {
732 string sCommandText = "BSDX GET ACCESS GROUP TYPES";
733 ConnectInfo.RPMSDataTable(sCommandText, "AccessGroupType", m_dsGlobal);
734 Debug.Write("LoadGlobalRecordsets -- AccessGroupTypes loaded\n");
735 }
736
737 public void LoadBSDXResourcesTable()
738 {
739 string sCommandText = "BSDX RESOURCES^" + m_ConnectInfo.DUZ;
740 ConnectInfo.RPMSDataTable(sCommandText, "Resources", m_dsGlobal);
741 Debug.Write("LoadGlobalRecordsets -- Resources loaded\n");
742 }
743
744 public void LoadResourceGroupTable()
745 {
746 //ResourceGroup Table (Resource Groups by User)
747 //Table "ResourceGroup" contains all resource group names
748 //to which user has access
749 //Fields are: RESOURCE_GROUPID, RESOURCE_GROUP
750 string sCommandText = "BSDX RESOURCE GROUPS BY USER^" + m_ConnectInfo.DUZ;
751 ConnectInfo.RPMSDataTable(sCommandText, "ResourceGroup", m_dsGlobal);
752 Debug.Write("LoadGlobalRecordsets -- ResourceGroup loaded\n");
753 }
754
755 public void LoadGroupResourcesTable()
756 {
757 //Table "GroupResources" contains all active GROUP/RESOURCE combinations
758 //to which user has access based on entries in BSDX RESOURCE USER file
759 //If user has BSDXZMGR or XUPROGMODE keys, then ALL Group/Resource combinstions
760 //are returned.
761 //Fields are: RESOURCE_GROUPID, RESOURCE_GROUP, RESOURCE_GROUP_ITEMID, RESOURCE_NAME, RESOURCE_ID
762 string sCommandText = "BSDX GROUP RESOURCE^" + m_ConnectInfo.DUZ;
763 ConnectInfo.RPMSDataTable(sCommandText, "GroupResources", m_dsGlobal);
764 Debug.Write("LoadGlobalRecordsets -- GroupResources loaded\n");
765 }
766
767 public void LoadScheduleUserTable()
768 {
769 //Table "ScheduleUser" contains an entry for each user in File 200 (NEW PERSON)
770 //who possesses the BSDXZMENU security key.
771 string sCommandText = "BSDX SCHEDULE USER";
772 ConnectInfo.RPMSDataTable(sCommandText, "ScheduleUser", m_dsGlobal);
773 Debug.Write("LoadGlobalRecordsets -- ScheduleUser loaded\n");
774 }
775
776 public void LoadResourceUserTable()
777 {
778 //Table "ResourceUser" duplicates the BSDX RESOURCE USER File.
779 //NOTE: Column names are RESOURCEUSER_ID, RESOURCEID,
780 // OVERBOOK, MODIFY_SCHEDULE, USERID, USERID1
781 //string sCommandText = "SELECT BMXIEN RESOURCEUSER_ID, INTERNAL[RESOURCENAME] RESOURCEID, OVERBOOK, MODIFY_SCHEDULE, USERNAME USERID, INTERNAL[USERNAME] FROM BSDX_RESOURCE_USER";
782 LoadResourceUserTable(false);
783 }
784
785 public void LoadResourceUserTable(bool bAllUsers)
786 {
787 string sCommandText = @"SELECT BMXIEN RESOURCEUSER_ID, RESOURCENAME, INTERNAL[RESOURCENAME] RESOURCEID, OVERBOOK, MODIFY_SCHEDULE, MODIFY_APPOINTMENTS, USERNAME, INTERNAL[USERNAME] USERID FROM BSDX_RESOURCE_USER"; // WHERE INTERNAL[INSTITUTION]=" + m_ConnectInfo.DUZ2;
788
789 if (!bAllUsers)
790 {
791 sCommandText += String.Format(" WHERE INTERNAL[USERNAME] = {0}", m_ConnectInfo.DUZ);
792 }
793
794 ConnectInfo.RPMSDataTable(sCommandText, "ResourceUser", m_dsGlobal);
795 Debug.Write("LoadGlobalRecordsets -- ResourceUser loaded\n");
796 }
797
798
799 public void RegisterDocumentView(CGDocument doc, CGView view)
800 {
801 //Store the view in the list of views
802 this.Views.Add(view, doc);
803
804 //Hook into the view's 'closed' event
805 view.Closed += new EventHandler(ViewClosed);
806
807 //Hook into the view's mnuRPMSServer.Click event
808 view.mnuRPMSServer.Click += new EventHandler(mnuRPMSServer_Click);
809
810 //Hook into the view's mnuRPMSLogin.Click event
811 view.mnuRPMSLogin.Click += new EventHandler(mnuRPMSLogin_Click);
812
813 }
814
815 public void RegisterAVDocumentView(CGAVDocument doc, CGAVView view)
816 {
817 //Store the view in the list of views
818 this.AvailabilityViews.Add(view, doc);
819
820 //Hook into the view's 'closed' event
821 view.Closed += new EventHandler(AVViewClosed);
822 }
823
824 public CGAVView GetAVViewByResource(ArrayList sResourceArray)
825 {
826 if (sResourceArray == null)
827 return null;
828
829 bool bEqual = true;
830 foreach (CGAVView v in m_AVViews.Keys)
831 {
832 CGAVDocument d = v.Document;
833
834 bEqual = false;
835 if (d.Resources.Count == sResourceArray.Count)
836 {
837 bEqual = true;
838 for (int j = 0; j < sResourceArray.Count; j++)
839 {
840 if (sResourceArray.Contains(d.Resources[j]) == false)
841 {
842 bEqual = false;
843 break;
844 }
845 if (d.Resources.Contains(sResourceArray[j]) == false)
846 {
847 bEqual = false;
848 break;
849 }
850 }
851 if (bEqual == true)
852 return v;
853 }
854 }
855 return null;
856 }
857 /// <summary>
858 /// Return the first view having a resource array matching sResourceArray
859 /// </summary>
860 /// <param name="sResourceArray"></param>
861 /// <returns></returns>
862 public CGView GetViewByResource(ArrayList sResourceArray)
863 {
864 if (sResourceArray == null)
865 return null;
866
867 bool bEqual = true;
868 foreach (CGView v in _views.Keys)
869 {
870 CGDocument d = v.Document;
871
872 bEqual = false;
873 if (d.Resources.Count == sResourceArray.Count)
874 {
875 bEqual = true;
876 for (int j = 0; j < sResourceArray.Count; j++)
877 {
878 if (sResourceArray.Contains(d.Resources[j]) == false)
879 {
880 bEqual = false;
881 break;
882 }
883 if (d.Resources.Contains(sResourceArray[j]) == false)
884 {
885 bEqual = false;
886 break;
887 }
888 }
889 if (bEqual == true)
890 return v;
891 }
892 }
893 return null;
894 }
895
896 /// <summary>
897 /// Removes view and Handles Disconnection from Database if no views are left.
898 /// </summary>
899 /// <param name="sender"></param>
900 /// <param name="e"></param>
901 private void ViewClosed(object sender, EventArgs e)
902 {
903 //Remove the sender from our document list
904 Views.Remove(sender);
905
906 //If no documents left, then close RPMS connection & exit the application
907 if ((Views.Count == 0)&&(this.AvailabilityViews.Count == 0)&&(m_bExitOK == true))
908 {
909 m_ConnectInfo.EventPollingEnabled = false;
910 m_ConnectInfo.UnSubscribeEvent("BSDX SCHEDULE");
911 m_ConnectInfo.CloseConnection();
912 Application.Exit();
913 }
914 }
915
916 private void AVViewClosed(object sender, EventArgs e)
917 {
918 //Remove the sender from our document list
919 this.AvailabilityViews.Remove(sender);
920
921 //If no documents left, then close RPMS connection & exit the application
922 if ((Views.Count == 0)&&(this.AvailabilityViews.Count == 0)&&(m_bExitOK == true))
923 {
924 m_ConnectInfo.bmxNetLib.CloseConnection();
925 Application.Exit();
926 }
927 }
928
929 /// <summary>
930 /// Not used
931 /// </summary>
932 private void KeepAlive()
933 {
934 foreach (CGView v in _views.Keys)
935 {
936 CGDocument d = v.Document;
937 DateTime dNow = DateTime.Now;
938 DateTime dLast = d.LastRefreshed;
939 TimeSpan tsDiff = dNow - dLast;
940 if (tsDiff.Seconds > 180)
941 {
942 for (int j = 0; j < d.Resources.Count; j++)
943 {
944 v.RaiseRPMSEvent("SCHEDULE-" + d.Resources[j].ToString(), "");
945 }
946
947 break;
948 }
949 }
950 }
951
952 /// <summary>
953 /// Propogate availability updates to all sRresource's doc/views
954 /// </summary>
955 public void UpdateViews(string sResource, string sOldResource)
956 {
957 if (sResource == null)
958 return;
959 foreach (CGView v in _views.Keys)
960 {
961 CGDocument d = v.Document;
962 for (int j = 0; j < d.Resources.Count; j++)
963 {
964 if ((sResource == "") || (sResource == ((string) d.Resources[j])) || (sOldResource == ((string) d.Resources[j])))
965 {
966 d.RefreshDocument();
967 break;
968 }
969 }
970 v.UpdateTree();
971 }
972 }
973
974 /// <summary>
975 /// Propogate availability updates to all doc/views
976 /// </summary>
977 public void UpdateViews()
978 {
979 UpdateViews("","");
980 foreach (CGView v in _views.Keys)
981 {
982 v.UpdateTree();
983 }
984 }
985
986 /// <summary>
987 /// Calls each view associated with document Doc and closes it.
988 /// </summary>
989 public void CloseAllViews(CGDocument doc)
990 {
991 //iterate through all views and call update.
992 Hashtable h = CGDocumentManager.Current.Views;
993
994 CGDocument d;
995 int nTempCount = h.Count;
996 do
997 {
998 nTempCount = h.Count;
999 foreach (CGView v in h.Keys)
1000 {
1001 d = (CGDocument) h[v];
1002 if (d == doc)
1003 {
1004 v.Close();
1005 break;
1006 }
1007 }
1008 } while ((h.Count > 0) && (nTempCount != h.Count));
1009 }
1010
1011 /// <summary>
1012 /// Calls each view associated with Availability Doc and closes it.
1013 /// </summary>
1014 public void CloseAllViews(CGAVDocument doc)
1015 {
1016 //iterate through all views and call update.
1017 Hashtable h = CGDocumentManager.Current.AvailabilityViews;
1018
1019 CGAVDocument d;
1020 int nTempCount = h.Count;
1021 do
1022 {
1023 nTempCount = h.Count;
1024 foreach (CGAVView v in h.Keys)
1025 {
1026 d = (CGAVDocument) h[v];
1027 if (d == doc)
1028 {
1029 v.Close();
1030 break;
1031 }
1032 }
1033 } while ((h.Count > 0) && (nTempCount != h.Count));
1034
1035
1036 }
1037
1038 /// <summary>
1039 /// Accomplishes Changing the Server to which you connect
1040 /// </summary>
1041 /// <remarks>
1042 /// Parameter relog-in for InitializeApp forces initialize app to use
1043 /// 1. The server the user just picked and then BMX saved off to User Preferences
1044 /// 2. A new access and verify code pair
1045 /// </remarks>
1046 /// <param name="sender">unused</param>
1047 /// <param name="e">unused</param>
1048 private void mnuRPMSServer_Click(object sender, EventArgs e)
1049 {
1050 //Warn that changing servers will close all schedules
1051 if (MessageBox.Show("Are you sure you want to close all schedules and connect to a different VistA server?", "Clinical Scheduling", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
1052 return;
1053
1054 //Reconnect to RPMS and recreate all global recordsets
1055 try
1056 {
1057 // Close All, but tell the Close All method not to call Applicaiton.Exit since we still plan to continue.
1058 // Close All does not call Application.Exit, but CGView_Close handler does
1059 m_bExitOK = false;
1060 CloseAll();
1061 m_bExitOK = true;
1062
1063 //Used in Do loop
1064 bool bRetry = true;
1065
1066 // Do Loop to deal with changing the server and the vagaries of user choices.
1067 do
1068 {
1069 try
1070 {
1071 //ChangeServerInfo does not re-login the user
1072 //It only changes the saved server information in the %APPDATA% folder
1073 //so it can be re-used when BMX tries to log in again.
1074 //Access and Verify code are prompted for in InitializeApp
1075 m_ConnectInfo.ChangeServerInfo();
1076 bRetry = false;
1077 }
1078 catch (Exception ex)
1079 {
1080 if (ex.Message == "User cancelled.")
1081 {
1082 bRetry = false;
1083 Application.Exit();
1084 return;
1085 }
1086 if (MessageBox.Show("Unable to connect to VistA. " + ex.Message , "Clinical Scheduling", MessageBoxButtons.RetryCancel) == DialogResult.Retry)
1087 {
1088 bRetry = true;
1089 }
1090 else
1091 {
1092 bRetry = false;
1093 Application.Exit();
1094 return;
1095 }
1096 }
1097 } while (bRetry == true);
1098
1099 //Parameter for initialize app tells it that this is a re-login and forces a new access and verify code.
1100 bool isEverythingOkay = this.InitializeApp(true);
1101
1102 //if an error occurred, break out. This time we need to call Application.Exit since it's already running.
1103 if (!isEverythingOkay)
1104 {
1105 Application.Exit();
1106 return;
1107 }
1108
1109 //Otherwise, everything is okay. So open document and view, then show and activate view.
1110 CGDocument doc = new CGDocument();
1111 doc.DocManager = _current;
1112
1113 CGView view = new CGView();
1114 view.InitializeDocView(doc, _current, doc.StartDate, _current.WindowText);
1115
1116 view.Show();
1117 view.Activate();
1118
1119 //Application.Run need not be called b/c it is already running.
1120 }
1121 catch (Exception ex)
1122 {
1123 throw ex;
1124 }
1125
1126 }
1127
1128 /// <summary>
1129 /// Accomplishes Re-login into RPMS/VISTA. Now all logic is in this event handler.
1130 /// </summary>
1131 /// <param name="sender">not used</param>
1132 /// <param name="e">not used</param>
1133 private void mnuRPMSLogin_Click(object sender, EventArgs e)
1134 {
1135 //Warn that changing login will close all schedules
1136 if (MessageBox.Show("Are you sure you want to close all schedules and login to VistA?", "Clinical Scheduling", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
1137 return;
1138
1139 //Reconnect to RPMS and recreate all global recordsets
1140 try
1141 {
1142 // Close All, but tell the Close All method not to call Applicaiton.Exit since we still plan to continue.
1143 // Close All does not call Application.Exit, but CGView_Close handler does
1144 m_bExitOK = false;
1145 CloseAll();
1146 m_bExitOK = true;
1147
1148 //Parameter for initialize app tells it that this is a re-login and forces a new access and verify code.
1149 bool isEverythingOkay = this.InitializeApp(true);
1150
1151 //if an error occurred, break out. This time we need to call Application.Exit since it's already running.
1152 if (!isEverythingOkay)
1153 {
1154 Application.Exit();
1155 return;
1156 }
1157
1158 //Otherwise, everything is okay. So open document and view, then show and activate view.
1159 CGDocument doc = new CGDocument();
1160 doc.DocManager = _current;
1161
1162 CGView view = new CGView();
1163 view.InitializeDocView(doc, _current, doc.StartDate, _current.WindowText);
1164
1165 view.Show();
1166 view.Activate();
1167
1168 //Application.Run need not be called b/c it is already running.
1169 }
1170 catch (Exception ex)
1171 {
1172 throw ex;
1173 }
1174
1175 }
1176
1177 delegate void CloseAllDelegate(string sMsg);
1178
1179 private void CloseAll(string sMsg)
1180 {
1181 if (sMsg == "")
1182 {
1183 sMsg = "Scheduling System Shutting Down Immediately for Maintenance.";
1184 }
1185
1186 MessageBox.Show(sMsg, "Clinical Scheduling Administrator -- System Shutdown Notification", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
1187
1188 CloseAll();
1189 }
1190
1191 private void CloseAll()
1192 {
1193 //Close all documents, views and connections
1194 Hashtable h = CGDocumentManager.Current.Views;
1195 int nTempCount = h.Count;
1196 do
1197 {
1198 nTempCount = h.Count;
1199 foreach (CGView v in h.Keys)
1200 {
1201 v.Close();
1202 break;
1203 }
1204 } while ((h.Count > 0) && (nTempCount != h.Count));
1205
1206 h = CGDocumentManager.Current.AvailabilityViews;
1207 nTempCount = h.Count;
1208 do
1209 {
1210 nTempCount = h.Count;
1211 foreach (CGAVView v in h.Keys)
1212 {
1213 v.Close();
1214 break;
1215 }
1216 } while ((h.Count > 0) && (nTempCount != h.Count));
1217
1218 }
1219
1220 public delegate DataTable RPMSDataTableDelegate(string CommandString, string TableName);
1221
1222 public DataTable RPMSDataTable(string sSQL, string sTableName)
1223 {
1224 //Retrieves a recordset from RPMS
1225 string sErrorMessage = "";
1226 DataTable dtOut;
1227
1228 try
1229 {
1230 //System.IntPtr pHandle = this.Handle;
1231 RPMSDataTableDelegate rdtd = new RPMSDataTableDelegate(ConnectInfo.RPMSDataTable);
1232 //dtOut = (DataTable) this.Invoke(rdtd, new object[] {sSQL, sTableName});
1233 dtOut = rdtd.Invoke(sSQL, sTableName);
1234 }
1235
1236 catch (Exception ex)
1237 {
1238 sErrorMessage = "CGDocumentManager.RPMSDataTable error: " + ex.Message;
1239 throw ex;
1240 }
1241
1242 return dtOut;
1243
1244 }
1245
1246 public void ChangeDivision(System.Windows.Forms.Form frmCaller)
1247 {
1248 this.ConnectInfo.ChangeDivision(frmCaller);
1249 foreach (CGView v in _views.Keys)
1250 {
1251 v.InitializeDocView(v.Document.DocName);
1252 v.Document.RefreshDocument();
1253 }
1254 }
1255
1256 public void ViewRefresh()
1257 {
1258 foreach (CGView v in _views.Keys)
1259 {
1260 try
1261 {
1262 v.Document.RefreshDocument();
1263 }
1264 catch (Exception ex)
1265 {
1266 Debug.Write("CGDocumentManager.ViewRefresh Exception: " + ex.Message + "\n");
1267 }
1268 finally
1269 {
1270 }
1271 }
1272 Debug.Write("DocManager refreshed all views.\n");
1273 }
1274
1275 #endregion Methods & Events
1276
1277 }
1278}
Note: See TracBrowser for help on using the repository browser.