Example #1
0
    protected void SetUserGridData()
    {


         

        //logFiles.ErrorLog("INTO SET USER GRID: curr group " + CurrentGroupName);

        try
        {
            string groupname = CurrentGroupName;
          
            curgrpname.Text = " Current Group: " + groupname;
            if (CurrentGroupName == "None") return;

            
            setLeadeermsg(username, groupname);


            int groupid = groupManagement.find_group_id(groupname);
            if (groupid < 1)
            {
                ShowErrorMessage(" did not find group " + groupname);
                return;
            }

            string selectQuery = " SELECT distinctrow webmpx.group_members.*  FROM webmpx.group_members WHERE (((Group_members.Groupname)='" + groupname + "')) order by webmpx.group_members.Username asc;";

            using (OdbcConnection connection = new OdbcConnection(ConfigurationManager.ConnectionStrings["MySQLConnStr"].ConnectionString))
            {
                connection.Open();
                using (OdbcCommand command = new OdbcCommand(selectQuery, connection))
                using (OdbcDataAdapter adapter = new OdbcDataAdapter(command))
                {
                    DataTable dt = new DataTable();
                    try
                    {
                        adapter.Fill(dt);
                        dt.DefaultView.Sort = SortExpression;
                        groupmembers.DataSource = dt.DefaultView;
                        groupmembers.DataBind();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Error in getting data using sql query: " + selectQuery + ". " + ex.Message, ex);
                    }
                }
                connection.Close();
            }

        }
        catch (Exception exp)
        {
            logFiles.ErrorLog(exp);
            ShowErrorMessage("An error has occured when reading user data.");

        }
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public int add_model_file(string filePath, string fileName, string fileOwner, int groupid)
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    {
        try
        {
            byte[] rawData  = File.ReadAllBytes(filePath + "\\" + fileName);
            int    fileSize = rawData.Length;

            // other way to get a file to byte array
            //FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            //long fileSize2 = fs.Length;
            //rawData = new byte[fileSize];
            //fs.Read(rawData, 0, (int)fileSize2);
            //fs.Close();

            string groupname;
            groupname = find_group_name(groupid);
            DateTime DateC = DateTime.UtcNow;

            DbUse.RunMySqlParams("INSERT INTO webmpx.group_files (File_name, File_stuff, File_size, File_owner, Group_id, Groupname, Date_created) VALUES (@FileName, @File, @FileSize, @File_owner, @Group_id, @Groupname, @DateC);",
                                 new string[] { "@FileName", "@File", "@FileSize", "@File_owner", "@Group_id", "@Groupname", "@DateC" },
                                 new object[] { fileName, rawData, fileSize, fileOwner, groupid, groupname, DateC });
        }
        catch (Exception ex)
        {
            // show error message...
            LogFiles logFiles = new LogFiles();
            logFiles.ErrorLog(ex);
            return(0);
        }

        return(-1);
    }
Example #3
0
    public static bool OpenAdoMysql(ADODB.Connection conn)
    {
        bool opened;

        // close the connection if it already exists
        CloseAdo(conn);

        try {
            //  gwwd - nont here at start ... conn.DefaultDatabase = "";
            //conn.ConnectionString = "Provider=MySQLProv;Data Source=webmpx; Persist Security Info = False";
            //conn.ConnectionString = "Provider=MySQLProv;" + GetUserDatabaseConnection().ToString();

            /* using (OdbcConnection connection = new OdbcConnection(ConfigurationManager.ConnectionStrings["MySQLConnStr"].ConnectionString)) {
             *  connection.Open();
             * */
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["MySQLConnStr"].ConnectionString;
            conn.Mode             = (ADODB.ConnectModeEnum)ADODB.CursorLocationEnum.adUseServer;
            conn.Open();
            opened = true;
        } catch (Exception e) {
            // MyUtilities.MsgBox("Error in opening database connection: " + conn.ConnectionString + " (" + e.Message + ")");
            opened = false;
            LogFiles logFiles = new LogFiles();
            logFiles.ErrorLog(e);
            //throw new Exception(e.Message);
        }
        return(opened);
    }
Example #4
0
    public static bool RunMysql(string commandString)
    {
        bool   updated     = false;
        string conn_string = GetConnectionString();

        using (MySqlConnection conn = new MySqlConnection(conn_string))
            using (MySqlCommand cmd = conn.CreateCommand()) { //watch out for this SQL injection vulnerability below
                cmd.CommandText = commandString;
                try {
                    conn.Open();
                    try {
                        cmd.ExecuteNonQuery();
                    } catch (Exception exp) {
                        throw new Exception("Error in executing MySql command. Command string: " + commandString + ". Exception message: " + exp.Message, exp);
                    }
                    updated = true;
                } catch (Exception ex) {
                    LogFiles logFiles = new LogFiles();
                    logFiles.ErrorLog(ex);
                } finally {
                    conn.Close();
                }
            }
        return(updated);
    }
    public static bool SameOperNumDiffNameExists(string opName, int opNum, int prodId, int opId, string connectionString, LogFiles logFiles)
    {
        bool exists = false;

        ADODB.Connection conn = new ADODB.Connection();
        ADODB.Recordset  rec  = new ADODB.Recordset();

        opName = opName.ToUpper();

        bool   adoOpen     = DbUse.OpenAdo(conn, connectionString);
        string queryString = "SELECT OpID, OpNam, OpNum, Prodfore FROM tblOper WHERE Prodfore = " + prodId + " AND OpNam <> '" + opName + "' AND OpNum = " + opNum + " AND OpID <> " + opId;
        bool   recOpen     = DbUse.OpenAdoRec(conn, rec, queryString);

        try {
            if (adoOpen && recOpen)
            {
                exists = !rec.EOF;
            }
        } catch (Exception ex) {
            logFiles.ErrorLog(ex);
        } finally {
            DbUse.CloseAdoRec(rec);
            DbUse.CloseAdo(conn);
        }
        return(exists);
    }
Example #6
0
    public static bool RunMySqlParams(string commandString, string[] paramNames, object[] parameters)
    {
        bool   updated;
        string conn_string = GetConnectionString();

        try {
            using (MySqlConnection oleConn = new MySqlConnection(conn_string)) {
                oleConn.Open();
                using (MySqlCommand comm = new MySqlCommand(commandString, oleConn)) {
                    try {
                        for (int i = 0; i < parameters.Length; i++)
                        {
                            comm.Parameters.AddWithValue(paramNames[i], parameters[i]);
                        }
                        comm.ExecuteNonQuery();
                    } catch (Exception ex) {
                        Exception excep = new Exception("Error in executing mysql command. Command string: " + comm.CommandText + ". Exception message: " + ex.Message, ex);
                        throw excep;
                    }
                    oleConn.Close();
                    updated = true;
                }
            }
        } catch (Exception ex) {
            LogFiles logFiles = new LogFiles();
            logFiles.ErrorLog(ex);
            updated = false;
        }
        return(updated);
    }
Example #7
0
    public static bool RunSql(string commandString, string connectionString)
    {
        bool updated;

        try {
            using (OleDbConnection oleConn = new OleDbConnection(connectionString)) {
                oleConn.Open();
                using (OleDbCommand comm = new OleDbCommand(commandString, oleConn)) {
                    try {
                        comm.ExecuteNonQuery();
                    } catch (Exception ex) {
                        Exception excep = new Exception("Error in executing oledb command. Command string: " + comm.CommandText + ". Exception message: " + ex.Message, ex);
                        throw excep;
                    }
                    oleConn.Close();
                    updated = true;
                }
            }
        } catch (Exception ex) {
            LogFiles logFiles = new LogFiles();
            logFiles.ErrorLog(ex);
            updated = false;
        }
        return(updated);
    }
Example #8
0
 public void LogRequest()
 {
     try
     {
         LogFiles logFile = new LogFiles();
         logFile.ErrorLog(Server.MapPath("/Logs/Success/LogUrl"), Request.Url.ToString());
     }
     catch { }
 }
Example #9
0
 public void LogError(string Error)
 {
     try
     {
         LogFiles logFile = new LogFiles();
         logFile.ErrorLog(Server.MapPath("/Log/Error/LogUrl"), "ERROR: " + Error + " >>>URL: " + Request.Url.ToString());
     }
     catch { }
 }
Example #10
0
 public static void CreateRunFile(string userdirPath, string username)
 {
     try {
         using (StreamWriter runFile = new StreamWriter(userdirPath + CalcClass.RUN_FILE, false)) {
             runFile.WriteLine(DateTime.Now.Ticks);
             runFile.Close();
         }
     } catch (Exception ex) {
         LogFiles logFiles = new LogFiles(username);
         logFiles.ErrorLog(ex);
     }
 }
    public bool ChangePassword(string link, string pswdNew)
    {
        bool updated = false;
        int  id      = GetPasswordResetLinkId(link);

        if (id != -1)
        {
            string hash = PasswordHash.PasswordHash.CreateHash(pswdNew);
            updated = DbUse.RunMysql("UPDATE userlog SET usercode = '" + hash + "' WHERE id = " + id + ";");
            if (updated)
            {
                try {
                    string logBody = "Password was changed for\n";
                    logBody += "Username: "******"username", "id", id, "userlist") + "\n";
                    logBody += "User IP: " + System.Web.HttpContext.Current.Request.UserHostAddress + "\n";
                    MailInfo.SendMail(logBody, MailInfo.PASSWORD_RESET_ACTION);
                } catch (Exception ex) {
                    logFiles.ErrorLog(ex);
                }
            }
        }
        return(updated);
    }
