示例#1
0
/// <summary>
/// Create document with status update & cancel allowed (gets cross-thread exception)
/// </summary>
        void CreateDocument()
        {
            try
            {
                Progress.Show("Formatting preview...", "Mobius", true);
                ThreadStart ts        = new ThreadStart(CreateDocumentThreadMethod);
                Thread      newThread = new Thread(ts);
                newThread.IsBackground = true;
                newThread.SetApartmentState(ApartmentState.STA);
                newThread.Start();

                while (true)
                {
                    Thread.Sleep(10000);
                    if (!Ps.Document.IsCreating)
                    {
                        break;
                    }
                    Progress.Show("Formatting preview page " + (Ps.Document.PageCount + 1).ToString() + "...");
                    if (Progress.CancelRequested)
                    {
                        Ps.ExecCommand(PrintingSystemCommand.StopPageBuilding);
                        Thread.Sleep(250);
                        break;
                    }
                }

                Progress.Hide();
            }
            catch (Exception ex) { ex = ex; }
        }
示例#2
0
/// <summary>
/// Import a list
/// </summary>
/// <returns></returns>

        static string ImportList()
        {
            string filePath = SelectListFileDialog("List File to Import", "");

            if (String.IsNullOrEmpty(filePath))
            {
                return("");
            }

            string fileName = Path.GetFileNameWithoutExtension(filePath);

            UserObject oListName = new UserObject(UserObjectType.CnList, SS.I.UserName, fileName);

            oListName = UserObjectSaveDialog.Show("Database List to Import Into", oListName);
            if (oListName == null)
            {
                return("");
            }

            Progress.Show("Importing List...");
            CidList list = CidList.ReadFromFile(filePath); // read file list

            Write(list, oListName);                        // write database list
            Progress.Hide();

            return(list.Count.ToString() + " " + MetaTable.KeyMetaTable.KeyMetaColumn.Label + "s have been imported");
        }
