Esempio n. 1
0
        public Automation3Form(bool show)
        {
            try
            {
                //status = new RiskApps3Automation.org.partners.dipr.hra.Service1();
                string url = Configurator.getAutomationHeartbeatServiceURL();
                if (url.Length == 0)
                {
                    status = null;
                }
                else
                {
                    status = new AutomationHeartbeat.Service1(url);
                }
            }
            catch (Exception e)
            {
                Logger.Instance.WriteToLog(e.ToString());
            }

            InitializeComponent();
            initFormText();
            string AutomationInterval = Configurator.getNodeValue("Globals", "AutomationInterval");
            int    aint = 10000;

            if (int.TryParse(AutomationInterval, out aint))
            {
                timer1.Interval = aint;
            }
            else
            {
                timer1.Interval = 10000;
            }
            timer1.Enabled = true;


            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(DocLoadComplete);

            PrinterSettings settings = new PrinterSettings();

            defaultPrinter = settings.PrinterName;
        }
Esempio n. 2
0
        public void automate()
        {
            if (status != null)
            {
                try
                {
                    //status.LogHeartbeat(this.Text);
                }
                catch (Exception ex)
                {
                    //  Logger.Instance.WriteToLog(ex.ToString());
                }
            }

            List <int> apptIDs = new List <int>();

            /***********************   get appointments to automate   ********************/
            SqlDataReader reader;
            string        CustomAutomationString = Configurator.getNodeValue("DatabaseInfo", "AUTOMATION_SQL");

            if (string.IsNullOrEmpty(CustomAutomationString) == false)
            {
                reader = BCDB2.Instance.ExecuteReader(CustomAutomationString);
            }
            else
            {
                reader = BCDB2.Instance.ExecuteReaderSPWithParams("sp_Automation", null);
            }
            try
            {
                while (reader.Read())
                {
                    if (reader.IsDBNull(0) == false)
                    {
                        apptIDs.Add(reader.GetInt32(0));
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Instance.WriteToLog("Error getting appointment IDs: " + e.ToString());
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }

            if (apptIDs.Count == 0)
            {
                ProcessingThread.ReportProgress(0,
                                                "No appointments are marked for automation - " + DateTime.Now.ToString());
                return;
            }


            /***********************    automation cycle   ********************/
            foreach (int apptid in apptIDs)
            {
                if (ProcessingThread.CancellationPending)
                {
                    return;
                }

                ProcessingThread.ReportProgress(0, "Running automation for appt: " + apptid.ToString() + ".");

                /***********************  Get Unitnum & set active patient  ********************/
                string unitnum         = "";
                ParameterCollection pc = new ParameterCollection("apptID", apptid);
                using (reader = BCDB2.Instance.ExecuteReaderSPWithParams("sp_3_GetUnitnum", pc))
                //ExecuteReader("SELECT unitnum FROM tblAppointments WHERE apptID = " + apptid))
                {
                    if (reader != null && reader.Read())
                    {
                        unitnum = reader.GetValue(0).ToString();
                    }
                }

                //StatusReport sr = new StatusReport();
                //sr.apptid = apptid;
                //sr.description = "Started Automation cycle";
                //ProcessingThread.ReportProgress(300, sr);

                //StatusReport sr = (StatusReport)e.UserState;
                //if (status != null)
                //{
                try
                {
                    //temp debug
                    //status.LogStatus(this.Text,
                    //         "Automation",
                    //         "Ok",
                    //         "tarted Automation cycle " + apptid.ToString());
                }
                catch (Exception ex)
                {
                    Logger.Instance.WriteToLog(ex.ToString());
                }
                //}
                SessionManager.Instance.SetActivePatientNoCallback(unitnum, (int)apptid);

                /***********************  Risk Calculations   ********************/
                try
                {
                    ProcessingThread.ReportProgress(1,
                                                    "Running risk calculations for appointment: " + apptid.ToString() +
                                                    ".");
                    SessionManager.Instance.GetActivePatient().RecalculateRisk();
                }
                catch (Exception e)
                {
                    ProcessingThread.ReportProgress(1,
                                                    "Risk calculations FAILED for appointment: " + apptid.ToString() +
                                                    ". " + e.ToString());
                }

                /***********************  Update BigQueue   ********************/
                try
                {
                    ProcessingThread.ReportProgress(1, "Updating BigQueue for appointment: " + apptid.ToString() + ".");
                    pc = new ParameterCollection("unitnum", unitnum);
                    BCDB2.Instance.RunSPWithParams("sp_3_populateBigQueue", pc);
                }
                catch (Exception e)
                {
                    ProcessingThread.ReportProgress(1,
                                                    "Updating BigQueue FAILED for appointment: " + apptid.ToString() +
                                                    ". " + e.ToString());
                }

                /***********************  Process Queue Documents    ********************/
                ProcessingThread.ReportProgress(1,
                                                "Processing Queue Documents for appointment: " + apptid.ToString() + ".");
                pc = new ParameterCollection("apptID", apptid);
                BCDB2.Instance.RunSPWithParams("sp_processQueueDocuments", pc);



                /***********************  Process Automation Save Documents    ********************/
                ProcessingThread.ReportProgress(1,
                                                "Processing Auto Save Documents: " + apptid.ToString() + ".");
                ApptUtils.saveAutomationDocumentsToPrintQueue(apptid);


                /***********************  Run Automation Stored Procedures    ********************/
                ProcessingThread.ReportProgress(1,
                                                "Run Automation Stored Procedures  : " + apptid.ToString() + ".");

                ApptUtils.runAutomationStoredProcedures(apptid);

                /***********************  export HL7 files    ********************/
                ProcessingThread.ReportProgress(1,
                                                "Export HL7 File: " + apptid.ToString() + ".");
                RiskService.exportHL7File(apptid);

                /***********************  Print Documents   ********************/
                try
                {
                    ProcessingThread.ReportProgress(1, "Printing documents for appointment: " + apptid.ToString() + ".");
                    ParameterCollection printDocArgs = new ParameterCollection();
                    printDocArgs.Add("apptid", apptid);
                    reader = BCDB2.Instance.ExecuteReaderSPWithParams("sp_AutomationHtmlDocsToPrint", printDocArgs);

                    int    templateID = -1;
                    string printer    = "";

                    while (reader.Read())
                    {
                        if (reader.IsDBNull(0) == false)
                        {
                            templateID = reader.GetInt32(0);
                        }
                        if (reader.IsDBNull(1) == false)
                        {
                            printer = reader.GetString(1);
                        }

                        if (templateID > 0)
                        {
                            if (string.IsNullOrEmpty(printer) == false)
                            {
                                if (printer.ToUpper() != "NO_PRINT")
                                {
                                    ProcessingThread.ReportProgress(1,
                                                                    "Printing templateID " + templateID.ToString() +
                                                                    " for apptID " + apptid.ToString() + ".");
                                    HtmlDocument hdoc = new HtmlDocument(templateID, unitnum, apptid);
                                    hdoc.targetPrinter = printer;
                                    hdoc.apptid        = apptid;
                                    htmlInProgress     = true;


                                    //try
                                    //{
                                    //    ////temp debug
                                    //    //status.LogStatus(this.Text,
                                    //    //                 "Automation",
                                    //    //                 "Ok",
                                    //    //                 "Appt " + hdoc.apptid.ToString() + " Sent doc " + hdoc.template.documentTemplateID.ToString() + " to " + hdoc.targetPrinter);
                                    //}
                                    //catch (Exception ex) { Logger.Instance.WriteToLog(ex.ToString()); }

                                    if (status != null)
                                    {
                                        try
                                        {
                                            status.LogStatus(this.Text,
                                                             "Automation",
                                                             "Ok",
                                                             "Appt " + hdoc.apptid.ToString() + " Sent doc " +
                                                             hdoc.template.documentTemplateID.ToString() + " to " +
                                                             hdoc.targetPrinter);
                                        }
                                        catch (System.Web.Services.Protocols.SoapException e)
                                        {
                                            //do nothing
                                        }
                                        catch (Exception ex)
                                        {
                                            Logger.Instance.WriteToLog(ex.ToString());
                                        }
                                    }


                                    ProcessingThread.ReportProgress(100, hdoc);
                                    while (htmlInProgress)
                                    {
                                        Thread.Sleep(100);
                                    }

                                    string sqlStr =
                                        "INSERT INTO tblDocuments([apptID],[documentTemplateID],[created],[createdBy]) VALUES(" +
                                        hdoc.apptid.ToString() + "," + hdoc.template.documentTemplateID + "," + "'" +
                                        DateTime.Now +
                                        "','AUTOMATION');";

                                    BCDB2.Instance.ExecuteNonQuery(sqlStr);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    ProcessingThread.ReportProgress(1,
                                                    "Printing FAILED for appointment: " + apptid.ToString() + ". " +
                                                    e.ToString());
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
                /***********************  Mark as printed to complete automation   ********************/
                try
                {
                    String sqlStr = "UPDATE tblRiskData SET printed = 1 WHERE apptid = " + apptid.ToString() + ";";
                    BCDB2.Instance.ExecuteNonQuery(sqlStr);
                }
                catch (Exception e)
                {
                    ProcessingThread.ReportProgress(1,
                                                    ("Automation - unable to update appt id=" + apptid.ToString() +
                                                     " printed=1.\n" + e.ToString()));
                }

                ProcessingThread.ReportProgress(200, "");
            }
        }
Esempio n. 3
0
        private void loginButton_Click(object sender, EventArgs e)
        {
            string lockoutMsg = "";
            User   u          = null;
            bool   validUser  = users.Any(x => ((User)x).userLogin.ToLower() == usernameTextBox.Text.ToLower());

            if (validUser)
            {
                u = (User)(users.First(x => ((User)x).userLogin.ToLower() == usernameTextBox.Text.ToLower()));
            }

            // begin jdg 10/30/15
            NameValueCollection values = Configurator.GetConfig("AppSettings");

            if (values != null)
            {
                LDAPSecurityContext = values["SecurityContext"];
            }
            if (String.IsNullOrEmpty(LDAPSecurityContext))
            {
                LDAPSecurityContext = "Off";
            }
            bool bLDAPSuccess = false;
            bool bLDAP        = (((LDAPSecurityContext.ToUpper() == "MACHINE") || (LDAPSecurityContext.ToUpper() == "DOMAIN")) ? true : false);

            try
            {
                if (bLDAP)
                {
                    switch (LDAPSecurityContext.ToUpper())
                    {
                    case "MACHINE":
                        using (var context = new PrincipalContext(ContextType.Machine))
                        {
                            if (context.ValidateCredentials(usernameTextBox.Text, passwordTextBox.Text))
                            {
                                bLDAPSuccess = true;
                            }
                        }
                        break;

                    case "DOMAIN":
                        using (var context = new PrincipalContext(ContextType.Domain))
                        {
                            if (context.ValidateCredentials(usernameTextBox.Text, passwordTextBox.Text))
                            {
                                bLDAPSuccess = true;
                            }
                        }
                        break;

                    default:

                        break;
                    }
                }
            }
            catch (Exception excLDAP)
            {
                RiskApps3.Utilities.Logger.Instance.WriteToLog("LDAP Authentication failed for user " + usernameTextBox.Text + " for this reason: " + excLDAP.ToString());
            }
            // end jdg 10/30/15

            String encryptedPassword = RiskAppCore.User.encryptPassword(passwordTextBox.Text);

            bool authenticated     = false;
            int  numFailedAttempts = 0;
            int  numMaxFailures    = 5;
            int  lockoutPeriod     = 0;

            lockoutMsg = "";

            Utilities.ParameterCollection pc = new Utilities.ParameterCollection();
            pc.Add("ntLoginName", DBUtils.makeSQLSafe(ntUser));
            pc.Add("userLogin", DBUtils.makeSQLSafe((u != null) ? u.userLogin : usernameTextBox.Text));

            //if (SessionManager.Instance.MetaData.Globals.encryptPasswords)
            if ((SessionManager.Instance.MetaData.Globals.encryptPasswords) && (!bLDAP))
            {
                pc.Add("userPassword", DBUtils.makeSQLSafe(encryptedPassword));
            }
            else
            {
                pc.Add("userPassword", DBUtils.makeSQLSafe(passwordTextBox.Text));
            }
            // begin jdg 10/30/15
            pc.Add("bLDAP", (bLDAP ? 1 : 0));
            pc.Add("bLDAPSuccess", (bLDAPSuccess ? 1 : 0));
            // end jdg 10/30/15

            SqlDataReader reader = BCDB2.Instance.ExecuteReaderSPWithParams("sp_Authenticate_User", pc);

            if (reader != null)
            {
                if (reader.Read())
                {
                    authenticated     = (bool)reader.GetSqlBoolean(0);
                    numFailedAttempts = (int)reader.GetInt32(1);
                    numMaxFailures    = (int)reader.GetInt32(2);
                    lockoutPeriod     = (int)reader.GetInt32(3);
                }
                reader.Close();
            }
            if ((!validUser) || (!authenticated))  //note that if they're not a valid user they won't be authenticated, but we've updated the failed count and timeout values
            {
                if (lockoutPeriod > 0)
                {
                    lockoutMsg = "\r\nLogin attempts will be blocked for " + lockoutPeriod.ToString() + " minute" + ((lockoutPeriod > 1) ? "s." : ".");
                }
                else
                {
                    lockoutMsg = "\r\nYou have made " + numFailedAttempts.ToString() + " failed Login attempt" + ((numFailedAttempts > 1) ? "s" : "") + " of a maximum " + numMaxFailures.ToString() + " allowed.";
                }
            }

            if (validUser && authenticated)
            {
                //see if user is forced to change password
                if (!bLDAP) // jdg 10/30/15
                {
                    if (ApplicationUtils.checkPasswordForceChange(u.userLogin))
                    {
                        String username = usernameTextBox.Text;
                        SessionManager.Instance.MetaData.Users.BackgroundListLoad();
                        passwordTextBox.Text = "";
                        usernameTextBox.Text = username;
                        this.DialogResult    = System.Windows.Forms.DialogResult.None;
                        return;
                    }

                    if (ApplicationUtils.checkPasswordDateOK(u.userLogin) == false)
                    {
                        String username = usernameTextBox.Text;
                        SessionManager.Instance.MetaData.Users.BackgroundListLoad();
                        passwordTextBox.Text = "";
                        usernameTextBox.Text = username;
                        this.DialogResult    = System.Windows.Forms.DialogResult.None;
                        return;
                    }
                }
                roleID   = RiskAppCore.User.fetchUserRoleID(u.userLogin);
                roleName = RiskAppCore.User.fetchUserRoleName(u.userLogin);

                switch (roleName)
                {
                case "Tablet":
                    RiskAppCore.ErrorMessages.Show(RiskAppCore.ErrorMessages.ROLE_ACCESS_DENIED);
                    return;

                default:
                    break;
                }
                SessionManager.Instance.ActiveUser = u;
                InitUserGUIPrefs(u);
                u.UserClinicList.user_login = u.userLogin;
                u.UserClinicList.AddHandlersWithLoad(null, UserClinicListLoaded, null);
                //DialogResult = DialogResult.OK;

                HraObject.AuditUserLogin(u.userLogin);

                stopWatch.Stop();
                // Get the elapsed time as a TimeSpan value.
                TimeSpan ts = stopWatch.Elapsed;
                if (ts.TotalSeconds < requiredSplashTime)
                {
                    progressBar1.Style = ProgressBarStyle.Blocks;
                    progressBar1.Value = progressBar1.Maximum;
                    progressBar1.Refresh();
                    Application.DoEvents();
                    Thread.Sleep((int)(1000 * (requiredSplashTime - ts.TotalSeconds)));
                }

                return;
            }

            if (numFailedAttempts == 1)
            {
                MessageBox.Show(
                    "You have provided an incorrect username or password.\r\nPlease correct your password or try a different user." + lockoutMsg,
                    "Incorrect Username/Password",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }
            else if (numFailedAttempts > 1)
            {
                MessageBox.Show(
                    lockoutMsg,
                    "Incorrect Username/Password",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }
            return;
        }
Esempio n. 4
0
        /**************************************************************************************************/
        private void UsersListLoaded(HraListLoadedEventArgs e)
        {
            //don't show and ask for login + password unless not using NT Auth or NT Auth failed
            groupBox1.Visible = false;

            WindowsPrincipal wp      = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            string           strTemp = wp.Identity.Name;
            int intPos = strTemp.IndexOf("\\", 0);

            ntUser = strTemp.Substring(intPos + 1);

            usernameTextBox.Text = ntUser;

            usernameTextBox.Focus();
            usernameTextBox.SelectAll();
            bool userInList = users.IsUserInList(usernameTextBox.Text);

            if (UseNtAuthentication && Configurator.useNTAuthentication() && userInList)
            {
                roleID   = RiskAppCore.User.fetchUserRoleID(usernameTextBox.Text);
                roleName = RiskAppCore.User.fetchUserRoleName(usernameTextBox.Text);

                SessionManager.Instance.ActiveUser = users.GetUser(usernameTextBox.Text);
                InitUserGUIPrefs(SessionManager.Instance.ActiveUser);
                SessionManager.Instance.ActiveUser.UserClinicList.user_login = SessionManager.Instance.ActiveUser.userLogin;
                SessionManager.Instance.ActiveUser.UserClinicList.AddHandlersWithLoad(null, UserClinicListLoaded, null);

                HraObject.AuditUserLogin(ntUser);

                stopWatch.Stop();
                // Get the elapsed time as a TimeSpan value.
                TimeSpan ts = stopWatch.Elapsed;
                if (ts.TotalSeconds < requiredSplashTime)
                {
                    progressBar1.Style = ProgressBarStyle.Blocks;
                    progressBar1.Value = progressBar1.Maximum;
                    progressBar1.Refresh();

                    for (int i = 1; i <= 50; i++)
                    {
                        Application.DoEvents();
                        Thread.Sleep((int)(20 * (requiredSplashTime - ts.TotalSeconds)));
                    }
                }
            }
            else
            {
                groupBox1.Visible    = true;
                progressBar1.Visible = false;
                label12.Visible      = false;
                foreach (User u in users)
                {
                    if (u.userLogin.Equals(ntUser))
                    {
                        usernameTextBox.Tag  = u;
                        usernameTextBox.Text = u.userLogin;
                        break;
                    }
                }

                while (this.Height < 525)
                {
                    this.Height = this.Height + 5;
                    Application.DoEvents();
                }
            }
        }
Esempio n. 5
0
        // if force is true, update tables no matter what the dates are for the last update or the dates of tables on the server
        public static void updateTables(Boolean bForce)
        {
            NameValueCollection values = Configurator.GetConfig("globals");
            string APIServiceActive    = values["APIServiceActive"] ?? "False";

            if (APIServiceActive != "True")
            {
                //don't overwrite any tables and simply return
                return;
            }

            if (!bForce)
            {
                //get the local script date of the most recent script run
                string localDBDate = (string)BCDB2.Instance.ExecuteScalarQuery(@"
                    SELECT TOP (1) scriptDate
	                FROM tblScriptsRun
	                ORDER BY dateRun DESC, scriptDate DESC"    );

                if (!String.IsNullOrEmpty(localDBDate))
                {
                    //test to see if the local DB needs freshening
                    //by comparing the result of the similar script run on the Server
                    string APIGetScriptsRunDateURL = values["APIGetScriptsRunDateURL"] ?? "None";
                    if (APIGetScriptsRunDateURL == "None")
                    {
                        return;
                    }

                    //var jsonScriptsRunDate = new WebClient().DownloadString(APIGetScriptsRunDateURL);
                    //new way: get response w/in 5 seconds or exception out
                    try
                    {
                        var jsonScriptsRunDate = new TimedWebClient(5000).DownloadString(APIGetScriptsRunDateURL);

                        var    jObjScriptsRunDate = (JObject)JsonConvert.DeserializeObject(jsonScriptsRunDate);
                        string scriptsRunDate     = jObjScriptsRunDate.SelectToken("scriptsRunDate").ToObject <string>();
                        //since both dates are char strings in YYYY-MM-DD format, which go from highest to least significant digits,
                        //we can use direct string comparison without bothering to convert to dates
                        if (String.Compare(localDBDate, scriptsRunDate) >= 0)  //local DB is already more recently updated or same as the Service's date
                        {
                            return;
                        }
                    }
                    catch (WebException wex)
                    {
                        Logger.Instance.WriteToLog("[RefreshTables] could not connect to URL " + APIGetScriptsRunDateURL + ":\n\t" + wex.Message);
                        return;
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.WriteToLog("[RefreshTables] could not process response from " + APIGetScriptsRunDateURL + ":\n\t" + ex.Message);
                        return;
                    }
                }
            }

            string APIGetGenTablesURL = values["APIGetGenTablesURL"] ?? "None";

            if (APIGetGenTablesURL == "None")
            {
                return;
            }
            var json = ""; //old way didn't handle firewall issue properly: new WebClient().DownloadString(APIGetGenTablesURL);

            //new way: get response w/in 10 seconds or exception out
            try
            {
                json = new TimedWebClient(10000).DownloadString(APIGetGenTablesURL);
            }
            catch (WebException wex)
            {
                Logger.Instance.WriteToLog("[RefreshTables] could not connect to URL " + APIGetGenTablesURL + ":\n\t" + wex.Message);
                return;
            }

            var jArr = (JArray)JsonConvert.DeserializeObject(json);

            var tableList = jArr.ToObject <object[]>().ToList();

            foreach (JObject jObj in tableList)
            {
                string tableName = jObj.SelectToken("tableName").ToObject <string>();

                var    colNamesList = jObj.SelectToken("colNames").ToObject <string[]>().ToList();
                string colNames     = String.Join(",", colNamesList.ToArray());

                var dataList = jObj.SelectToken("data").ToObject <object[][]>().ToList();
                var dataRows = dataList.ToArray <object[]>();

                DataTable dt = new DataTable(tableName);
                foreach (var c in colNamesList)
                {
                    DataColumn col = new DataColumn();
                    dt.Columns.Add(col);
                }

                // add all rows to DataRowCollection.
                foreach (var r in dataRows)
                {
                    DataRow dr = dt.NewRow();
                    dr.ItemArray = r;
                    dt.Rows.Add(dr);
                }

                //remove existing records in table
                BCDB2.Instance.ExecuteNonQuery("TRUNCATE TABLE " + tableName);

                //insert new data drom Service into table
                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(BCDB2.Instance.getConnectionString()))
                {
                    bulkCopy.DestinationTableName = tableName;
                    try
                    {
                        // Write from the source to the destination.
                        bulkCopy.WriteToServer(dt);
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.WriteToLog("[RefreshTables] could not do SQL bulk copy of table " + tableName + ":\n\t" + ex.Message);
                    }
                }
                Logger.Instance.WriteToLog("RefreshTables successfully updated table " + tableName + " from the Server.");
            }
        }