Example #12
0
    public static void DeleteCommonRunFile()
    {
        string pathToRunFile = GetMainDirectory() + "Bin\\" + COMMON_RUN_FILE;

        if (FileOperations.WaitForFile(pathToRunFile, 50, 100))
        {
            try {
                File.Delete(pathToRunFile);
            } catch (Exception ex) {
                LogFiles logFiles = new LogFiles();
                logFiles.ErrorLog(ex);
            }
        }
    }
Example #13
0
    public static void CreateDllInProcessFile(string username)
    {
        LogFiles logFiles = new LogFiles();
        string   fullPath = GetMainDirectory() + "Bin\\" + COMMON_RUN_FILE;

        try {
            using (StreamWriter runFile = new StreamWriter(fullPath, false)) {
                runFile.WriteLine(DateTime.Now.Ticks);
                runFile.Close();
            }
            logFiles.ErrorMessageLog("Created common fun file '" + fullPath + "'.");
        } catch (Exception ex) {
            logFiles.ErrorLog(ex);
            throw ex;
        }
    }
    ///////////////////////////////////////////
    public int get_file(int fileId, int groupid, string filePath, string username)
    ///////////////////////////////////////////
    {
        string nfilename;
        string fuldir;

        //  get file with fileid from groupid
        nfilename = get_filename(groupid, fileId);


        //  check for dupl name (add a_ at front if file exists already)
        fuldir = unique_user_filename(nfilename, filePath);

        //  place file into userdir


        using (MySqlConnection conn = new MySqlConnection(DbUse.GetConnectionString()))
        {
            using (MySqlCommand cmd = new MySqlCommand("SELECT File_stuff From Webmpx.group_files WHERE file_id = @fileId;", conn))
            {
                try
                {
                    conn.Open();
                    cmd.Parameters.AddWithValue("@fileId", fileId);
                    MySqlDataReader reader = cmd.ExecuteReader();

                    if (reader.Read())
                    {
                        byte[] fileBytes = (byte[])reader["File_stuff"];
                        File.WriteAllBytes(fuldir, fileBytes);
                    }
                    conn.Close();
                }
                catch (Exception ex)
                {
                    // show error message...
                    LogFiles logFiles = new LogFiles();
                    logFiles.ErrorLog(ex);
                    return(0);
                }
            }
        }

        return(-1);
    }
