Ejemplo n.º 1
0
        /// <summary>
        /// Process a command line to grant a user a privilege
        /// </summary>
        /// <param name="commandLine"></param>et
        /// <returns></returns>

        public static string GrantPrivilege(
            string commandLine)
        {
            if (UserInfo == null || !IsAdministrator(UserInfo.UserName))
            {
                return("You must be an administrator to grant privileges");
            }

            Lex lex = new Lex();

            lex.OpenString(commandLine);
            string priv     = lex.Get();
            string userName = lex.Get();

            if (Lex.Eq(userName, "to"))
            {
                userName = lex.Get();
            }
            if (priv == "" || userName == "")
            {
                return("Syntax: GRANT privilege TO userid");
            }
            if (!PrivilegesMx.IsValidPrivilegeName(priv))
            {
                return(priv + " is not a valid privilege");
            }
            if (!UserExists(userName))
            {
                return("User " + userName + " doesn't exist");
            }
            GrantPrivilege(userName, priv);
            return("Privilege granted");
        }
Ejemplo n.º 2
0
/// <summary>
/// Format internal form of advanced expression
/// </summary>
/// <param name="advExpr"></param>
/// <param name="q"></param>

        string  FormatAdvancedExpr(
            string advExpr,
            out Query q)
        {
            QueryTable  qt;
            QueryColumn qc;
            MetaTable   mt;
            MetaColumn  mc;

            string extExpr = advExpr;             // copy internal form to external

            q = new Query();

            Lex lex = new Lex();

            lex.OpenString(advExpr);
            while (true)
            {
                string tok = lex.Get();
                if (tok == "")
                {
                    break;
                }
                if (Lex.IsQuoted(tok, '"'))
                {
                    tok = tok.Substring(1, tok.Length - 2).Trim();
                    mc  = MetaColumn.ParseMetaTableMetaColumnName(tok);
                    if (mc == null)
                    {
                        continue;                                 // not found, may be typo, ignore for now
                    }
                    mt = mc.MetaTable;
                    if (q.GetQueryTableByName(mt.Name) == null)
                    {
                        q.AddQueryTable(new QueryTable(mt));
                    }

                    string tok2 = mt.Name + "." + mc.Label;
                    extExpr = extExpr.Replace(tok, tok2);
                }
            }

// Add any other tables from base query for convenience

            Query q2 = QueriesControl.BaseQuery;

            if (q2 != null)
            {
                foreach (QueryTable qt0 in q2.Tables)
                {
                    qt = q.GetQueryTableByName(qt0.MetaTable.Name);
                    if (qt == null)
                    {
                        q.AddQueryTable(qt0.Clone());
                    }
                }
            }

            return(extExpr);            // return external form
        }
Ejemplo n.º 3
0
/// <summary>
/// Constructor given a string of numbers
/// </summary>
/// <param name="cnList"></param>

        public CidList(
            string cnList)
        {
            if (cnList == null)
            {
                return;
            }

            Lex lex = new Lex();

            lex.SetDelimiters(",");
            lex.OpenString(cnList);

            while (true)
            {
                string tok = lex.Get();
                if (tok == "")
                {
                    break;
                }
                if (tok == ",")
                {
                    continue;
                }
                this.Add(tok);
            }
        }
Ejemplo n.º 4
0
/// <summary>
/// Parse external format advanced expression into internal form
/// </summary>
/// <param name="advExprExt"></param>
/// <param name="mcList"></param>
/// <returns></returns>

        string ParseAdvancedExpr(
            string advExprExt,
            out List <MetaColumn> mcList)
        {
            MetaTable  mt;
            MetaColumn mc;

            string advExpr = advExprExt;             // copy external to internal

            mcList = new List <MetaColumn>();

            Lex lex = new Lex();

            lex.OpenString(advExprExt);
            while (true)
            {
                string tok = lex.Get();
                if (tok == "")
                {
                    break;
                }
                if (Lex.IsQuoted(tok, '"'))
                {
                    tok = tok.Substring(1, tok.Length - 2).Trim();                     // remove quotes
                    int i1 = tok.IndexOf('.');
                    if (i1 < 0)
                    {
                        throw new Exception("Invalid table.field name: " + tok);
                    }
                    string table  = tok.Substring(0, i1);
                    string column = tok.Substring(i1 + 1);
                    mt = MetaTableCollection.Get(table);
                    if (mt == null)
                    {
                        throw new Exception("Unknown table name: " + table);
                    }

                    mc = mt.GetMetaColumnByLabel(column);
                    if (mc == null)
                    {
                        mc = mt.GetMetaColumnByName(column);
                    }
                    if (mc == null)
                    {
                        throw new Exception("Unknown column name: " + column);
                    }

                    string tok2 = mt.Name + "." + mc.Name;                     // store as internal name
                    advExpr = advExpr.Replace(tok, tok2);

                    if (!mcList.Contains(mc))
                    {
                        mcList.Add(mc);
                    }
                }
            }

            return(advExpr);            // return internal form
        }