示例#3
0
        /// <summary>
        /// If the file is a UNC name check to see if the services can write to it
        /// </summary>
        /// <param name="fileName"></param>

        public static DialogResult CanWriteFileFromServiceAccount(
            string fileName)
        {
            //if (DisplayedUncWarningMessage) return DialogResult.OK;

            if (!fileName.StartsWith(@"\\"))
            {
                return(DialogResult.OK);
            }
            ;

            Progress.Show("Checking Mobius background write privileges...", UmlautMobius.String, false);
            bool canWrite = ServerFile.CanWriteFileFromServiceAccount(fileName);

            Progress.Hide();
            //canWrite = false; // debug
            if (canWrite)
            {
                return(DialogResult.OK);
            }

            DialogResult dr = MessageBoxMx.Show(
                "The specified file is in a shared Windows network folder.\n" +
                "Mobius can't currently perform a background export directly to this file.\n" +
                "However, if write access to this shared folder is granted to the <mobiusAccount>\n" +
                "account then Mobius will be able to export directly to the specified file.",
                "Mobius", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

            DisplayedUncWarningMessage = true;
            return(dr);
        }
示例#4
0
/// <summary>
/// Export a list
/// </summary>
/// <returns></returns>

        static string ExportList()
        {
            CidList list;

            UserObject iListName = SelectListDialog("Database List to Export");

            if (iListName == null)
            {
                return("");
            }

            string initialName = iListName.Name + ".lst";
            string fileName    = UIMisc.GetSaveAsFilename("List File to Export Into", initialName,
                                                          "Lists (*.lst)|*.lst|All files (*.*)|*.*", "LST");

            if (fileName == "")
            {
                return("");
            }

            Progress.Show("Exporting List...");
            list = Read(iListName);             // read database list
            if (list == null)
            {
                return("Error reading list from database");
            }

            list.WriteToFile(fileName, SS.I.RemoveLeadingZerosFromCids);             // write file list
            Progress.Hide();

            return(list.Count.ToString() + " " + MetaTable.KeyMetaTable.KeyMetaColumn.Label + "s have been exported");
        }
示例#5
0
 public static void Show(
     Progress msg)
 {
     if (msg == null || Lex.IsNullOrEmpty(msg.Text))
     {
         Hide();                                                         // hide it
     }
     else
     {
         Progress.Show(msg.Caption.Text, msg.Text, msg.Cancel.Enabled, msg.CancellingMessage.Text);
     }
 }
示例#6
0
        /// <summary>
        /// Show progress from thread other than the UI thread
        /// </summary>
        /// <param name="caption"></param>
        /// <param name="title"></param>
        /// <param name="allowCancel"></param>

        public static void InvokeShow(
            string caption,
            string title,
            bool allowCancel)
        {
            Progress.Show(caption, title, allowCancel);

            //if (Instance != null)
            //{
            //	Instance.Invoke(new ProgressDelegates.ShowDelegate(Show), caption, title, allowCancel);
            //}
            //else
            //{ //want the Instance to have been created IN THE UI THREAD!!!
            //	SessionManager.Instance.ShellForm.Invoke(new ProgressDelegates.ShowDelegate(Show), caption, title, allowCancel);
            //}
        }
示例#7
0
        /// <summary>
        /// Build a Spotfire view for the QueryTable in the current query
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>

        public static string StoreSpotfireQueryTableSql()
        {
            string sqlStmtName = QbUtil.Query.UserObject.Name;

            if (Lex.StartsWith(sqlStmtName, "SF_"))             // trim the sf prefix
            {
                sqlStmtName = sqlStmtName.Substring(3);
            }

            while (true)
            {
                sqlStmtName = InputBoxMx.Show("Name to assign to stored SQL:", "Store Mobius QueryTable SQL for Use by Spotfire", sqlStmtName);
                if (Lex.IsUndefined(sqlStmtName))
                {
                    return("");
                }

                string existingSql = QueryEngine.ReadSpotfireSql(sqlStmtName, 0);
                if (Lex.IsDefined(existingSql))
                {
                    DialogResult dr = MessageBoxMx.Show(
                        "Sql statement " + sqlStmtName + " already exists.\r\n" +
                        "Do you want to overwrite it?",
                        "Confirm Overwrite", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                    if (dr == DialogResult.No)
                    {
                        continue;                                            // allow name reentry
                    }
                    else if (dr == DialogResult.Cancel)
                    {
                        return("");
                    }
                }

                break;
            }

            Progress.Show("Saving SQL...");
            int id = QueryEngine.SaveSpotfireSql(sqlStmtName, QbUtil.Query);

            Progress.Hide();

            string msg = "Sql statement " + sqlStmtName + " has been stored.";

            return(msg);
        }
示例#8
0
        /// <summary>
        /// Build a Spotfire view for the QueryTable in the current query
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>

        public static string BuildSpotfireQueryTableView(string viewName)
        {
            string initialViewName = viewName;

            if (Lex.IsUndefined(initialViewName))
            {
                viewName = QbUtil.Query.UserObject.Name;
            }

            do
            {
                if (Lex.IsUndefined(initialViewName) || viewName.Length > 30)
                {
                    viewName = InputBoxMx.Show("Name to assign to stored SQL:", "Build QueryTable SQL for Use by Spotfire", viewName);
                    if (Lex.IsUndefined(viewName))
                    {
                        return("");
                    }
                }
            }while (viewName.Length > 30);

            string serializedQuery = QbUtil.Query.Serialize();

            string command = "BuildQueryTableOracleView " + viewName + " " + serializedQuery;

            Progress.Show("Executing Command...");
            string result = CommandLine.ExecuteServiceCommand(command);

            Progress.Hide();
            return(result);

            //QueryTable qt = QbUtil.Query.CurrentTable;
            //if (qt == null) return "No current QueryTable";

            //Query q = new Query();
            //qt = qt.Clone();
            //q.AddQueryTable(qt);

            //string initialViewName = viewName;
            //if (Lex.IsUndefined(initialViewName))
            //  viewName = "SF_" + qt.MetaTable.Name; // default view name has SF prefix
        }
示例#9
0
        /// <summary>
        /// Display the grid of alerts & let user add, edit and cancel them.
        /// </summary>
        /// <returns></returns>
        public static string Show(string args)
        {
            List <UserObject> alerts;
            Alert             alert = null;
            int    alertId, queryId, row;
            string txt;

            string userid = SS.I.UserName;

            if (args == null || args == "")
            {
                Progress.Show("Retrieving alerts...", UmlautMobius.String, false);
                alerts = UserObjectDao.ReadMultiple(UserObjectType.Alert, SS.I.UserName, false, false);
            }

            else
            {
                if (!Security.IsAdministrator(SS.I.UserName))
                {
                    return("Only administrators can execute this command");
                }
                Progress.Show("Retrieving alerts...", UmlautMobius.String, false);
                if (Lex.Eq(args, "All"))                 // all users
                {
                    alerts = UserObjectDao.ReadMultiple(UserObjectType.Alert, false);
                }
                else                 // some other user
                {
                    alerts = UserObjectDao.ReadMultiple(UserObjectType.Alert, args, false, false);
                }
            }

            AlertGridDialog Instance = new AlertGridDialog();

            Instance.SetupGrid(alerts);
            Progress.Hide();

            DialogResult dr = Instance.ShowDialog(SessionManager.ActiveForm);

            return("");
        }
示例#10
0
        /// <summary>
        /// Start new process to check queued alerts
        /// </summary>

        public void StartQueueProcessor(
            string args)
        {
            _numberOfCurrentProcessors++;
            string msg = "Starting queue processor " + NumberOfCurrentProcessors;

            AlertUtil.LogAlertMessage(msg);
            Progress.Show(msg);

            if (Lex.Contains(args, "singleProcessor"))             // use single queue processor within this process (for debug)
            {
                CheckQueuedAlerts(args);
            }

            else             // start separate process to check the queued alerts
            {
                try
                { CommandLine.StartForegroundSession("Check Queued Alerts " + args, null); }
                catch (Exception ex)
                { AlertUtil.LogAlertMessage("Couldn't start new queue processor:\r\n" + ex.Message); }
            }
        }
示例#11
0
        /// <summary>
        /// See if a ClickFunction command & process if so
        /// </summary>
        /// <param name="command"></param>
        /// <param name="qm"></param>
        /// <param name="cInf"></param>

        public static void Process(
            string command,
            QueryManager qm,
            CellInfo cInf = null)
        {
            QueryTable    rootQt, qt;
            QueryColumn   qc;
            MetaTable     mt;
            MetaColumn    mc;
            Query         q2;
            string        dbName = "", mtName = "", mcName = "";
            List <string> args0, args;
            string        funcName, arg1, arg2, arg3, arg4, arg5;
            string        value = "", keyValue = "";

            int ai;

            try
            {
                // Parse click function arguments stripping all single quotes.
                // Arguments may be defined in the clickfunction definition including col values
                // indicated by field.Value in the metacolumn clickfunction definition.
                // If no args are defined in the clickfunction definition then a field value
                // argument will be added by default or the keyValue if [keyvalue] appears in the
                // ClickFunction definition

                CurrentClickQueryManager = qm;
                args0 = Lex.ParseAllExcludingDelimiters(command, "( , )", false);
                args  = new List <string>();
                for (ai = 0; ai < args0.Count; ai++)                 // strip all single quotes
                {
                    string arg = args0[ai];
                    if (arg.StartsWith("'"))
                    {
                        arg = Lex.RemoveSingleQuotes(arg);
                    }

                    //if (Lex.Eq(arg, "[rowcol]") && cInf!= null)
                    //{ // pass grid row & col
                    //  args.Add(cInf.GridRowHandle.ToString());
                    //  args.Add(cInf.GridColAbsoluteIndex.ToString());
                    //}
                    //else

                    args.Add(arg);
                }

                funcName = args[0];
                arg1     = (args.Count >= 2 ? args[1] : "");             // get other args
                arg2     = (args.Count >= 3 ? args[2] : "");
                arg3     = (args.Count >= 4 ? args[3] : "");
                arg4     = (args.Count >= 5 ? args[4] : "");
                arg5     = (args.Count >= 6 ? args[5] : "");

                if (Lex.Eq(funcName, "DisplayAllData"))
                {                 // do all data display for supplied root table and key, i.e. DisplayAllData(TableName, KeyColName, KeyValue)
                    ParseMetaTableMetaColumn(arg1, out mt, arg2, out mc);
                    string extKey = arg3;
                    string intKey = CompoundId.Normalize(extKey, mt);

                    Progress.Show("Building Query...");
                    _query = QueryEngine.GetSelectAllDataQuery(mt.Name, intKey);
                    Progress.Show("Retrieving data...");                     // put up progress dialog since this may take a while
                    QbUtil.RunPopupQuery(_query, mt.KeyMetaColumn.Name + " " + extKey);
                    Progress.Hide();
                    return;
                }

                else if (Lex.Eq(funcName, "DisplayAllDataUsingDbName"))
                {                 // display all data for supplied database synonym & key value, i.e. DisplayAllData2(DataBaseSynonym, KeyValue)
                    mtName = null;
                    dbName = arg1;
                    RootTable rti = RootTable.GetFromTableLabel(dbName);
                    if (rti != null)
                    {
                        mtName = rti.MetaTableName;
                    }
                    else                     // try synonyms
                    {
                        DictionaryMx dict = DictionaryMx.Get("Database_Synonyms");
                        if (dict != null)
                        {
                            mtName = dict.LookupDefinition(dbName);
                        }
                    }

                    if (String.IsNullOrEmpty(mtName))
                    {
                        MessageBoxMx.ShowError("Unrecognized database: " + dbName);
                        return;
                    }

                    mt = MetaTableCollection.Get(mtName);
                    if (mt == null)
                    {
                        MessageBoxMx.ShowError("Can't find key metatable " + mtName + " for database " + dbName);
                        return;
                    }

                    string extKey = arg2;
                    string intKey = CompoundId.Normalize(extKey, mt);

                    Progress.Show("Building Query...");
                    _query = QueryEngine.GetSelectAllDataQuery(mt.Name, intKey);
                    Progress.Show("Retrieving data...");                     // put up progress dialog since this may take a while
                    QbUtil.RunPopupQuery(_query, mt.KeyMetaColumn.Name + " " + extKey);
                    return;
                }

                // Run a query displaying results to a grid or web page and substituting a parameter value

                else if (Lex.Eq(funcName, "RunHtmlQuery") || Lex.Eq(funcName, "RunGridQuery"))
                {                 // command to display to grid or html
                    if (arg1.StartsWith("MetaTreeNode=", StringComparison.OrdinalIgnoreCase))
                    {             // query based on metatables under a tree node
                        string nodeName = arg1.Substring("MetaTreeNode=".Length).Trim();
                        _cid = arg2;

                        MetaTreeNode mtn = MetaTree.GetNode(nodeName);
                        if (mtn == null)
                        {
                            MessageBoxMx.ShowError("Can't find tree node referenced in ClickFunction: " + nodeName);
                            return;
                        }

                        _query = new Query();
                        MetaTable rootMt = null;
                        foreach (MetaTreeNode mtn_ in mtn.Nodes)
                        {
                            if (!mtn_.IsDataTableType)
                            {
                                continue;
                            }
                            mt = MetaTableCollection.Get(mtn_.Target);
                            if (mt == null)
                            {
                                continue;
                            }
                            if (rootMt == null)
                            {
                                rootMt = mt.Root;
                                rootQt = new QueryTable(_query, rootMt);
                            }

                            if (mt == rootMt)
                            {
                                continue;
                            }
                            qt = new QueryTable(_query, mt);
                        }

                        if (_query.Tables.Count == 0)
                        {
                            MessageBoxMx.ShowError("No valid data tables found: " + nodeName);
                            return;
                        }

                        _query.KeyCriteria = "= " + _cid;
                        _title             = mtn.Label + " for " + _query.Tables[0].MetaTable.MetaColumns[0].Label + " " + CompoundId.Format(_cid);
                    }

                    else if (arg1.StartsWith("Query=", StringComparison.OrdinalIgnoreCase))
                    {                     // query based on saved query
                        string qIdString = arg1.Substring("Query=".Length).Trim();
                        if (qIdString.StartsWith("Query_", StringComparison.OrdinalIgnoreCase))
                        {
                            qIdString = qIdString.Substring("Query_".Length).Trim();
                        }
                        int qId = int.Parse(qIdString);

                        _query = QbUtil.ReadQuery(qId);

                        _cid = arg2;
                        _query.KeyCriteria = "= " + _cid;
                        _title             = _query.UserObject.Name + " for " + _query.Tables[0].MetaTable.MetaColumns[0].Label + " " + CompoundId.Format(_cid);
                    }

                    else                     // explicit mql string to execute
                    {
                        _mql = arg1;         // mql to execute
                        if (Lex.IsUndefined(_mql))
                        {
                            throw new Exception("Expected MQL query not found: " + command);
                        }

                        mt = null;
                        mc = null;

                        if (Lex.IsDefined(arg2) && Lex.IsDefined(arg3))
                        {
                            mtName   = arg2;
                            mcName   = arg3;
                            value    = arg4;                          // value to plug in to mql
                            keyValue = value;
                            ParseMetaTableMetaColumn(arg2, out mt, arg3, out mc);
                        }

                        else if (cInf != null)
                        {
                            mt       = cInf.Mt;
                            mc       = cInf.Mc;
                            value    = cInf?.DataValue?.ToString();
                            keyValue = qm?.DataTableManager?.GetRowKey(cInf.DataRowIndex);
                        }

                        if (mt == null || mc == null)
                        {
                            throw new Exception("Invalid MetaTable or MetaColumn name(s): " + command);
                        }

                        if (!mc.IsNumeric)
                        {
                            value = Lex.AddSingleQuotes(value);                             // quote if not numeric
                        }
                        int i1 = _mql.ToLower().IndexOf("[value]");                         // see if a value parameter
                        if (i1 >= 0)
                        {
                            string value2 = value;
                            _mql   = _mql.Replace(_mql.Substring(i1, 7), value);
                            _title = mc.Label + " " + value;
                        }

                        i1 = _mql.ToLower().IndexOf("[keyvalue]");                         // see if a key value parameter
                        if (i1 >= 0)
                        {
                            _mql   = _mql.Replace(_mql.Substring(i1, 10), keyValue);
                            _title = mt.KeyMetaColumn.Label + " " + keyValue;
                        }

                        try { _query = MqlUtil.ConvertMqlToQuery(_mql); }
                        catch (Exception ex)
                        {
                            MessageBoxMx.ShowError("Error converting Mql to query: " + ex.Message);
                            return;
                        }
                    }

                    if (Lex.Eq(funcName, "RunHtmlQuery"))
                    {
                        QbUtil.RunPopupQuery(_query, _title, OutputDest.Html);
                    }

                    else                     // output to grid
                    {
                        QbUtil.RunPopupQuery(_query, _title, OutputDest.WinForms);
                    }

                    //else // create new grid query & run (will lose results for current query)
                    //{
                    //	QbUtil.NewQuery(_title); // show in query builder
                    //	QbUtil.SetCurrentQueryInstance(_query);
                    //	QbUtil.RenderQuery();
                    //	string nextCommand = QueryExec.RunQuery(_query, OutputDest.Grid);
                    //}

                    return;
                }

                // Open a URL, normally substituting parameter value

                else if (Lex.Eq(funcName, "OpenUrl"))
                {
                    string url = arg1;                    // url to execute
                    value = arg2;                         // value to plug in to url

                    int i1 = Lex.IndexOf(url, "[value]"); // fill in one of the value place holders
                    if (i1 >= 0)
                    {
                        string value2 = value;
                        url = url.Replace(url.Substring(i1, 7), value);
                    }

                    else                     // check to see if we are matching on key
                    {
                        i1 = Lex.IndexOf(url, "[keyvalue]");
                        if (i1 >= 0)
                        {
                            url = url.Replace(url.Substring(i1, 10), value);
                        }
                    }

                    SystemUtil.StartProcess(url);
                    return;
                }

                else if (Lex.Eq(funcName, "OpenUrlFromSmallWorldCid"))
                {
                    SmallWorldDepictions.OpenUrlFromSmallWorldCid(arg1);
                    return;
                }

                else if (Lex.Eq(funcName, "ShowProjectDescription"))
                {
                    string projName = arg1;
                    QbUtil.ShowProjectDescription(projName);
                    return;
                }

                else if (Lex.Eq(funcName, "ShowTableDescription"))
                {
                    mtName = arg1;
                    QbUtil.ShowTableDescription(mtName);
                    return;
                }

                else if (Lex.Eq(funcName, "DisplayDrilldownDetail"))
                {                           // drill down into a result value
                    mtName = arg1;          // table
                    mcName = arg2;          // column
                    int    level    = Int32.Parse(arg3);
                    string resultId = arg4; // quoted resultId to get
                    q2 = QueryEngine.GetSummarizationDetailQuery(mtName, mcName, level, resultId);
                    if (q2 == null)
                    {
                        throw new Exception("Unable to build drill-down query for: " + mtName + "." + mcName);
                    }
                    bool success = QbUtil.RunPopupQuery(q2, "Result Detail", OutputDest.WinForms);
                    return;
                }

                //else if (Lex.Eq(funcName, "PopupSmilesStructure")) // display structure for a Smiles string (still needs some work...)
                //{
                //	string molString = arg1.ToString();
                //	ChemicalStructure cs = new ChemicalStructure(StructureFormat.Smiles, molString);
                //	ToolHelper.DisplayStructureInPopupGrid("Title...", "Smiles", "Structure", cs);
                //}

                //else if (Lex.Eq(funcName, "PopupChimeStructure")) // display structure for a Chime string
                //{
                //	string molString = arg1.ToString();
                //	ChemicalStructure cs = new ChemicalStructure(StructureFormat.Smiles, molString);
                //	ToolHelper.DisplayStructureInPopupGrid("Title...", "Smiles", "Structure", cs);
                //}

                else if (Lex.Eq(funcName, "DisplayWebPage"))
                {                 // substitute a field value into a url & display associated web page
                    string url = arg1;

                    ParseMetaTableMetaColumn(arg2, out mt, arg3, out mc);
                    value = arg4;                     // value to plug in to mql

                    //				value = "{6E9C28EF-407E-44A0-9007-5FFB735A5C6C}"; // debug
                    //				value = "{0AC17903-E551-445E-BFAA-860023D2884F}"; // debug
                    //				value = "{63EE71F9-15BA-42FB-AFDC-C399103707B1}"; // debug
                    //				value = "{80591183-B7BA-4669-8C5F-7E7F53D981CE}";

                    //lex.OpenString(mc.ClickFunction); // reparse url to get proper case
                    //funcName = lex.GetNonDelimiter();
                    //url = Lex.RemoveAllQuotes(lex.GetNonDelimiter());

                    _title = mc.Label + " " + value;
                    int i1 = url.ToLower().IndexOf("[value]");                     // fill in one of the value place holders
                    if (i1 >= 0)
                    {
                        url = url.Replace(url.Substring(i1, 7), value);
                    }

                    else                     // check to see if we are matching on key
                    {
                        i1 = url.ToLower().IndexOf("[keyvalue]");
                        if (i1 >= 0)
                        {
                            url    = url.Replace(url.Substring(i1, 10), value);
                            _title = mt.KeyMetaColumn.Label + " " + value;
                        }
                    }

                    UIMisc.ShowHtmlPopupFormDocument(url, _title);
                    return;
                }

                else if (Lex.Eq(funcName, "DisplayOracleBlobDocument")) // display a document contained in an Oracle blob column
                {                                                       // Syntax: DisplayOracleBlobDocument(<table-to-lookup>, <value_match_column>, <file-name-or-type-col>, <content-column>)
                    string table      = arg1;
                    string matchCol   = arg2;
                    string typeCol    = arg3;
                    string contentCol = arg4;
                    string matchVal   = arg5;                   // value to match

                    try
                    {
                        string typeName;
                        byte[] ba;
                        UalUtil.SelectOracleBlob(table, matchCol, typeCol, contentCol, matchVal, out typeName, out ba);
                        if (ba == null || ba.Length == 0)
                        {
                            return;
                        }

                        UIMisc.SaveAndOpenBinaryDocument(typeName, ba);
                    }

                    catch (Exception ex)
                    {
                        MessageBoxMx.ShowError("Error retrieving document: " + ex.Message);
                        return;
                    }

                    return;
                }

                else if (Lex.Eq(funcName, "DisplayOracleClobDocument")) // display a document contained in an Oracle clob column
                {                                                       // Syntax: DisplayOracleBlobDocument(<table-to-lookup>, <value_match_column>, <file-name-or-type-col>, <content-column>)
                    string table      = arg1;
                    string matchCol   = arg2;
                    string typeCol    = arg3;
                    string contentCol = arg4;
                    string matchVal   = arg5;                   // value to match

                    try
                    {
                        string typeName, clobString;
                        UalUtil.SelectOracleClob(table, matchCol, typeCol, contentCol, matchVal, out typeName, out clobString);
                        if (Lex.IsUndefined(clobString))
                        {
                            return;
                        }

                        UIMisc.SaveAndOpenBase64BinaryStringDocument(typeName, clobString);                         // assume clob string is a Base64Binary string
                    }

                    catch (Exception ex)
                    {
                        MessageBoxMx.ShowError("Error retrieving document: " + ex.Message);
                        return;
                    }

                    return;
                }

                else if (Plugins.IsMethodExtensionPoint(funcName))
                {
                    List <object> objArgs = new List <object>();
                    for (ai = 1; ai < args.Count; ai++)                     // build list of object arguments
                    {
                        objArgs.Add(args[ai]);
                    }
                    Plugins.CallStringExtensionPointMethod(funcName, objArgs);
                }

                else if (Lex.Eq(funcName, "None"))                 // dummy click function
                {
                    return;
                }

                else
                {
                    MessageBoxMx.ShowError("Unrecogized click function: " + funcName);
                    return;
                }
            }

            catch (Exception ex)
            {
                Exception ex2 = ex;
                if (ex.InnerException != null)
                {
                    ex2 = ex.InnerException;
                }
                string msg = "Error executing ClickFunction: " + command + "\r\n" +
                             DebugLog.FormatExceptionMessage(ex);
                MessageBoxMx.ShowError(msg);

                ServicesLog.Message(msg);
            }
        }
示例#12
0
        /// <summary>
        /// Execute search & get hit list
        /// </summary>
        /// <param name="saveHitlist"></param>
        /// <returns></returns>

        public bool ExecuteSearch(bool saveHitlist)
        {
            int          voi, ti, fi;
            ResultsTable rt;
            ResultsField rfld;
            MetaTable    mt;
            MetaColumn   mc, mc2;

            if (saveHitlist)             // clear current list
            {
                SessionManager.CurrentResultKeys = new List <string>();
                if (QueryManager.StatusBarManager != null)
                {
                    QueryManager.StatusBarManager.DisplayCurrentCount();
                }
            }

            // Start thread running the query

            QueryResultsAvailable = false;
            QueryEngineException  = null;
            ThreadStart ts = new ThreadStart(ExecuteQueryThreadMethod);
            Thread      executeQueryThread = new Thread(ts);

            executeQueryThread.Name         = "ExecuteSearch";
            executeQueryThread.IsBackground = true;
            executeQueryThread.SetApartmentState(ApartmentState.STA);
            executeQueryThread.Start();

            // Put up message for user

            if (((Query.ResultKeys != null && Query.UseResultKeys) ||             // already have list
                 ResultsFormat.SessionOutputFormContext) && !QueryEngineStatsForm.ShowStats)
            {
                Progress.Show("Retrieving data...", UmlautMobius.String, true, "Cancelling retrieval...");
            }

            else             // normal type search
            {
                Progress.Show("Searching database - 0:00", UmlautMobius.String, true, "Cancelling search...");
                if (QueryEngineStatsForm.ShowStats)
                {
                    QueryEngineStatsForm.StartNewQueryExecution(Query);
                    QueryEngineStatsForm.StartingSearch();
                }
            }

            // Wait until results available or the query is cancelled by the user

            while (true)
            {
                Thread.Sleep(100);
                Application.DoEvents();

                if (QueryResultsAvailable)                 // completed normally
                {
                    ResultsKeys = QueryEngine.GetKeys();
                    if (saveHitlist)                     // store for session manager also (may differ but probably shouldn't)
                    {
                        SessionManager.CurrentResultKeys = ResultsKeys;
                    }
                    //Progress.Hide();
                    break;
                }

                else if (QueryEngineException != null)
                {
                    Progress.Hide();
                    if (QueryEngineException is QueryException ||
                        QueryEngineException is UserQueryException)
                    {
                        throw QueryEngineException;
                    }
                    else
                    {
                        throw new Exception(QueryEngineException.Message, QueryEngineException);
                    }
                }

                else if (Progress.CancelRequested)
                {
                    if (QueryEngine != null)
                    {
                        QueryEngine.Cancel(false);                                          // start the cancel
                    }
                    Thread.Sleep(250);
                    Application.DoEvents();
                    if (executeQueryThread != null)
                    {
                        executeQueryThread.Abort();                                                 // kill the local thread executing the query
                    }
                    Progress.Hide();
                    return(false);
                }
            }

            // If the query contains tables marked for remapping then build new expanded query & use going forward

            // modifiedQuery = QueryEngine.DoPresearchChecksAndTransforms(Query); // do any presearch transforms

            OriginalQuery = Query;
            if (TransformedQuery != null)
            {
                //ResultsPages qrp = query.ResultsPages;
                //ResultsPages mqrp = modifiedQuery.ResultsPages; // use same set of results pages so view changes propagate back to original query
                Query.PresearchDerivedQuery = TransformedQuery; // link original query to the transformed query
                Query = TransformedQuery;                       // replace original query with this query
            }

            else
            {
                Query.PresearchDerivedQuery = null;
            }

            InitializeQueryManager(QueryManager, Query, QueryManager.ResultsFormat, QueryEngine, ResultsKeys);

            // Save the hit list as needed

            if (saveHitlist)
            {
                CidList currentList = new CidList(ResultsKeys);
                CidListCommand.WriteCurrentList(currentList);
                SessionManager.DisplayCurrentCount();
            }

            return(true);
        }
示例#13
0
        /// <summary>
        /// Run the query
        /// </summary>
        /// <param name="browseExistingResults">If true browse existing results</param>
        /// <returns></returns>

        public string RunQuery3(
            ResultsFormat rf,
            bool saveHitlist,
            bool browseExistingResults)
        {
            Query        modifiedQuery;
            QueryTable   qt;
            QueryColumn  qc;
            ResultsTable rt;
            ResultsField rfld;
            MetaTable    mt;
            MetaColumn   mc;
            string       txt, msg;
            DialogResult dr;
            bool         success;
            CellGraphic  cg;
            Lex          lex = new Lex();
            string       tempfile, tok, command, unrecognizedCommand, response;
            int          ti, gi, rc, i1, i2;

            // Begin execution

            if (rf == null)
            {
                throw new Exception("QueryExec.Run - Null ResultsFormat");
            }

            if (ResultsFormatter == null)
            {
                throw new Exception("QueryExec.Run - Null ResultsFormatter");
            }

            if (rf.Segments == null)
            {
                throw new Exception("QueryExec.Run - Null ResultsFormat.Segments");
            }

            if (Query == null)
            {
                throw new Exception("QueryExec.Run - Null Rf.Query");
            }

            if (Query.Tables == null || Query.Tables.Count <= 0)
            {
                throw new QueryException("QueryExec.Run - No Query Tables");
            }

            QueryManager qm = QueryManager;

            ReturnMsg = "";

            //bool useExistingQueryEngine = Rf.ParentQe != null;
            //bool useExistingDataTable = Query.BrowseExistingResultsWhenOpened && Query.SerializeResults &&
            //  qm.DataTable != null && qm.DataTable.Rows.Count > 0;

            try
            {
                //if (Math.Sqrt(4) == 2) throw new Exception("test"); // debug

                if (!browseExistingResults)                 // normal open of search
                {
                    Progress.Show("Analyzing query...");    // put up a status message to the user as soon as possible to let them know something is happening...

                    dr = ValidateQuery(Query);
                    if (dr == DialogResult.Cancel)
                    {
                        return("");
                    }

                    WriteCurrentListToServerIfNeeded(Query);

                    if (rf.OutputDestination == OutputDest.WinForms)                     // update access stats if grid
                    {
                        UpdateTableUsageStatistics(Query);
                    }

                    Query.ResultsDataTable = null;                     // be sure to get new results

                    qm = BuildQueryManager(Query, rf);

                    Query.ResetViewStates();                     // reset state of views for proper operation

                    if (Rf.ParentQe == null)                     // open search unless using existing query engine
                    {
                        if (!ExecuteSearch(saveHitlist))         // returns false if cancelled by user
                        {
                            Progress.Hide();
                            return("");
                        }
                    }

                    if ((ResultsKeys == null || ResultsKeys.Count == 0) &&                      // nothing for search
                        !Query.Preview &&
                        !MqlUtil.SingleStepExecution(Query) &&
                        qm.DataTable.Rows.Count == 0 &&
                        Query.RetrievesDataFromQueryEngine)
                    {
                        // if (!Rf.PopupDisplay)
                        Progress.Hide();
                        if (qm.StatusBarManager != null)
                        {
                            qm.StatusBarManager.DisplayStatusMessage("");
                        }
                        // if (QueryEngine.Cancelled) return ""; // cancelled by user
                        msg = "No data have been found that matches your query.";
                        if (ResultsFormat.PopupOutputFormContext && !ResultsFormat.SuppressNoDataMessage)
                        {
                            MessageBoxMx.Show(msg, "Search Result",
                                              MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return("Command EditQuery");                            // return to edit query menu
                        }
                        else
                        {
                            return(msg);
                        }
                    }

                    //if (ResultsFormat.PopupDisplay)
                    //  SessionManager.DisplayStatusMessage("Retrieving data...");
                    //else Progress.Show("Retrieving data...", UmlautMobius.Value, true, "Cancelling Retrieval...");

                    //Progress.Show("Retrieving data...", UmlautMobius.String, true, "Cancelling Retrieval...");
                    Progress.Hide();                     // hide progress - "Retrieving data..." message now appears as bottom line of grid

                    if (ResultsFormat.Grid)
                    {
                        if (ResultsFormat.SessionOutputFormContext)              // if normal main session form grid display, set browse mode & view state
                        {
                            Query.ResetViewStates();                             // reset view state for all views
                            QbUtil.SetMode(QueryMode.Browse, Query);

                            if (ResultsFormat.Query.LogicType == QueryLogicType.And)                             // log grid query by logic type
                            {
                                UsageDao.LogEvent("QueryGridAnd", "");
                            }
                            else if (ResultsFormat.Query.LogicType == QueryLogicType.Or)
                            {
                                UsageDao.LogEvent("QueryGridOr", "");
                            }
                            else if (ResultsFormat.Query.LogicType == QueryLogicType.Complex)
                            {
                                UsageDao.LogEvent("QueryGridComplex", "");
                            }
                        }

                        else if (ResultsFormat.PopupOutputFormContext)                         // create popup window & configure
                        {
                            PopupResults.Show(qm);
                            //MoleculeGridPanel.ConfigureAndShow(qm, null);
                        }

                        else if (ResultsFormat.ToolOutputFormContext)
                        {
                            ContainerControl    cc;
                            QueryResultsControl qrc = ResultsFormat.OutputContainerControl as QueryResultsControl;
                            AssertMx.IsTrue(qrc != null, "ResultsFormat.OutputContainerControl must be a QueryResultsControl");
                            if (!WindowsHelper.FindContainerControl(qrc, typeof(ToolResultsContainer), out cc))
                            {
                                throw new Exception("ToolResultsContainer not found");
                            }

                            ToolResultsContainer trc = cc as ToolResultsContainer;
                            trc.SetupQueryResultsControlForResultsDisplay(qm);
                        }

                        else
                        {
                            throw new Exception("Invalid OutputformContext: " + ResultsFormat.OutputFormContext);
                        }
                    }
                }

                else                 // reentering display switch to browse tab
                {
                    QbUtil.SetMode(QueryMode.Browse, Query);
                }

                response = ResultsFormatter.BeginFormatting(browseExistingResults); // format the data

                if (ResultsFormat.SessionOutputFormContext)                         // normal display
                {
                    if (MqlUtil.SingleStepExecution(Query))
                    {                     // be sure hit count display is up to date
                        if (ResultsKeys != null)
                        {
                            if (qm.StatusBarManager != null)
                            {
                                qm.StatusBarManager.DisplayCurrentCount();
                            }
                        }
                    }

                    if (saveHitlist)
                    {
                        CidList hitList = new CidList(ResultsKeys);
                        rc = CidListCommand.WriteCurrentList(hitList);
                        SessionManager.DisplayCurrentCount();
                    }
                }

                return(response);
            }             // end of surrounding try

            catch (Exception ex)
            {
                Progress.Hide();
                if (ex is UserQueryException)                 // exception that can occur from user error
                {
                    throw new UserQueryException(ex.Message, ex);
                }

                else
                {
                    msg = DebugLog.FormatExceptionMessage(ex);
                    if (!Lex.Contains(msg, "QueryLogged:"))                     // exception & query
                    {
                        QueryEngine.LogExceptionAndSerializedQuery(msg, Query);
                    }
                    else
                    {
                        ServicesLog.Message(msg);                      // just log exception
                    }
                    throw new Exception(ex.Message, ex);               // pass it up
                }
            }
        }
示例#14
0
/// <summary>
/// Right-click commands on objects in a tree
/// </summary>
/// <param name="command">The command to process</param>
        /// <param name="mtn">MetaTreeNode</param>
        /// <param name="uo">Any associated user object</param>
        /// <param name="ctc">ContentsTreeControl</param>
/// <returns></returns>

        public static bool ProcessCommonRightClickObjectMenuCommands(
            string command,
            MetaTreeNode mtn,
            UserObject[] uoArray,
            ContentsTreeControl ctc)
        {
            UserObject uo2;
            string     txt;
            UserObject uo = null;

            if (uoArray != null && uoArray.Length == 1)
            {
                uo = uoArray[0];
            }

            //if (mtn == null)
            //{
            //	MessageBoxMx.ShowError("Operation is not allowed for this Database Contents node.");
            //	return true;
            //}

            if (Lex.Eq(command, "Cut"))
            {
                CopyCutDelete(command, uoArray, ctc, true, true);
            }

            else if (Lex.Eq(command, "Copy"))
            {
                CopyCutDelete(command, uoArray, ctc, true, false);
            }

            else if (Lex.Eq(command, "Paste"))
            {
                try
                {
                    txt = Clipboard.GetText();
                    //uo2 = UserObject.Deserialize(txt);
                    uoArray = Deserialize(txt);
                    if (uoArray == null)
                    {
                        throw new Exception("Not a UserObject");
                    }
                    //if (uo2 == null) throw new Exception("Not a UserObject");
                }
                catch (Exception ex)
                {
                    MessageBoxMx.ShowError("The clipboard does not contain a recognized user objects");
                    return(true);
                }

                foreach (var userObject in uoArray)
                {
                    Progress.Show("Pasting " + userObject.Name + "...", UmlautMobius.String, false);

                    Permissions.UpdateAclForNewOwner(userObject, userObject.Owner, SS.I.UserName); // fixup the ACL for the new owner
                    userObject.Owner        = SS.I.UserName;
                    userObject.ParentFolder = mtn.Name;
                    mtn = UserObjectTree.GetValidUserObjectTypeFolder(userObject);

                    for (int ci = 0; ; ci++) // find a name that's not used
                    {
                        UserObject uo3 = UserObjectDao.ReadHeader(userObject);
                        if (uo3 == null)
                        {
                            break;
                        }

                        if (ci == 0)
                        {
                            userObject.Name = "Copy of " + userObject.Name;
                        }
                        else if (ci == 1)
                        {
                            userObject.Name = Lex.Replace(userObject.Name, "Copy of ", "Copy (2) of ");
                        }
                        else
                        {
                            userObject.Name = Lex.Replace(userObject.Name, "Copy (" + ci + ") of ", "Copy (" + (ci + 1) + ") of ");
                        }
                    }

                    UserObject userObjectFinal = null;
                    if (UserObjectDao.ReadHeader(userObject.Id) != null) // create a deep clone if orignal object exists
                    {
                        userObjectFinal = DeepClone(userObject);
                    }

                    if (userObjectFinal == null)
                    {
                        userObjectFinal = userObject;
                    }

                    UserObjectDao.Write(userObjectFinal, userObjectFinal.Id); // write using the current id

                    Progress.Hide();
                }

                //if (ctc != null) // need to update form directly?
                //  UserObjectTree.RefreshSubtreeInTreeControl(uo2, ctc);
            }

            else if (Lex.Eq(command, "Delete"))
            {
                CopyCutDelete(command, uoArray, ctc, false, true);
            }

            else if (Lex.Eq(command, "Rename"))
            {
                if (!UserHasWriteAccess(uo))
                {
                    MessageBoxMx.ShowError("You are not authorized to rename " + uo.Name);
                    return(true);
                }

                string newName = InputBoxMx.Show("Enter the new name for " + uo.Name,
                                                 "Rename", uo.Name);

                if (newName == null || newName == "" || newName == uo.Name)
                {
                    return(true);
                }

                if (!IsValidUserObjectName(newName))
                {
                    MessageBoxMx.ShowError("The name " + newName + " is not valid.");
                    return(true);
                }

                uo2      = uo.Clone();
                uo2.Name = newName;
                uo2.Id   = 0;               // clear Id so not looked up by id

                if (!Lex.Eq(newName, uo.Name) && UserObjectDao.ReadHeader(uo2) != null)
                {
                    MessageBoxMx.ShowError(newName + " already exists.");
                    return(true);
                }

                uo2.Id = uo.Id;
                UserObjectDao.UpdateHeader(uo2);

                if (ctc != null)
                {
                    UserObjectTree.UpdateObjectInTreeControl(uo, uo2, ctc);
                }
            }

            else if (Lex.Eq(command, "MakePublic") ||
                     Lex.Eq(command, "MakePrivate"))
            {
                UserObjectAccess newAccess;
                MetaTreeNode     objFolder;

                if (!UserHasWriteAccess(uo))
                {
                    MessageBoxMx.ShowError("You are not authorized to make " + uo.Name +
                                           ((Lex.Eq(command, "MakePublic")) ? " public" : " private"));
                    return(true);
                }

                if (Lex.Eq(command, "MakePublic"))
                {
                    if (uo.ParentFolder == "DEFAULT_FOLDER")
                    {
                        MessageBoxMx.ShowError("Items in the Default Folder cannot be made public");
                        return(true);
                    }
                    else
                    {
                        //check the folder id parentage to ensure that the current folder isn't a subfolder of the default folder
                        if (UserObjectTree.FolderNodes.ContainsKey(uo.ParentFolder))
                        {
                            objFolder = UserObjectTree.FolderNodes[uo.ParentFolder];
                            while (objFolder != null)
                            {
                                if (objFolder.Target == "DEFAULT_FOLDER")
                                {
                                    MessageBoxMx.ShowError("Items in the Default Folder cannot be made public");
                                    return(true);
                                }
                                objFolder = objFolder.Parent;
                            }
                        }
                        else
                        {
                            throw new Exception("Failed to recognize the folder that this object is in!");
                        }
                    }

                    newAccess = UserObjectAccess.Public;
                }
                else
                {
                    //user folders cannot be made private if they contain public children
                    if (uo.Type == UserObjectType.Folder)
                    {
                        objFolder = UserObjectTree.BuildNode(uo);
                        if (UserObjectTree.FolderNodes.ContainsKey(objFolder.Target))
                        {
                            objFolder = UserObjectTree.FolderNodes[objFolder.Target];
                            for (int i = 0; i < objFolder.Nodes.Count; i++)
                            {
                                MetaTreeNode currentChild = (MetaTreeNode)objFolder.Nodes[i];
                            }
                        }
                    }

                    newAccess = UserObjectAccess.Private;
                }

                uo2 = UserObjectDao.Read(uo);
                if (uo2 == null)
                {
                    return(true);
                }
                if (uo2.AccessLevel == newAccess)
                {
                    return(true);                                              // no change
                }
                uo2.AccessLevel = newAccess;
                UserObjectDao.UpdateHeader(uo2);

                if (ctc != null)                 // need to update form directly?
                {
                    UserObjectTree.RefreshSubtreeInTreeControl(uo2, ctc);
                }

                return(true);
            }

            else if (Lex.Eq(command, "ChangeOwner"))
            {
                string newOwner = InputBoxMx.Show("Enter the user name of the person to transfer ownership of " + Lex.AddDoubleQuotes(uo.Name) + " to:",
                                                  "Change Owner", "");

                if (Lex.IsNullOrEmpty(newOwner))
                {
                    return(true);
                }

                string result = UserObjectUtil.ChangeOwner(uo.Id, newOwner);
                if (!Lex.IsNullOrEmpty(result))
                {
                    MessageBoxMx.Show(result);
                }
                return(true);
            }

            else if (Lex.Eq(command, "Permissions"))             // set object permissions
            {
                PermissionsDialog.Show(uo);
                return(true);
            }

            else if (Lex.Eq(command, "ViewSource"))
            {
                uo = UserObjectDao.Read(uo);
                if (uo == null)
                {
                    return(true);
                }

                string ext = ".txt";                 // default extension
                if (uo.Type == UserObjectType.Query ||
                    uo.Type == UserObjectType.Annotation)
                {
                    ext = ".xml";
                }
                string       cFile = ClientDirs.TempDir + @"\Source" + ext;
                StreamWriter sw    = new StreamWriter(cFile);
                sw.Write(uo.Content);
                sw.Close();

                SystemUtil.StartProcess(cFile);                 // show it
            }

            else
            {
                return(false);       // command not recognized
            }
            return(true);            // command recognized and processed
        }
示例#15
0
        /// <summary>
        /// Selected a new target map
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void TargetMap_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (InSetup)
            {
                return;
            }
            string newTargetMap = TargetMap.Text;

            if (Lex.Eq(newTargetMap, "Retrieve KEGG Pathway...")) // lookup KEGG pathway
            {
                if (Math.Abs(1) == 1)                             // 2/1/2013, best available now e.g. http://www.kegg.jp/kegg-bin/show_pathway?hsa04010
                {
                    MessageBoxMx.ShowError(@"Automated access to pathway maps is now available through subsciption only.");
                    return;
                }

                SetTargetMapText(SelectedTargetMap);                 // keep current map for now

                string pathwayId = InputBoxMx.Show(
                    "Enter the KEGG pathway id (e.g. hsa00010) for the desired pathway. " +
                    "Pathway identifiers can be looked up at: " +
                    "<a href=\"http://www.genome.jp/kegg/pathway.html\" target=\"_blank\">http://www.genome.jp/kegg/pathway.html</a>",
                    "KEGG Pathway Identifier");

                if (String.IsNullOrEmpty(pathwayId))
                {
                    return;
                }

                try
                {
                    Progress.Show("Retrieving KEGG information for pathway: " + pathwayId, UmlautMobius.String, false);
                    TargetMap tm = TargetMapDao.GetKeggPathway(pathwayId);
                    Progress.Hide();
                    if (!MapLabelDict.ContainsKey(tm.Label.ToUpper()))
                    {
                        MapLabelDict[tm.Label.ToUpper()] = null;
                        MapLabelList.Add(tm.Label);
                        UserMapNames.Add(tm.Name);
                    }

                    TargetMap.Properties.Items.Clear();
                    TargetMap.Properties.Items.AddRange(MapLabelList);       // update list
                    SelectedTargetMap = tm.Label;
                    SetTargetMapText(SelectedTargetMap);                     // make current selection
                }

                catch (Exception ex)
                {
                    string msg = ex.Message;
                    Progress.Hide();
                    MessageBoxMx.ShowError("Pathway not found");
                    return;
                }

                return;
            }

            else if (newTargetMap.StartsWith("---"))             // divider selected, ignore
            {
                SetTargetMapText(SelectedTargetMap);
            }

            SetTargetMapText(newTargetMap);             // new map selected
        }
示例#16
0
        /// <summary>
        /// Retrieve the results of a background export
        /// Example: Retrieve Background Export 231243
        /// </summary>
        /// <param name="objectIdString">Id of BackgroundExport UserObject containing serialized ResultsFormat</param>
        /// <returns></returns>

        public static string RetrieveBackgroundExport(
            string objectIdString)
        {
            ResultsFormat rf;
            Query         q;
            int           objId;

            QbUtil.SetMode(QueryMode.Build);             // be sure in build mode

            if (!int.TryParse(objectIdString, out objId))
            {
                return("Invalid UserObjectId: " + objectIdString);
            }

            UserObject uo = UserObjectDao.Read(objId);

            if (uo == null)
            {
                return("RunInBackground UserObject not found: " + objectIdString);
            }
            if (uo.Type != UserObjectType.BackgroundExport)
            {
                return("Object is not the expected RunInBackground UserObject type");
            }

            rf = ResultsFormat.Deserialize(uo.Content);
            if (rf == null)
            {
                throw new Exception("Failed to deserialize ResultsFormat: " + objectIdString);
            }

            string clientFile = rf.OutputFileName;
            string serverFile = GetServerFileName(rf, objId);

            string ext    = Path.GetExtension(clientFile);
            string filter = "*" + ext + "|*" + ext;

            if (SharePointUtil.IsRegularFileSystemName(clientFile))
            {
                clientFile = UIMisc.GetSaveAsFilename("Retrieve Background Export File", clientFile, filter, ext);
            }

            else
            {
                clientFile =
                    SharePointFileDialog.GetSaveAsFilename("Retrieve Background Export File", clientFile, filter, ext);
            }

            if (String.IsNullOrEmpty(clientFile))
            {
                return("");
            }

            Progress.Show("Retrieving file...");
            try { ServerFile.CopyToClient(serverFile, clientFile); }
            catch (Exception ex)
            {
                string msg =
                    "Unable to retrieve cached export file: " + serverFile + "\n" +
                    "to client file: " + clientFile + "\n" +
                    DebugLog.FormatExceptionMessage(ex);
                ServicesLog.Message(msg);
                Progress.Hide();
                return(msg);
            }

            Progress.Hide();

            if (Lex.Eq(ext, ".xls") || Lex.Eq(ext, ".xlsx") || Lex.Eq(ext, ".doc") || Lex.Eq(ext, ".docx"))
            {
                DialogResult dr = MessageBoxMx.Show("Do you want to open " + clientFile + "?",
                                                    UmlautMobius.String, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr == DialogResult.Yes)
                {
                    SystemUtil.StartProcess(clientFile);
                }
            }

            return("Background export file retrieved: " + clientFile);
        }
示例#17
0
        /// <summary>
        /// Check queued alerts. Several of these process may be running at the same time in parallel.
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>

        public static string CheckQueuedAlerts(
            string args)
        {
            string msg;
            int    i1;
            bool   forceCheck        = false;
            bool   checkOnly         = false;
            int    firstToCheck      = 0;
            bool   hasMoreAlerts     = true;
            int    alertsWithNewData = 0;
            int    alertsChecked     = 0;

            string processorIdTxt = ", Pid: " + (int)DateTime.Now.TimeOfDay.TotalSeconds;             // mark each message with id of processor (sec of day started)

            AlertUtil.LogAlertMessage("Queue processor started: " + args + processorIdTxt);

            if (args != null && args.Trim().Length > 0)
            {
                if (Lex.Contains(args, "forceCheck"))
                {
                    forceCheck = true;
                }
                if (Lex.Contains(args, "checkOnly"))
                {
                    checkOnly = true;
                }
            }

            string alertQueueFileName = GetAlertQueueFileName();

            while (hasMoreAlerts)
            {
                UserObject uo = GetNextAlert(processorIdTxt, alertQueueFileName);
                if (uo == null)
                {
                    break;
                }

                int queryId = 0;                 // get queryId from alert name
                i1 = uo.Name.IndexOf("_");
                if (i1 > 0)
                {
                    try { queryId = Int32.Parse(uo.Name.Substring(i1 + 1)); }
                    catch (Exception) { }
                }

                msg = "Processing Alert: " + uo.Id +
                      ", QueryId: " + queryId + processorIdTxt;
                //			Thread.Sleep(10000); // debug
                AlertUtil.LogAlertMessage(msg);
                Progress.Show(msg);

                DateTime begin = DateTime.Now;
                try                 // check it
                {
                    msg = AlertUtil.Check(uo, forceCheck, checkOnly, false);
                }
                catch (Exception ex)
                {
                    msg = "Error executing Alert: " + uo.Id +
                          ", QueryId: " + queryId + ", Processor: " + processorIdTxt;

                    if (Lex.Contains(ex.Message, "ORA-01012") || Lex.Contains(ex.Message, "ORA-00028"))
                    {
                        msg += ", Error: " + ex.Message; // keep simple if forced logoff
                    }
                    else                                 // include stack trace otherwise
                    {
                        msg += "Error: " + DebugLog.FormatExceptionMessage(ex, msg);
                    }

                    AlertUtil.LogAlertMessage(msg);
                    AlertUtil.LogAlertErrorMessage(msg);
                    alertsChecked++;
                    continue;
                }

                if (Lex.Contains(msg, "Delayed Alert"))
                {
                    AlertUtil.LogAlertMessage(msg);
                    Alert alert = Alert.GetAlertFromUserObject(uo, true);
                    AddAlertBack(alert);
                    SleepUntilNextAlertStartTime(uo);
                    continue;
                }

                string msg0 =                  // message prefix
                              "Completed Alert: " + uo.Id + ", QueryId: " + queryId + processorIdTxt;

                //DateTime end = DateTime.Now; // (redundant)
                //TimeSpan elapsed = end.Subtract(begin);
                //string eTxt = elapsed.ToString();
                //if ((i1 = eTxt.IndexOf(".")) > 0) eTxt = eTxt.Substring(0, i1);
                //msg0 += ", Time to process = " + eTxt;

                msg = msg0 + " " + msg;
                AlertUtil.LogAlertMessage(msg);

                if (Lex.Contains(msg, "Error executing alert"))                 // keep separate log of errors
                {
                    AlertUtil.LogAlertErrorMessage(msg);
                }

                alertsChecked++;
                if (msg.Contains("Changed compounds"))
                {
                    alertsWithNewData++;
                }
            }

            msg = "Queue processor complete, Alerts checked: " + alertsChecked +
                  ", Alert E-mails: " + alertsWithNewData + processorIdTxt;

            AlertUtil.LogAlertMessage("");
            AlertUtil.LogAlertMessage(msg);
            Progress.Hide();
            return(msg);
        }
示例#18
0
        /// <summary>
        /// Create an annotation table from a DataTable
        /// </summary>
        /// <param name="fullyQualifiedName">Fully qualified name to assign to table</param>
        /// <param name="dataTable">DataTable containing table definition & data</param>
        /// <param name="showProgress">Display dialog box showing progress of creation</param>
        /// <returns>Internal name assigned to annotation table (ANNOTATION_12345)</returns>

        public static MetaTable CreateAnnotationTable(
            string fullyQualifiedName,
            DataTable dataTable,
            bool showProgress)
        {
            List <AnnotationVo> voList = new List <AnnotationVo>();
            AnnotationVo        avo;

            if (dataTable == null)
            {
                DebugMx.ArgException("DataTable is null");
            }
            if (dataTable.Columns.Count == 0)
            {
                DebugMx.ArgException("No DataColumns are defined");
            }
            if (dataTable.Columns[0].DataType != typeof(CompoundId))
            {
                DebugMx.ArgException("The first column must be of type CompoundId");
            }

            if (showProgress)
            {
                Progress.Show("Creating annotation table...");
            }

            AnnotationDao aDao = new AnnotationDao();
            UserObject    auo  = UserObjectUtil.ParseInternalUserObjectName(fullyQualifiedName);

            auo.Type = UserObjectType.Annotation;
            UserObjectTree.GetValidUserObjectTypeFolder(auo);
            UserObject auo2  = UserObjectDao.Read(auo);            // see if there already
            MetaTable  oldMt = null;

            if (auo2 == null)                       // get new identifier
            {
                auo.Id = UserObjectDao.GetNextId(); // id to store table under
            }
            else                                    // reuse identifier
            {
                auo.Id = auo2.Id;                   // copy it over
                aDao.DeleteTable(auo.Id);           // delete any existing data
                string oldMtName = "ANNOTATION_" + auo2.Id;
                oldMt = MetaTableCollection.Get(oldMtName);
            }

            MetaTable mt = new MetaTable();

            mt.MetaBrokerType = MetaBrokerType.Annotation;
            mt.Name           = "ANNOTATION_" + auo.Id; // name table by uo
            mt.Label          = auo.Name;
            mt.Code           = auo.Id.ToString();      // code for the metatable
            int mtCode = auo.Id;

            if (dataTable.ExtendedProperties.ContainsKey("ParentTableName"))
            {
                mt.Parent = MetaTableCollection.Get((string)dataTable.ExtendedProperties["ParentTableName"]);
            }

            foreach (DataColumn dc in dataTable.Columns)
            {
                MetaColumn mc = new MetaColumn();
                mc.MetaTable = mt;
                mc.Name      = dc.ColumnName;
                MetaColumn oldMc = null;
                if (oldMt != null)
                {
                    oldMc = oldMt.GetMetaColumnByName(mc.Name);              // see if column name exists
                }
                if (oldMc != null && oldMc.ResultCode != "")                 // use any existing code
                {
                    mc.ResultCode = oldMc.ResultCode;
                }
                else
                {
                    mc.ResultCode = aDao.GetNextIdLong().ToString();
                }

                if (dc.Caption != null)
                {
                    mc.Label = dc.Caption;
                }
                else
                {
                    mc.Label = mc.Name;
                }
                if (dc.DataType == typeof(CompoundId))
                {
                    mc.DataType = MetaColumnType.CompoundId;
                    if (dc.ExtendedProperties.ContainsKey("StorageType") && dc.ExtendedProperties["StorageType"] is MetaColumnType &&
                        ((MetaColumnType)dc.ExtendedProperties["StorageType"]) == MetaColumnType.String)
                    {
                        mc.ColumnMap = "EXT_CMPND_ID_TXT";                         // text column
                    }
                    else
                    {
                        mc.ColumnMap = "EXT_CMPND_ID_NBR";                      // numeric column otherwise
                    }
                }
                else if (dc.DataType == typeof(int) || dc.DataType == typeof(Int16) || dc.DataType == typeof(Int32))
                {
                    mc.DataType = MetaColumnType.Integer;
                }
                else if (dc.DataType == typeof(float) || dc.DataType == typeof(double))
                {
                    mc.DataType = MetaColumnType.Number;
                }
                else if (dc.DataType == typeof(QualifiedNumber))
                {
                    mc.DataType = MetaColumnType.QualifiedNo;
                }
                else if (dc.DataType == typeof(string))
                {
                    mc.DataType = MetaColumnType.String;
                }
                else if (dc.DataType == typeof(DateTime))
                {
                    mc.DataType = MetaColumnType.Date;
                }
                else if (dc.DataType == typeof(MoleculeMx))
                {
                    mc.DataType = MetaColumnType.Structure;
                }
                else
                {
                    throw new Exception("Invalid data type " + dc.DataType.ToString());
                }

                if (dc.ExtendedProperties.ContainsKey("DisplayLevel"))
                {
                    mc.InitialSelection = (ColumnSelectionEnum)dc.ExtendedProperties["DisplayLevel"];
                }
                if (dc.ExtendedProperties.ContainsKey("DisplayWidth"))
                {
                    mc.Width = (float)dc.ExtendedProperties["DisplayWidth"];
                }
                if (dc.ExtendedProperties.ContainsKey("DisplayFormat"))
                {
                    mc.Format = (ColumnFormatEnum)dc.ExtendedProperties["DisplayFormat"];
                }
                if (dc.ExtendedProperties.ContainsKey("Decimals"))
                {
                    mc.Decimals = (int)dc.ExtendedProperties["Decimals"];
                }

                mt.MetaColumns.Add(mc);
            }

            ToolHelper.CreateAnnotationTable(mt, auo);

            aDao.BeginTransaction();             // insert all data in single transaction

            if (showProgress)
            {
                Progress.Show("Writing data to annotation table...");
            }
            int t1         = TimeOfDay.Milliseconds();
            int writeCount = 0;

            foreach (DataRow dr in dataTable.Rows)
            {
                if (dr.IsNull(0))
                {
                    continue;                               // shouldn't happen
                }
                string key = dr[0].ToString();
                key = CompoundId.NormalizeForDatabase(key, mt.Root);
                long rslt_grp_id = aDao.GetNextIdLong();

                for (int ci = 1; ci < dataTable.Columns.Count; ci++)                 // do columns after key
                {
                    if (dr.IsNull(ci))
                    {
                        continue;
                    }
                    DataColumn dc     = dataTable.Columns[ci];
                    MetaColumn mc     = mt.MetaColumns[ci];
                    int        mcCode = Int32.Parse(mc.ResultCode);
                    avo             = new AnnotationVo();
                    avo.rslt_grp_id = rslt_grp_id;                     // keep row together

                    if (dc.DataType == typeof(CompoundId))             // shouldn't happen since key processed already
                    {
                        avo.rslt_val_txt = dr[ci].ToString();
                    }

                    else if (dc.DataType == typeof(int) || dc.DataType == typeof(Int16) || dc.DataType == typeof(Int32) ||
                             dc.DataType == typeof(float) || dc.DataType == typeof(double))
                    {
                        avo.rslt_val_nbr = (double)dr[ci];
                    }

                    else if (dc.DataType == typeof(QualifiedNumber))
                    {
                        QualifiedNumber qn = (QualifiedNumber)dr[ci];
                        avo.rslt_val_nbr      = qn.NumberValue;
                        avo.rslt_val_prfx_txt = qn.Qualifier;
                        avo.rslt_val_txt      = qn.TextValue;
                        avo.dc_lnk            = qn.Hyperlink;
                    }

                    else if (dc.DataType == typeof(string))
                    {
                        avo.rslt_val_txt = dr[ci].ToString();
                    }

                    else if (dc.DataType == typeof(DateTime))
                    {
                        avo.rslt_val_dt = (DateTime)dr[ci];
                    }

                    else if (dc.DataType == typeof(MoleculeMx))
                    {
                        avo.rslt_val_txt = dr[ci].ToString();
                    }

                    AddAnnotationVoToList(avo, key, mtCode, mcCode, voList);
                }

                writeCount++;

                if (Progress.CancelRequested)                 // check for cancel
                {
                    aDao.Commit();
                    aDao.Insert(voList);
                    voList.Clear();
                    aDao.Commit();
                    aDao.Dispose();
                    if (showProgress)
                    {
                        Progress.Hide();
                    }
                    MessageBoxMx.ShowError("Writing of annotation table cancelled.");
                    return(null);
                }

                int t2 = TimeOfDay.Milliseconds();
                if (showProgress && t2 - t1 >= 1000)
                {
                    t1 = t2;
                    Progress.Show("Writing data to annotation table " + writeCount.ToString() +
                                  " of " + dataTable.Rows.Count.ToString() + " ...");
                    aDao.Insert(voList);
                    voList.Clear();
                    aDao.Commit();
                }
            }

            aDao.Insert(voList);
            voList.Clear();
            aDao.Commit();
            aDao.Dispose();

            if (showProgress)
            {
                Progress.Hide();
            }
            return(mt);            // return metatable name
        }
示例#19
0
/// <summary>
/// Build & show the Print Preview dialog
/// </summary>
/// <param name="printableDxControl"></param>
/// <returns></returns>

        static DialogResult ShowDialog(
            IPrintable printableDxControl)
        {
            string leftColumn, middleColumn, rightColumn;
            int    m;

            Query query      = Instance.Qm.Query;
            int   printScale = query.PrintScale;           // scale the document

            if (printScale < 0 && !(Instance.Qm.MoleculeGrid.MainView is DevExpress.XtraGrid.Views.BandedGrid.BandedGridView))
            {             // if not banded view be sure not fit to width
                printScale = query.PrintScale = 100;
            }

            Instance.Qm.ResultsFormat.PageScale = printScale;             // do view scaling based on printScale
            ResultsFormat rf = Instance.Qm.ResultsFormat;

            PrintingSystem ps = new PrintingSystem();

            Instance.Ps = ps;
            Instance.PrintControl.PrintingSystem = ps;

            PrintableComponentLink pcl = new PrintableComponentLink(ps);

            Instance.Pcl  = pcl;
            pcl.Component = printableDxControl;
            ps.Links.Add(pcl);
            pcl.CreateDetailArea          += new CreateAreaEventHandler(Instance.PrintableComponentLink_CreateDetailArea);
            pcl.CreateDetailHeaderArea    += new CreateAreaEventHandler(Instance.PrintableComponentLink_CreateDetailHeaderArea);
            pcl.CreateInnerPageHeaderArea += new CreateAreaEventHandler(Instance.PrintableComponentLink_InnerPageHeaderArea);
            pcl.CreateMarginalHeaderArea  += new CreateAreaEventHandler(Instance.PrintableComponentLink_CreateMarginalHeaderArea);
            pcl.CreateReportHeaderArea    += new CreateAreaEventHandler(Instance.PrintableComponentLink_CreateReportHeaderArea);

            if (query.PrintMargins > 0)
            {
                m           = query.PrintMargins / 10;
                pcl.Margins = new Margins(m, m, m, m);
            }
            if (query.PrintOrientation == Orientation.Vertical)
            {
                pcl.Landscape = false;
            }
            else
            {
                pcl.Landscape = true;
            }

            PageHeaderFooter phf = pcl.PageHeaderFooter as PageHeaderFooter;

            phf.Header.Content.Clear();
            middleColumn = rf.Query.UserObject.Name;             // use query name for heading
            phf.Header.Content.AddRange(new string[] { "", middleColumn, "" });
            phf.Header.LineAlignment = BrickAlignment.Center;
            phf.Header.Font          = new Font("Arial", 10, FontStyle.Bold);

            leftColumn   = "Mobius: " + DateTimeMx.Format(DateTimeMx.GetCurrentDate());
            middleColumn = "Confidential";
            rightColumn  = "Page [Page #]";
            phf.Footer.Content.Clear();
            phf.Footer.Content.AddRange(new string[] { leftColumn, middleColumn, rightColumn });
            phf.Footer.LineAlignment = BrickAlignment.Center;

            // Todo: If DataTable is big just use a subset for preview? Takes about 5 secs to format 100 structs.

            Instance.PreviewRowCount = Instance.Qm.DataTable.Rows.Count;

            Progress.Show("Formatting preview...", "Mobius", true);
            pcl.CreateDocument();
            Progress.Hide();

            if (printScale > 0)                         // scale to percentage
            {
                ps.Document.ScaleFactor         = 1.0f; // keep document scale at 1.0
                ps.Document.AutoFitToPagesWidth = 0;
            }

            else
            {
                Instance.Qm.MoleculeGrid.ScaleBandedGridView(100.0);                // scale grid to full size before setting doc scale
                ps.Document.AutoFitToPagesWidth = (int)-printScale;                 // fit to 1 or more pages
                int pctScale = (int)(ps.Document.ScaleFactor * 100);
                Instance.Qm.ResultsFormat.PageScale = pctScale;
                Instance.Qm.MoleculeGrid.ScaleBandedGridView(pctScale / 100.0); // scale grid down to get structures correct size
                pcl.CreateDocument();                                           // recreate the doc
            }

            ps.StartPrint           += new PrintDocumentEventHandler(Instance.PrintingSystem_StartPrint);
            ps.PrintProgress        += new PrintProgressEventHandler(Instance.PrintingSystem_PrintProgress);
            ps.EndPrint             += new EventHandler(Instance.PrintingSystem_EndPrint);
            ps.ShowPrintStatusDialog = true;

            Form shell = SessionManager.Instance.ShellForm;

            Instance.Location    = shell.Location;
            Instance.Size        = shell.Size;
            Instance.WindowState = shell.WindowState;
            RibbonControl src = SessionManager.Instance.RibbonCtl;             // model this ribbon on shell ribbon

            if (src != null)
            {
                Instance.RibbonControl.RibbonStyle     = src.RibbonStyle;
                Instance.RibbonControl.ApplicationIcon = src.ApplicationIcon;
            }

            DialogResult dr = Instance.ShowDialog(shell);           // show the preview

            query.PrintMargins = pcl.Margins.Left * 10;             // keep margins in milliinches

            if (pcl.Landscape)
            {
                query.PrintOrientation = Orientation.Horizontal;
            }
            else
            {
                query.PrintOrientation = Orientation.Vertical;
            }

            Progress.Hide();             // just in case
            return(dr);
        }