Example #15
0
    public static bool RunSqlAdo(ADODB.Connection openConn, string queryString)
    {
        object ret;
        bool   success = false;

        try {
            try {
                openConn.Execute(queryString, out ret, 0);
            } catch (Exception ex) {
                throw new Exception("Error in executing ado command. Command string: " + queryString + ". Exception message: " + ex.Message, ex);
            }
            success = true;
        } catch (Exception ex) {
            LogFiles logFiles = new LogFiles();
            logFiles.ErrorLog(ex);
        }
        return(success);
    }
    public static bool DuplicateOperNamesOrNumbers(string connectionString, int prodId)
    {
        bool duplicate = false;

        ADODB.Connection conn     = new ADODB.Connection();
        ADODB.Recordset  rec      = new ADODB.Recordset();
        string           sqlQuery = "SELECT tblOper_1.ProdFore, tblOper.OpNum, tblOper.OpNam FROM tblOper INNER JOIN tblOper AS tblOper_1 ON (tblOper.OpNam = tblOper_1.OpNam) AND (tblOper.ProdFore = tblOper_1.ProdFore) WHERE ((tblOper.OpNum)<[tbloper_1].[opnum])";

        if (prodId > 0)
        {
            sqlQuery += " AND tblOper_1.ProdFore = " + prodId;
        }
        sqlQuery += ";";
        DbUse.OpenAdo(conn, connectionString);
        DbUse.OpenAdoRec(conn, rec, sqlQuery);
        try {
            duplicate = !rec.EOF;
        } catch (Exception exp) {
            LogFiles logFiles = new LogFiles();
            logFiles.ErrorLog(exp);
        } finally {
            DbUse.CloseAdoRec(rec);
        }

        sqlQuery = "SELECT tblOper_1.ProdFore, tblOper.OpNum, tblOper.OpNam FROM tblOper INNER JOIN tblOper AS tblOper_1 ON (tblOper.OpNum = tblOper_1.OpNum) AND (tblOper.ProdFore = tblOper_1.ProdFore) WHERE StrComp(tblOper.OpNam, tbloper_1.OpNam) = 1";
        if (prodId > 0)
        {
            sqlQuery += " AND tblOper_1.ProdFore = " + prodId;
        }
        sqlQuery += ";";
        DbUse.OpenAdoRec(conn, rec, sqlQuery);
        try {
            duplicate = duplicate || !rec.EOF;
        } catch (Exception exp) {
            LogFiles logFiles = new LogFiles();
            logFiles.ErrorLog(exp);
        } finally {
            DbUse.CloseAdoRec(rec);
        }
        DbUse.CloseAdo(conn);
        return(duplicate);
    }