Ejemplo n.º 5
0
        static bool GetKeyValuePair(
            Lex lex,
            out string key,
            out string value)
        {
            key   = lex.Get();
            value = null;
            if (String.IsNullOrEmpty(key))
            {
                return(false);
            }
            lex.GetExpected("=");
            value = lex.Get();

            key   = Lex.RemoveAllQuotes(key).Trim();
            value = Lex.RemoveAllQuotes(value).Trim();
            return(true);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Return list of MetaColumns
        /// </summary>
        /// <returns></returns>

        public List <MetaColumn> GetInputMetaColumnList()
        {
            int mci;

            List <MetaColumn> mcList = new List <MetaColumn>();

            if (CalcType == CalcTypeEnum.Basic)
            {
                foreach (CalcFieldColumn cfc in CfCols)
                {
                    if (cfc != null && cfc.MetaColumn != null)
                    {
                        mcList.Add(cfc.MetaColumn);
                    }
                }
            }

            else if (CalcType == CalcTypeEnum.Advanced)
            {
                Lex lex = new Lex();
                lex.OpenString(AdvancedExpr);
                while (true)
                {
                    string tok = lex.Get();
                    if (tok == "")
                    {
                        break;
                    }
                    if (!Lex.IsQuoted(tok, '"'))
                    {
                        continue;
                    }
                    tok = Lex.RemoveDoubleQuotes(tok);
                    MetaColumn mc = MetaColumn.ParseMetaTableMetaColumnName(tok);
                    if (mc == null)
                    {
                        continue;
                    }
                    for (mci = 0; mci < mcList.Count; mci++)
                    {
                        if (mcList[mci] == mc)
                        {
                            break;
                        }
                    }

                    if (mci >= mcList.Count)
                    {
                        mcList.Add(mc);
                    }
                }
            }

            return(mcList);
        }
Ejemplo n.º 7
0
        bool Cancelled = false;              // set to true if processing cancelled

/// <summary>
/// Main entrypoint for plugin
/// </summary>
/// <param name="args"></param>
/// <returns></returns>

        public string Run(
            string args)
        {
            DialogResult dr;

            try
            {
                Lex lex = new Lex();
                if (args == null)
                {
                    args = "";
                }
                lex.OpenString(args);
                string cmd   = lex.Get();
                string args2 = lex.GetRestOfLine().Trim();

                if (cmd == "" || Lex.Eq(cmd, "ShowDialog"))
                {
                    QbUtil.SetMode(QueryMode.Build);                     // be sure in build mode
                    dr = Instance.ShowDialog(args2);
                    if (dr == DialogResult.OK)
                    {
                        cmd = "Command RunQuery";                         // pass command back to main level
                        return(cmd);
                    }
                    else
                    {
                        return("");
                    }
                }

                else if (Lex.Eq(cmd, "ShowPopup"))
                {
                    if (Lex.IsUndefined(args2))
                    {
                        throw new Exception("Syntax: TargetResultsViewer ShowPopup <CorpId>");
                    }
                    ShowPopup(args2);
                    return("");
                }

                else
                {
                    throw new Exception("Invalid command: " + cmd);
                }
            }

            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
Ejemplo n.º 8
0
/// <summary>
/// Disable user
/// </summary>
/// <param name="commandLine"></param>
/// <returns></returns>

        public static string DisableUser(
            string commandLine)
        {
            string tok, msg;

            UserInfo ui  = new UserInfo();
            Lex      lex = new Lex();

            lex.OpenString(commandLine);
            string userName    = lex.Get();
            bool   interactive = Lex.IsNullOrEmpty(userName);

            while (true)
            {
                if (interactive)
                {
                    userName = InputBoxMx.Show("Enter the Username of the user to disable:", "Disable User", userName);
                    if (Lex.IsNullOrEmpty(userName))
                    {
                        return("");
                    }
                }

                userName = userName.ToUpper();
                if (Security.ReadUserInfo(userName) == null)
                {
                    msg = "User doesn't exist: " + userName;
                    if (!interactive)
                    {
                        return(msg);
                    }
                    MessageBoxMx.ShowError(msg);
                    continue;
                }

                try
                {
                    Security.RevokePrivilege(userName, "Logon");
                    msg = "User disabled: " + userName;
                }
                catch (Exception ex) { msg = "Disable user failed for: " + userName; }
                if (!interactive)
                {
                    return(msg);
                }

                MessageBoxMx.Show(msg);
                userName = "";
                continue;
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Process command line to revoke a user privilege
        /// </summary>
        /// <param name="commandLine"></param>
        /// <returns></returns>

        public static string RevokePrivilege(
            string commandLine)
        {
            if (UserInfo == null || !IsAdministrator(UserInfo.UserName))
            {
                return("You must be an administrator to revoke privileges");
            }

            Lex lex = new Lex();

            lex.OpenString(commandLine);

            string priv     = lex.Get();
            string userName = lex.Get();

            if (Lex.Eq(userName, "from"))
            {
                userName = lex.Get();
            }
            if (priv == "" || userName == "")
            {
                return("Syntax: REVOKE privilege FROM userid");
            }
            if (!PrivilegesMx.IsValidPrivilegeName(priv))
            {
                return(priv + " is not a valid privilege");
            }
            if (!UserExists(userName))
            {
                return("User " + userName + " doesn't exist");
            }
            if (!HasPrivilege(userName, priv))
            {
                return("User " + userName + " doesn't have this privilege");
            }
            RevokePrivilege(userName, priv);
            return("Privilege revoked");
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Commandline command to analyse usage data
        /// </summary>
        /// <param name="commandLine"></param>
        /// <returns></returns>

        public static string AnalyzeUsageData(
            string commandArgs)
        {
            string      currentUserid = "";
            DateTime    startTime = DateTime.MinValue, finishTime;
            int         count, pass, n, rowCount = 0;
            int         i1, i2;
            string      txt, rec, buf;
            string      sql, sqlmsg, stmt, table;
            int         objid, curobj, emp_id;
            int         noMatchingBegin = 0;
            DbCommandMx drd;

            Lex lex = new Lex();

            lex.OpenString(commandArgs);
            string startDate  = lex.Get();
            string endDate    = lex.Get();
            string startDate2 = DateTimeMx.Normalize(startDate);
            string endDate2   = DateTimeMx.Normalize(endDate);

            if (startDate2 == null || endDate2 == null)
            {
                throw new Exception("Syntax: Analyze Usage Data <start_date> <end_date>");
            }

            startDate2 = "to_date('" + startDate2 + "','YYYYMMDD')";
            endDate2   = "to_date('" + endDate2 + " 235959','YYYYMMDD HH24MISS')";

            string where = "where crt_dt between " + startDate2 + " and " + endDate2;

            string arg = lex.Get();

            if (Lex.Eq(arg, "DumpUsageData"))
            {
                return(DumpUsageData(where));
            }

            // Init data

            TableData       = new Hashtable();       // number of times each table accessed
            CommandData     = new Hashtable();       // number of times each command accessed
            TransactionData = new Hashtable();       // count for each transaction type
            UserDataHash    = new Hashtable();       // info on each user, site, department

            // Process usage log records. Find the users for the time period,
            // how many times each user accessed app and the average
            // session time in minutes for each user

            string orderBy = "order by ownr_id, crt_dt";

            drd = UsageDao.Select(where, orderBy);

            UserObject beginUo = new UserObject();

            while (true)
            {
                UserObject uo = UsageDao.Read(drd);
                if (uo == null)
                {
                    drd.Dispose();
                    if (rowCount > 0)
                    {
                        break;
                    }
                    throw new Exception("No data found for specified for time period");
                }

                if (uo.Owner == null || uo.Owner.Trim().Length == 0)
                {
                    continue;                     // skip if owner not specified
                }
                if (rowCount % 1000 == 0)
                {
                    UAL.Progress.Show("Analyzing Usage Data, rows: " + rowCount + " ...", UmlautMobius.String, false);
                }

                rowCount++;

                string eventName = uo.Description;
                string eventData = uo.Content;

                // Increment count on event type

                object o = TransactionData[eventName];
                if (o == null)
                {
                    TransactionData.Add(eventName, 0);
                    count = 0;
                }
                else
                {
                    count = (int)o;
                }
                TransactionData[eventName] = count + 1;

                // Beginning of session?

                if (Lex.Eq(eventName, "Begin"))
                {
                    beginUo       = uo;
                    currentUserid = uo.Owner;
                    startTime     = uo.UpdateDateTime;
                    UserData(currentUserid).Count++;
                }

                else if (Lex.Eq(eventName, "SSS") ||
                         eventName.ToLower().StartsWith("strsrch sss"))
                {
                    UserData(uo.Owner).SsCount++;
                }

                else if (Lex.Eq(eventName, "MSimilar") ||
                         eventName.ToLower().StartsWith("strsrch msimilar"))
                {
                    UserData(uo.Owner).SimCount++;
                }

                else if (eventName.StartsWith("QueryGrid"))                 // get QueryGridAnd, Complex & Or
                {
                    UserData(uo.Owner).QueryCount++;
                }

                else if (Lex.Eq(eventName, "TableStats") && uo.Content != null)
                {
                    string[] sa = uo.Content.Split('\n');
                    for (i1 = 0; i1 < sa.Length; i1++)
                    {
                        if (sa[i1] == null || sa[i1] == "" || sa[i1] == "")
                        {
                            continue;
                        }
                        string[] sa2 = sa[i1].Split('\t');                         // split into table name & count
                        if (sa2.Length != 2)
                        {
                            continue;
                        }
                        o = TableData[sa2[0]];                         // lookup table
                        if (o == null)
                        {
                            TableData.Add(sa2[0], null);
                            count = 0;
                        }
                        else
                        {
                            count = (int)o;
                        }
                        TableData[sa2[0]] = count + Int32.Parse(sa2[1]);
                    }
                }

                else if (Lex.Eq(eventName, "CommandStats") && uo.Content != null)
                {
                    string[] sa = uo.Content.Split('\n');
                    for (i1 = 0; i1 < sa.Length; i1++)
                    {
                        if (sa[i1] == null || sa[i1] == "" || sa[i1] == "")
                        {
                            continue;
                        }
                        string[] sa2 = sa[i1].Split('\t');                         // split into table name & count
                        if (sa2.Length != 2)
                        {
                            continue;
                        }
                        o = CommandData[sa2[0]];                         // lookup table
                        if (o == null)
                        {
                            CommandData.Add(sa2[0], null);
                            count = 0;
                        }
                        else
                        {
                            count = (int)o;
                        }
                        CommandData[sa2[0]] = count + Int32.Parse(sa2[1]);
                    }
                }

                else if (Lex.Eq(eventName, "End"))
                {
                    if (uo.Owner == currentUserid)                     // same user?
                    {
                        UserData(currentUserid).Ended++;

                        TimeSpan elapsed = uo.UpdateDateTime.Subtract(startTime);
                        UserData(currentUserid).TotalTime += elapsed.Minutes;
                    }
                    else
                    {
                        noMatchingBegin++;
                    }

                    currentUserid = "";
                }
            }             // end of main loop

            // Calculate totals

            UserDataVo totalVo = UserData("=Total=");

            foreach (UserDataVo vo in UserDataHash.Values)
            {
                if (vo.Userid == totalVo.Userid)
                {
                    continue;
                }

                totalVo.Users++;
                totalVo.Count      += vo.Count;
                totalVo.Ended      += vo.Ended;
                totalVo.SsCount    += vo.SsCount;
                totalVo.SimCount   += vo.SimCount;
                totalVo.QueryCount += vo.QueryCount;
                totalVo.TotalTime  += vo.TotalTime;
            }

            // Calculate site totals


            foreach (UserDataVo vo in UserDataHash.Values)
            {
                if (vo.Users > 0)
                {
                    continue;                               // just individuals
                }
                if (vo.Site == "")
                {
                    continue;                                // ignore if no site info
                }
                totalVo.Users++;
                totalVo.Count      += vo.Count;
                totalVo.Ended      += vo.Ended;
                totalVo.SsCount    += vo.SsCount;
                totalVo.SimCount   += vo.SimCount;
                totalVo.QueryCount += vo.QueryCount;
                totalVo.TotalTime  += vo.TotalTime;
            }

            // Order user data by descending usage count

            ArrayList UserDataList = new ArrayList(UserDataHash.Values);

            UserDataVo ud1, ud2;

            for (i1 = 1; i1 < UserDataList.Count; i1++)
            {
                ud1 = (UserDataVo)UserDataList[i1];
                for (i2 = i1 - 1; i2 >= 0; i2--)
                {
                    ud2 = (UserDataVo)UserDataList[i2];
                    if (ud1.Count < ud2.Count)
                    {
                        break;
                    }
                    UserDataList[i2 + 1] = UserDataList[i2];
                }
                UserDataList[i2 + 1] = ud1;
            }

            // Output user info

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("Mobius Usage Statistics for " + startDate + " through " + endDate);
            sb.AppendLine("");

            string format, s;

            object[] args;

            format = "{0,-38} {1,5} {2,4} {3,7} {4,4} {5,4}";
            args   = new object[] { "User", "Uses", "Time", "Queries", "SSS", "Sim" };
            s      = String.Format(format, args);
            sb.AppendLine(s);

            args = new object[] { "--------------------------------------", "-----", "----", "-------", "----", "----" };
            s    = String.Format(format, args);
            sb.AppendLine(s);

            for (pass = 1; pass <= 2; pass++)             // do summary values first, then users
            {
                for (int ui = 0; ui < UserDataList.Count; ui++)
                {
                    UserDataVo vo = (UserDataVo)UserDataList[ui];
                    if (pass == 1 && vo.Users == 0)
                    {
                        continue;                                                 // skip users on first past
                    }
                    else if (pass == 2 && vo.Users > 0)
                    {
                        continue;                                                     // skip totals on 2nd pass
                    }
                    if (vo.Ended == 0)
                    {
                        vo.AverageTime = 0;
                    }
                    else
                    {
                        vo.AverageTime = vo.TotalTime / vo.Ended; // avg. Time (min) for properly ended sessions
                    }
                    if (vo.Users > 0)                             // summary
                    {
                        txt = vo.Userid + " (" + vo.Users.ToString() + " users)";
                    }

                    else
                    {                     // single user
                        try
                        {
                            UserInfo sui = Security.GetUserInfo(vo.Userid);
                            txt  = sui.LastName + ", " + sui.FirstName;
                            txt += " (" + vo.Userid + ")";
                        }
                        catch (Exception ex) { txt = vo.Userid; }

                        if (vo.Site != "")
                        {
                            txt += " (" + vo.Site + ")";
                        }
                    }

                    args = new object[] { txt, vo.Count, vo.AverageTime, vo.QueryCount, vo.SsCount, vo.SimCount };
                    s    = String.Format(format, args);
                    sb.AppendLine(s);
                }
            }

            // Output table usage stats

            sb.AppendLine("");
            format = "{0,-18} {1,8}";
            s      = String.Format(format, "MetaTable", "Accesses");
            sb.AppendLine(s);
            s = String.Format(format, "------------------", "--------");
            sb.AppendLine(s);

            ArrayList al = new ArrayList();

            foreach (string key in TableData.Keys)
            {
                s = String.Format(format, key, TableData[key]);
                al.Add(s);
            }
            al.Sort();
            foreach (string s2 in al)
            {
                sb.AppendLine(s2);
            }

            // Output command usage stats

            sb.AppendLine("");
            format = "{0,-18} {1,8}";
            s      = String.Format(format, "Command", "Accesses");
            sb.AppendLine(s);
            s = String.Format(format, "------------------", "--------");
            sb.AppendLine(s);

            al = new ArrayList();
            foreach (string key in CommandData.Keys)
            {
                s = String.Format(format, key, CommandData[key]);
                al.Add(s);
            }
            al.Sort();
            foreach (string s2 in al)
            {
                sb.AppendLine(s2);
            }

            // Output transaction counts

            sb.AppendLine("");
            format = "{0,-18} {1,8}";
            s      = String.Format(format, "Transaction", "Count");
            sb.AppendLine(s);
            s = String.Format(format, "------------------", "--------");
            sb.AppendLine(s);

            al = new ArrayList();
            foreach (string key in TransactionData.Keys)
            {
                s = String.Format(format, key, TransactionData[key]);
                al.Add(s);
            }
            al.Sort();
            foreach (string s2 in al)
            {
                sb.AppendLine(s2);
            }

            return(sb.ToString());
        }
Ejemplo n.º 11
0
/// <summary>
/// Delete all user account information and user objects
/// </summary>
/// <param name="commandLine"></param>
/// <returns></returns>

        public static string DeleteUser(
            string commandLine)
        {
            string tok, msg;

            Lex lex = new Lex();

            lex.OpenString(commandLine);
            string userName    = lex.Get();
            bool   interactive = Lex.IsNullOrEmpty(userName);

            while (true)
            {
                if (interactive)
                {
                    userName = InputBoxMx.Show("Enter the Username of the user to delete:", "Delete User", userName);
                    if (Lex.IsNullOrEmpty(userName))
                    {
                        return("");
                    }
                }

                userName = userName.ToUpper();
                UserInfo ui = Security.ReadUserInfo(userName);
                if (ui == null)
                {
                    msg = "User doesn't exist: " + userName;
                    if (!interactive)
                    {
                        return(msg);
                    }
                    MessageBoxMx.ShowError(msg);
                    continue;
                }

                msg = "Are you sure you want to delete user: "******" (" + ui.FullName + ")";
                DialogResult dr = MessageBoxMx.Show(msg, "Delete User", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                if (dr != DialogResult.Yes)
                {
                    if (!interactive)
                    {
                        return("");
                    }
                    else
                    {
                        continue;
                    }
                }

                bool result = Security.DeleteUser(userName);
                if (result == true)
                {
                    msg = "User deleted: " + userName;
                }
                else
                {
                    msg = "Delete user failed for: " + userName;
                }
                if (!interactive)
                {
                    return(msg);
                }

                MessageBoxMx.Show(msg);
                userName = "";
                continue;
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Process command line to create a user
        /// </summary>
        /// <param name="commandLine"></param>
        /// <returns></returns>

        public static string CreateUser(
            string commandLine)
        {
            string tok, msg;

            Lex lex = new Lex();

            lex.OpenString(commandLine);

            if (!Security.IsAdministrator(SS.I.UserName))
            {
                return("You must be a Mobius administrator to create users");
            }

            string userName    = lex.GetUpper();          // get user name
            bool   interactive = Lex.IsNullOrEmpty(userName);

            while (true)
            {
                UserInfo ui = new UserInfo();

                int i1 = userName.IndexOf(@"\");
                if (i1 < 0)
                {
                    i1 = userName.IndexOf(@"/"); // try forward slash
                }
                if (i1 < 0)                      // domain not specified, default is AM
                {
                    ui.UserName = userName;
                }
                else if (i1 > 0)
                {
                    ui.UserDomainName = userName.Substring(0, i1);
                    ui.UserName       = userName.Substring(i1 + 1);
                }

                if (interactive)                 // prompt
                {
                    DialogResult dr = CreateUserDialog.ShowDialog(ui, "Create User");
                    if (dr == DialogResult.Cancel)
                    {
                        return("");
                    }
                }

                else
                {                 // Syntax: CREATE USER [domain\]userid firstname [mi] lastname [emailAddress] [company] [site] [department]
                    ui.FirstName = Lex.CapitalizeFirstLetters(Lex.RemoveAllQuotes(lex.Get()));
                    tok          = Lex.CapitalizeFirstLetters(Lex.RemoveAllQuotes(lex.Get()));
                    if (tok.Length == 1)
                    {
                        ui.MiddleInitial = tok;
                    }
                    else
                    {
                        lex.Backup();
                    }
                    ui.LastName     = Lex.CapitalizeFirstLetters(Lex.RemoveAllQuotes(lex.Get()));
                    ui.EmailAddress = Lex.CapitalizeFirstLetters(Lex.RemoveAllQuotes(lex.Get()));
                    ui.Company      = Lex.CapitalizeFirstLetters(Lex.RemoveAllQuotes(lex.Get()));
                    ui.Site         = Lex.CapitalizeFirstLetters(Lex.RemoveAllQuotes(lex.Get()));
                    ui.Department   = Lex.CapitalizeFirstLetters(Lex.RemoveAllQuotes(lex.Get()));
                }

                UserInfo existingUi = Security.ReadUserInfo(ui.UserName);

                try
                {
                    Security.CreateUser(ui);
                    if (existingUi == null)
                    {
                        msg = "User successfully created";
                    }
                    else
                    {
                        msg = "User information updated";
                    }
                    msg += "\n\n" +
                           "User: "******"\n" +
                           "Domain: " + ui.UserDomainName + "\n" +
                           "First Name: " + ui.FirstName + "\n" +
                           "Middle Initial: " + ui.MiddleInitial + "\n" +
                           "Last Name: " + ui.LastName;
                }
                catch (Exception ex) { msg = "User creation failed: " + ex.Message; }

                if (!interactive)
                {
                    return(msg);
                }

                MessageBoxMx.Show(msg);
                userName = "";
            }
        }
Ejemplo n.º 13
0
        public static string Process(
            string command)
        {
            string tok;

            Lex lex = new Lex();

            lex.OpenString(command);
            tok = lex.Get();
            if (Lex.Eq(tok, "List"))
            {
                tok = lex.Get();
            }
            string arg = Lex.RemoveAllQuotes(lex.Get());

            if (Lex.Eq(tok, "New"))
            {
                return(CreateNewList());
            }
            else if (Lex.Eq(tok, "EditSaved"))
            {
                return(EditSaved());
            }
            else if (Lex.Eq(tok, "EditTemp"))
            {
                return(EditTemp(arg));
            }
            else if (Lex.Eq(tok, "SaveCurrent"))
            {
                return(SaveCurrentCommand());
            }
            else if (Lex.Eq(tok, "SaveCurrentToTemp"))
            {
                return(SaveCurrentToTempCommand(arg));
            }
            else if (Lex.Eq(tok, "SaveCurrentToNewTemp"))
            {
                return(SaveCurrentToNewTempCommand());
            }
            else if (Lex.Eq(tok, "CopySavedToCurrent"))
            {
                return(CopySavedToCurrentCommand());
            }
            else if (Lex.Eq(tok, "CopyTempToCurrent"))
            {
                return(CopyTempToCurrentCommand(arg));
            }
            else if (Lex.Eq(tok, "Delete"))
            {
                return(DeleteList());
            }
            else if (Lex.Eq(tok, "Logic"))
            {
                return(LogicallyCombineLists(""));
            }
            else if (Lex.Eq(tok, "Export"))
            {
                return(ExportList());
            }
            else if (Lex.Eq(tok, "Import"))
            {
                return(ImportList());
            }
            else if (Lex.Eq(tok, "Subset"))
            {
                return(SubsetDatabase(arg));
            }

            else
            {
                return(tok + " is not a valid List command");
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Reorder the rows in all annotation tables that haven't been reordered since last call
        /// </summary>

        public static string ReorderRows(string singleAnnotTableId)
        {
            long methodId = 0, rowCnt = 0, rowCnt2 = 0, totalRows = 0;
            int  failCnt = 0, skipCnt = 0;

            Lex lex = new Lex();

            lex.OpenString(singleAnnotTableId);
            string singleMvId = lex.Get();             // item to set

            string sql = @"
				select mthd_vrsn_id, count from 
				(
				select mthd_vrsn_id, count(mthd_vrsn_id) count 
				 FROM MBS_OWNER.mbs_adw_rslt
				 WHERE mthd_vrsn_id > 0 
				 group by mthd_vrsn_id)
				order by mthd_vrsn_id
				"                ;

            if (Lex.IsDefined(singleMvId))             // single annot table
            {
                if (!Lex.IsLong(singleMvId))
                {
                    throw new ArgumentException();
                }
                sql = Lex.Replace(sql, "> 0", "= " + singleMvId);
            }

            Mobius.UAL.Progress.Show("Getting list of annotation tables to update...");

            DbCommandMx cmd = DbCommandMx.PrepareAndExecuteReader(sql);

            List <long> methodIds       = new List <long>();
            List <long> methodRowCounts = new List <long>();

            while (cmd.Read())
            {
                methodId = cmd.GetLong(0);
                methodIds.Add(methodId);

                rowCnt = cmd.GetLong(1);
                methodRowCounts.Add(rowCnt);
            }
            cmd.Dispose();

            totalRows = 0;
            int vmIdCnt = 0;

            for (int mi = 0; mi < methodIds.Count; mi++)
            {
                methodId = methodIds[mi];

                //if (methodId <= 442290) continue; // continue where left off

                rowCnt = methodRowCounts[mi];
                string msg = "Table Id: " + methodId + " (" + (mi + 1) + " / " + methodIds.Count + "), Rows: " + rowCnt + ", Total Rows Reordered: " + totalRows + ", Failed: " + failCnt + ", Skipped: " + skipCnt;

                if (rowCnt > 1000000 && Lex.IsUndefined(singleMvId))                 // skip if > 1000000 rows and not a specific single annot table
                {
                    skipCnt++;
                    DebugLog.Message("Skipping " + msg);
                    continue;
                }

                Mobius.UAL.Progress.Show(msg);
                DebugLog.Message(msg);

                try
                {
                    rowCnt2 = ReorderRows(methodId);
                }

                catch (Exception ex)
                {
                    DebugLog.Message(DebugLog.FormatExceptionMessage(ex));
                    failCnt++;
                    continue;
                }

                vmIdCnt++;
                totalRows += rowCnt;
            }

            return("Annotation tables reordered: " + vmIdCnt + ", Failed: " + failCnt + ", Skipped: " + skipCnt + ", Total rows reordered: " + totalRows);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// ExportToPyMolMethod
        /// </summary>
        /// <param name="url"></param>
        /// <param name="qm"></param>
        void ExportToPyMolMethod(
            string url,
            string densityMapUrl,
            string target,
            QueryManager qm)
        {
            StreamWriter sw;

            string rec, msg, scriptSourceFile, pluginSourceFile, script;

            bool includeProtein = true;             // always include protein

            //bool includeElectronDensity = IncludeElectronDensityPyMol.Checked;
            if (!IncludeElectronDensityPyMol.Checked)
            {
                _qcDensity = null;
            }

            pluginSourceFile = CommonConfigInfo.MiscConfigDir + @"\CorpView.py";                       // the PyMOL plugin
            CopyToReadLockedFile(pluginSourceFile, CommonConfigInfo.MiscConfigDir + @"\CorpView2.py"); // move CorpView2.py to CorpView.py
            if (!File.Exists(pluginSourceFile))
            {
                throw new Exception("Plugin file not found: " + pluginSourceFile);
            }



            scriptSourceFile = CommonConfigInfo.MiscConfigDir + @"\CorpView.pml";             // the script that starts pymol & hands it the .csv file
            CopyToReadLockedFile(scriptSourceFile, CommonConfigInfo.MiscConfigDir + @"\CorpView2.pml");
            if (!File.Exists(scriptSourceFile))
            {
                throw new Exception("Script file not found: " + scriptSourceFile);
            }

            string csvFile = ClientDirs.TempDir + @"\PyMolBatchLoad.csv";             // the .csv file to write

            WriteCsvFile(csvFile, ExportSingle.Checked, _qcProtein, _qcDensity, _qcTarget, qm, url, densityMapUrl, target);

            //qm.Query.Tables[0].MetaTable.Name

            try             // Read the CorpView2.pml that gets edited.
            {
                StreamReader sr = new StreamReader(scriptSourceFile);
                script = sr.ReadToEnd();
                sr.Close();
            }
            catch (Exception ex)
            { throw new Exception("Error reading " + scriptSourceFile + ": " + ex.Message); }

            // Get the path to the plugin file

            string pluginFile = null;
            Lex    lex        = new Lex("=");

            lex.OpenString(script);
            while (true)
            {
                string tok = lex.Get();
                if (tok == "")
                {
                    break;
                }
                if (Lex.Ne(tok, "pluginLocation"))
                {
                    continue;
                }

                pluginFile = lex.Get();
                if (pluginFile == "=")
                {
                    pluginFile = lex.Get();
                }
                pluginFile = Lex.RemoveSingleQuotes(pluginFile);
            }

            if (pluginFile == null)
            {
                throw new Exception("Can't find definition of plugin location");
            }

            // Get the proper plugin directory

            string pluginFolder = Path.GetDirectoryName(pluginFile);

            if (!Directory.Exists(pluginFolder))
            {
                string pluginFile2 = pluginFile;
                pluginFile2 = Lex.Replace(pluginFile2, "Progra~1", "Progra~2");                 // Win7 x86 folder using 8.3 names
                pluginFile2 = Lex.Replace(pluginFile2, "Program Files", "Program Files (x86)"); // Win7 x86 folder with regular names
                string pluginFolder2 = Path.GetDirectoryName(pluginFile2);
                if (!Directory.Exists(pluginFolder2))
                {
                    DebugLog.Message("Can't find PyMOL plugin folder: " + pluginFolder);
                    MessageBox.Show("Can't find PyMol plugin folder " + pluginFolder + ".\rContact Pymol Support team.");
                    Progress.Hide();
                    return;
                }
                script     = Lex.Replace(script, pluginFile, pluginFile2);             // substitute proper plugin file name in script
                pluginFile = pluginFile2;
            }

            bool update         = false;
            bool pyMolInstalled = File.Exists(pluginFile);

            ClientLog.Message("Checking for PyMol installation...");

            if (pyMolInstalled)
            {
                DateTime dt1 = File.GetLastWriteTime(pluginSourceFile);
                DateTime dt2 = File.GetLastWriteTime(pluginFile);
                if (DateTime.Compare(dt1, dt2) > 0)
                {
                    ClientLog.Message("  PyMol file is older than the Mobius version.");
                    update = true;
                }
            }
            else
            {
                ClientLog.Message("  Could not find PyMol file: " + pluginFile);
                update = true;
            }

            // Be sure the plugin is up to date

            if (update)
            {
                try
                {
                    File.Copy(pluginSourceFile, pluginFile, true);                      // copy CorpView.py to Pymol startup dir
                }
                catch (Exception ex)
                {
                    ClientLog.Message("   Error copying CorpView.py to: " + pluginFile + ", " + ex.Message);
                    if (!pyMolInstalled)
                    {
                        MessageBox.Show("Unable to find Corp Plugin (CorpView.py) for Pymol.\rWindows 7 will not allow Mobius access to copy the plugin to your machine.\rContact Pymol Support team.");
                        Progress.Hide();
                        return;
                    }
                }
            }

            DebugLog.Message("Error copying CorpView.py to: " + pluginFile);

            // Plug the csv file name into the script

            string csvFileNameParm = "<csv-file-name>";

            if (!Lex.Contains(script, csvFileNameParm))
            {
                throw new Exception("<csv-file-name> not found in script");
            }
            string csvFileNameForScript = csvFile.Replace(@"\", "/");             // translate backslashes so they aren't interpreted as escapes

            script = Lex.Replace(script, csvFileNameParm, csvFileNameForScript);

            string scriptFile = ClientDirs.TempDir + @"\CorpView.pml";

            sw = new StreamWriter(scriptFile);
            sw.Write(script);
            sw.Close();

            Progress.Show("Passing data to PyMOL...");
            try
            {
                //DebugLog.Message("startFile: " + startFile);
                //DebugLog.Message("startArgs: " + startArgs);
                Process p = Process.Start(scriptFile);
            }
            catch (Exception ex)
            {
                MessageBoxMx.ShowError("Failed to start PyMOL");
                Progress.Hide();
                return;
            }

            System.Threading.Thread.Sleep(3000);             // leave message up a bit while PyMOL is starting/being activated
            Progress.Hide();
        }