Example #17
0
    public static bool OpenAdo(ADODB.Connection conn, string dbpath)
    {
        bool opened;

        // close the connection if it already exists
        CloseAdo(conn);
        try {
            conn.ConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source  = " + dbpath + "; Persist Security Info = False";
            conn.Mode             = (ADODB.ConnectModeEnum)ADODB.CursorLocationEnum.adUseServer;
            conn.Open();
            opened = true;
        } catch (Exception ex) {
            // MyUtilities.MsgBox("Error in opening database connection: " + conn.ConnectionString + " (" + e.Message + ")");
            LogFiles logFiles = new LogFiles();
            logFiles.ErrorLog(ex);
            opened = false;
            //throw new Exception(e.Message);
        }
        return(opened);
    }
Example #18
0
    public static bool OpenAdoRec(ADODB.Connection globaldb, ADODB.Recordset rec, string connectionString)
    {
        bool opened;

        CloseAdoRec(rec);
        try {
            // Open table.

            rec.CursorType = ADODB.CursorTypeEnum.adOpenDynamic; // all types of movement through Recordset are allowed
            rec.LockType   = ADODB.LockTypeEnum.adLockPessimistic;
            rec.Open(connectionString, globaldb);
            opened = true;
        } catch (Exception ex) {
            // MyUtilities.MsgBox("Error in opening recordset.");
            opened = false;
            LogFiles logFiles = new LogFiles();
            logFiles.ErrorLog(ex);
            //throw new Exception(ex.Message);
        }
        // Response.Write(opened); - for debugging purposes
        return(opened);
    }
Example #19
0
    public static void DeleteRunFile(string userdirPath, string username, bool logSuccess)
    {
        string   pathToRunFile = userdirPath + CalcClass.RUN_FILE;
        LogFiles logFiles      = new LogFiles(username);

        if (FileOperations.WaitForFile(pathToRunFile, 500, 3))
        {
            try {
                File.Delete(pathToRunFile);
                if (logSuccess)
                {
                    logFiles.ErrorMessageLog("Run file deleted successfully.");
                }
            } catch (Exception ex) {
                logFiles.ErrorLog(ex);
            }
        }
        else if (logSuccess)
        {
            logFiles.ErrorMessageLog("Run file '" + pathToRunFile + "' not found for user " + username + ".");
        }
    }
Example #20
0
    public static void SaveGroupFileToDb(string filePath, string fileName, string fileOwner)
    {
        try {
            byte[] rawData  = File.ReadAllBytes(filePath);
            int    fileSize = rawData.Length;

            // other way to get a file to byte array
            //FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            //long fileSize2 = fs.Length;
            //rawData = new byte[fileSize];
            //fs.Read(rawData, 0, (int)fileSize2);
            //fs.Close();

            DbUse.RunMySqlParams("INSERT INTO webmpx.group_files (FileName, File, FileSize, File_owner) VALUES (@FileName, @File, @FileSize, @File_owner);",
                                 new string[] { "@FileName", "@File", "@FileSize", "@File_owner" },
                                 new object[] { fileName, rawData, fileSize, fileOwner });
        } catch (Exception ex) {
            // show error message...
            LogFiles logFiles = new LogFiles();
            logFiles.ErrorLog(ex);
        }
    }
    public static bool SameOperNameNumExists(string opName, int prodId, int opNum, int opId, string connectionString, LogFiles logFiles)
    {
        bool exists = false;

        ADODB.Connection conn = new ADODB.Connection();
        ADODB.Recordset  rec  = new ADODB.Recordset();

        opName = opName.ToUpper();

        bool   adoOpen     = DbUse.OpenAdo(conn, connectionString);
        string queryString = "SELECT OpID, OpNam, OpNum, Prodfore FROM tblOper WHERE Prodfore = " + prodId + " AND OpNam = '" + opName + "' AND OpNum = " + opNum + " AND OpID <> " + opId;
        bool   recOpen     = DbUse.OpenAdoRec(conn, rec, queryString);

        try {
            if (adoOpen && recOpen)
            {
                if (opId != -1)
                {
                    // we actually know  the opid of the record
                    exists = !rec.EOF;
                }
                else
                {
                    // don't know opid - one record it is the one we previously entered, more records - more opers with same name and num
                    if (!rec.EOF)
                    {
                        rec.MoveNext();
                        exists = !rec.EOF;
                    }
                }
            }
        } catch (Exception ex) {
            logFiles.ErrorLog(ex);
        } finally {
            DbUse.CloseAdoRec(rec);
            DbUse.CloseAdo(conn);
        }
        return(exists);
    }
Example #22
0
    public static void SaveGroupFileToDisk(int fileId, string filePath)
    {
        using (MySqlConnection conn = new MySqlConnection(DbUse.GetConnectionString())) {
            using (MySqlCommand cmd = new MySqlCommand("SELECT File From Webmpx.group_files WHERE file_id = @fileId;", conn)) {
                try {
                    conn.Open();
                    cmd.Parameters.AddWithValue("@fileId", fileId);
                    MySqlDataReader reader = cmd.ExecuteReader();

                    if (reader.Read())
                    {
                        byte[] fileBytes = (byte[])reader["File"];
                        File.WriteAllBytes(filePath, fileBytes);
                    }
                    conn.Close();
                } catch (Exception ex) {
                    // show error message...
                    LogFiles logFiles = new LogFiles();
                    logFiles.ErrorLog(ex);
                }
            }
        }
    }
Example #23
0
    public static string GetEmailAddress(string username)
    {
        using (MySqlConnection conn = new MySqlConnection(DbUse.GetConnectionString())) {
            using (MySqlCommand cmd = new MySqlCommand("SELECT userlog.mail FROM userlog INNER JOIN userlist ON userlog.id = userlist.id WHERE username = @username;", conn)) {
                try {
                    conn.Open();
                    cmd.Parameters.AddWithValue("@username", username);
                    MySqlDataReader reader = cmd.ExecuteReader();

                    if (reader.Read())
                    {
                        string mail = reader["mail"].ToString();
                        conn.Close();
                        return(mail);
                    }
                    return(null);
                } catch (Exception ex) {
                    LogFiles logFiles = new LogFiles(username);
                    logFiles.ErrorLog(ex);
                    return(null);
                }
            }
        }
    }
Example #24
0
    public void buttonr1_a_click(Object sender, System.EventArgs e)
    {
        LogFiles logFiles = new LogFiles(this.username);

        logFiles.RunLog();

        if (DbUse.InRunProcess(userDir))
        {
            Master.ShowErrorMessage("Cannot start verification and calculations. The verification and calculations are still in process from the previous run. Please wait.");
            logFiles.DuplicateRunEndLog();
            return;
        }
        CreateRunFile();

        int ret;

        try {
            classE1_1.Open();
            classE1_1.SetBasicModelInfo(); //  sets glngwid etc.

            classE1_1.calc_return = 0;     //0 - none, 1 labor, 2 eq over util, 4 warnings 8 errors


            //-----------------------------------------------------------------

            // count all whatifs to be calculated and write it to the main mysql database
            ADODB.Recordset recWhatifs  = new ADODB.Recordset();
            bool            recOpened   = DbUse.OpenAdoRec(classE1_1.globaldb, recWhatifs, "SELECT tblWhatIf.*, tblWhatIf.recalc  FROM tblWhatIf WHERE FamilyID = 0;");
            int             totalCalc   = 1;
            int             currentCalc = 0;
            while (!recWhatifs.EOF)
            {
                totalCalc++;
                recWhatifs.MoveNext();
            }
            DbUse.CloseAdoRec(recWhatifs);


            DbUse.RunMysql("INSERT INTO usercalc (id) SELECT userlist.id FROM userlist WHERE userlist.sessionid = '" + HttpContext.Current.Session.SessionID + "';");
            DbUse.RunMysql("UPDATE usercalc INNER JOIN userlist ON usercalc.id = userlist.id SET total = " + totalCalc + ", calc = " + currentCalc + ", lastCheck = " + DateTime.Now.Ticks + ", cancel = 0 WHERE userlist.sessionid = '" + HttpContext.Current.Session.SessionID + "';");
            //////////////////////////////////////////////////////////////////////////////////////

            classE1_1.global_runalldone  = false;
            classE1_1.global_initwid     = classE1_1.glngwid;
            classE1_1.errorMessageGlobal = "";

            while (classE1_1.global_runalldone == false)
            {
                classE1_1.calc_return = 0;
                classE1_1.runall_from_display();
            }


            if (classE1_1.global_initwid != classE1_1.glngwid)
            {
                if (classE1_1.global_initwid != 0)
                {
                    classE1_1.LoadBaseCase();
                    ret = classE1_1.LoadWhatIf(classE1_1.global_initwid);
                }
                else
                {
                    classE1_1.LoadBaseCase();
                }
            }
            ;


            //-----------------------------------------------------------------

            MPXRunChoices.SetActiveView(viewResults);
            SetActiveView(2);
            if ((classE1_1.calc_return & CalcClass.ERR_FLAG) > 0)
            {
                resultsMessage = do_calc_msg(classE1_1.calc_return, 0);
            }
            else
            {
                resultsMessage = do_calc_msg(classE1_1.calc_return, 1);
            }

            /*  todaytoday    if ...  public const short LAB_OVER_U = 1;
             *            public const short EQ_OVER_U = 2;
             *   show ....
             *
             */
            string errorsMessage = GetErrorMessage();
            txtResults.Text = resultsMessage;
            txtErrors.Text  = errorsMessage;
            save_errors_results(resultsMessage, errorsMessage);
            pnlResults.Visible = true;
            pnlErrors.Visible  = !errorsMessage.Trim().Equals(String.Empty);


            classE1_1.runsqlado("UPDATE zs0tblWhatif SET display = -1 WHERE WID = " + classE1_1.glngwid + ";");
        } catch (Exception ex) {
            logFiles.ErrorLog(ex);
            Master.ShowErrorMessage("MPX internal error has occured. " + classE1_1.errorMessageGlobal);
        }
        classE1_1.Close();
        DbUse.RunMysql("DELETE usercalc.* FROM usercalc INNER JOIN userlist ON usercalc.id = userlist.id WHERE userlist.sessionid = '" + HttpContext.Current.Session.SessionID + "';");
        DeleteRunFile();
        logFiles.RunEndLog();
    }
Example #25
0
    public int Count;  //  counts # times run then erases database --  nothing in it... a.mdb !!

    public float RunSql2(string str1, short level1)
    {
        //on error GoTo err_RunSql2;

        ADODB.Recordset reccust = null;

        short  ret;
        int    i;
        float  retval;
        string str2;

        retval = -1;

        if (globaldb_a == null)
        {
            try {
                if (!File.Exists("a.xxx"))
                {
                    File.Copy(DbUse.GetMainDirectory() + "App_Data\\" + "a.xxx", varlocal + "a.xxx");
                }
                if (!File.Exists("b.xxx"))
                {
                    File.Copy(DbUse.GetMainDirectory() + "App_Data\\" + "b.xxx", varlocal + "b.xxx");
                }
            } catch (Exception) { }
            globaldb_a = new ADODB.Connection();
            Count      = 0;
        }
        else
        {
            Count++;
            DbUse.CloseAdo(globaldb_a);
        }
        if (Count > 2000)
        {
            try {
                File.Copy("b.xxx", "a.xxx", true);
                Count = 0;
            } catch (Exception) {
            }
        }
        DbUse.open_ado(ref globaldb_a, "a.xxx");

        //  DOES A CONVERSION OF AN EXPRESSION (6+7*4) TO A NUMBER...

        if ((str1.Trim() == "'") | (str1.Trim() == ".") | (str1.Trim() == ","))
        {
            retval = (float)0.0;
            return(retval);
        }

        str2 = "SELECT tbldummy.GeneralID, " + str1 + " AS a1 FROM tbldummy;";
        DbUse.open_ado_rec(globaldb_a, ref reccust, str2);


        try
        {
            // xxx  tomorrow  on run times  += <> /()*.,   no  '"?:;[]{}|&!@#$%^&    NO: [0-31]  33-39  42 58,59 63 64 91-96  123-127
            retval = (float)(double.Parse(reccust.Fields["a1"].Value.ToString()));
        }
        catch (Exception e)
        {    // ERRORMSG tomorrow
             //MyUtilities.MsgBox("Error in solving Operation Time/Data Equation:  " + conn.ConnectionString + " (" + e.Message + ")");


            string str3;
            str3 = e.Message;
            //retval = (float) -777.0;
            retval = float.NaN;
        } finally {
            DbUse.CloseAdoRec(reccust);
            DbUse.CloseAdo(globaldb_a);

            //gwwdd  adding error here !!!
            if (float.IsNaN(retval) || retval < -100)
            {
                try {
                    DbUse.open_ado_rec(globaldb, ref reccust, "zstblerrors");
                    reccust.AddNew();

                    if (Oper_err_id > 0)
                    {
                        reccust.Fields["Level"].Value = 0; // Error;
                        calc_return |= ERR_FLAG;
                        reccust.Fields["Table"].Value = "Operations";
                        string errorMsg = " Product " + Part_err_name + " Operation " + Oper_err_name + " has an operation time which is not a number. ";
                        if (!inOperRoutingPages)
                        {
                            errorMsg += "Go to Product Operations/Routing Page, hit the [Show Real Times] button and look for field value NaN.";
                        }
                        else
                        {
                            errorMsg += "Look for field value NaN.";
                        }
                        reccust.Fields["Text"].Value    = errorMsg;
                        reccust.Fields["mpxFlag"].Value = -1;
                        reccust.Fields["partid"].Value  = Part_err_id;
                        reccust.Fields["operid"].Value  = Oper_err_id;
                        reccust.Fields["Wid"].Value     = glngwid;
                        reccust.Update();
                    }
                    else
                    {                                      //  ROUTING DATA ERROR.
                        reccust.Fields["Level"].Value = 0; // Error;
                        calc_return |= ERR_FLAG;
                        reccust.Fields["Table"].Value = "Routing";
                        string errorMsg = " Product " + Part_err_name + " FROM Operation " + Oper_err_name + " has an % routing value that is not a number. ";
                        if (!inOperRoutingPages)
                        {
                            errorMsg += "Go to Product Operations/Routing Page, Scroll down to the ROUTING AREA hit the [Show Real Percentage] button and Look for field value NaN. ";
                        }
                        else
                        {
                            errorMsg += "Look for field value NaN.";
                        }
                        reccust.Fields["Text"].Value    = errorMsg;
                        reccust.Fields["mpxFlag"].Value = -1;
                        reccust.Fields["partid"].Value  = Part_err_id;
                        reccust.Fields["operid"].Value  = -1 * Oper_err_id;
                        reccust.Fields["Wid"].Value     = glngwid;
                        reccust.Update();
                    }
                } catch (Exception exp) {
                    LogFiles logFiles = new LogFiles(this.username);
                    logFiles.ErrorLog(exp);
                } finally {
                    DbUse.CloseAdoRec(reccust);
                }
            }
        }

        return(retval);

        //err_RunSql2:

        /*if (level1 == 1)
         * {
         *  retval = -999;
         *  return retval; //exit  Function;
         * };*/
        /*   if ((Err.Number == 3075))
         * {
         *     //parathesis problem;
         *     // msgbox("Error in evaluating string " + str1 + " Parathesis Problem? " + ErrorToString() + " Using -999 as the value", 0, appl_name);
         *
         *     //unsolved parameter;
         *     // msgbox("Error in evaluating string " + str1 + " Unresolved Parameter? " + ErrorToString() + " Using -999 as the value", 0, appl_name);
         *
         *     //divide by zero error;
         *     // msgbox("Error in evaluating string " + str1 + " Divide by zero error? " + ErrorToString() + " Using -999 as the value", 0, appl_name);
         *
         *     //a parameter has a null value. Check 'switch' and 'iif';
         *     // msgbox("Error in evaluating string " + str1 + " Null value! iif or Switch Problem? " + ErrorToString() + " Using -999 as the value", 0, appl_name);
         *
         *     // msgbox("Error in evaluating string " + str1 + " Unknown Problem? " + ErrorToString() + " Using -999 as the value", 0, appl_name);
         *     retval = -999;
         *     return retval; //exit  Function;
         * };
         */
        //retval = -999;
        //return retval;
        //RESUME NEXT
    } // end function;
    public static CalculationResult CalculateResults(ClassF classE1_1)
    {
        LogFiles logFiles = new LogFiles(classE1_1.username);

        if (DbUse.InRunProcess(classE1_1.varlocal, true))
        {
            logFiles.DuplicateRunEndLog();
            throw new Exception("Cannot start verification and calculations. The verification and calculations are still in process from the previous run. Please wait.");
        }


        DbUse.RunMysql("INSERT INTO usercalc (id) SELECT userlist.id FROM userlist WHERE userlist.sessionid = '" + HttpContext.Current.Session.SessionID + "';");
        DbUse.RunMysql("UPDATE usercalc INNER JOIN userlist ON usercalc.id = userlist.id SET total = 1, calc = 1, lastCheck = " + DateTime.Now.Ticks + ", cancel = 0 WHERE userlist.sessionid = '" + HttpContext.Current.Session.SessionID + "';");
        DbUse.CreateRunFile(classE1_1.varlocal, classE1_1.username);
        classE1_1.Open();
        classE1_1.SetBasicModelInfo(); //  sets glngwid etc.

        classE1_1.calc_return = 0;     //0 - none, 1 labor, 2 eq over util, 4 warnings 8 errors

        string errorsMessage  = "";
        string resultsMessage = "";

        try
        {
            classE1_1.RunDLL();
            if (!classE1_1.errorMessageGlobal.Equals(""))
            {
                string errorMessageGlobal = classE1_1.errorMessageGlobal;
                classE1_1.errorMessageGlobal = "";
                throw new Exception("The calculations were unsuccessful. " + errorMessageGlobal);
            }

            if ((classE1_1.calc_return & CalcClass.ERR_FLAG) > 0)
            {
                resultsMessage = do_calc_msg(classE1_1.calc_return, 0);
            }
            else
            {
                resultsMessage = do_calc_msg(classE1_1.calc_return, 1);
            }
            errorsMessage = GetErrorMessage(classE1_1);
            save_errors_results(classE1_1, resultsMessage, errorsMessage);
            classE1_1.runsqlado("UPDATE zs0tblWhatif SET display = -1 WHERE WID = " + classE1_1.glngwid + ";");
            classE1_1.Close();
        }
        catch (Exception ex)
        {
            logFiles.ErrorLog(ex);
            classE1_1.Close();
            DbUse.DeleteRunFile(classE1_1.varlocal, classE1_1.username);
            logFiles.RunEndLog();
            DbUse.RunMysql("DELETE usercalc.* FROM usercalc INNER JOIN userlist ON usercalc.id = userlist.id WHERE userlist.sessionid = '" + HttpContext.Current.Session.SessionID + "';");
            throw new Exception("MPX internal error has occured in calculations. Cannot calculate results. " + classE1_1.errorMessageGlobal);
        }
        DbUse.DeleteRunFile(classE1_1.varlocal, classE1_1.username);
        DbUse.RunMysql("DELETE usercalc.* FROM usercalc INNER JOIN userlist ON usercalc.id = userlist.id WHERE userlist.sessionid = '" + HttpContext.Current.Session.SessionID + "';");

        logFiles.RunEndLog();
        CalculationResult calcResult = new CalculationResult(resultsMessage, errorsMessage);

        return(calcResult);
    }
    //  delete group
    /// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public int delete_group(string groupname, string username)
    {
        /// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        int val;

        val = -1;


        int groupid = find_group_id(groupname);

        //  check check if leader !!!
        //  check if user has group leader authority
        if (has_group_leader(groupname, username) == 0)
        {
            return(0);
        }

        try {
            string message = String.Format("User {0} deleting group '{1}' .\n", username, System.Web.HttpContext.Current.Request.UserHostAddress, DbUse.DomainPath);
            //  mail to usr , all memebers of group and admin
            // TODO add mail addresses
            MailInfo.SendMail(message, MailInfo.GROUP_DELETED);
        } catch (Exception exp) {
            logFiles.ErrorLog(exp);
        }

        // delele membrs list
        string deleteQuery;

        if (!DbUse.RunMySqlParams("DELETE webmpx.group_members.* FROM webmpx.group_members WHERE (((Group_members.Groupname)= '" + groupname + "' ));",
                                  new string[] { }, new object[] {  }))
        {
            return(0);
        }



        //   xxx  delete members ?
        //       xx  flipLeader
        //           delete username from group

        //delete files
        deleteQuery = "DELETE webmpx.group_files.*  From Webmpx.group_files WHERE (((group_files.Groupname)= '" + groupname + "' ));";
        DbUse.RunMySqlParams(deleteQuery, new string[] {  }, new object[] { });


        //delete group
        deleteQuery = "DELETE webmpx.group_list.* FROM webmpx.group_list WHERE (((Group_list.Group_id)= @groupid ));";
        DbUse.RunMySqlParams(deleteQuery, new string[] { "@groupid" }, new object[] { groupid });



        try {
            string message = String.Format("User {0} deleted group '{1}' successfully.\n", username, System.Web.HttpContext.Current.Request.UserHostAddress, DbUse.DomainPath);
            MailInfo.SendMail(message, MailInfo.GROUP_DELETED);
        } catch (Exception exp) {
            logFiles.ErrorLog(exp);
        }



        return(val);
    }