Exemple #1
0
        /// <summary>
        /// RowHeight
        /// </summary>
        /// <param name="height"></param>

        public static void RowHeight(double height)
        {
            const int MaxRowHeight = 409;             // max Excel 2010 row height in points

            if (LogCalls)
            {
                DebugLog.Message("ExcelOp RowHeight " + height);
            }

            if (height > MaxRowHeight)
            {
                height = MaxRowHeight;                                    // keep within limit
            }
            try
            {
                if ((double)XlRange.RowHeight < height)
                {
                    XlRange.RowHeight = height;
                }
            }
            catch (Exception ex)
            {             // log Mobius 3.0 issue #200 (T. Richardson) exception
                string msg =
                    "ExcelOp.RowHeight (" + XlRange.Row + ", " + XlRange.Column + ") = " + height + "\r\n" +
                    DebugLog.FormatExceptionMessage(ex);
                ServicesLog.Message(msg);
                return;
            }
        }
Exemple #2
0
        /// <summary>
        /// Start new session to run background query
        /// </summary>
        /// <param name="bgeUoId">The Id of the BackgroundExport userobject </param>
        /// <returns></returns>

        public static string SpawnBackgroundQuery(
            int queryId,
            bool emailWhenDone)
        {
            string msg = "";

            string command = "RunQueryInBackground " + queryId + " " + emailWhenDone;

            try
            {
                CommandLine.StartBackgroundSession(command);
                msg = "The query has been started in the background.";
                if (emailWhenDone)
                {
                    msg += " A link to the results will be E-mailed to you when the query completes";
                }
            }

            catch (Exception ex)
            {
                msg = "Couldn't start new Mobius session:\n" + ex.Message;
                ServicesLog.Message(DebugLog.FormatExceptionMessage(ex, msg));
            }

            return(msg);
        }
Exemple #3
0
        /// <summary>
        /// Run query using supplied OutputDest displaying any error message
        /// </summary>
        /// <param name="query"></param>
        /// <param name="outputDest"></param>
        /// <returns></returns>

        public static string RunQuery(
            Query query,
            OutputDest outputDest)
        {
            try
            {
                bool browseExistingResults = QbUtil.BrowseExistingDataTable(query);
                return(RunQuery(query, outputDest, OutputFormContext.Session, null, browseExistingResults));
            }

            catch (UserQueryException ex)
            {             // just show message
                Progress.Hide();
                MessageBoxMx.ShowError(ex.Message);
                return("");
            }

            catch (Exception ex)
            {             // non-standard query exception, provide more detail
                Progress.Hide();
                string msg = DebugLog.FormatExceptionMessage(ex);

                if (!Lex.Contains(msg, "QueryLogged:"))                 // exception & query
                {
                    QueryEngine.LogExceptionAndSerializedQuery(msg, query);
                }
                else
                {
                    ServicesLog.Message(msg);                  // just log exception
                }
                MessageBoxMx.ShowError("Unexpected Exception\n\n" + msg);
                return("");
            }
        }
Exemple #4
0
        /// <summary>
        /// Log a Message
        /// </summary>
        /// <param name="msg"></param>

        public void Message(
            string msg,
            string logFileName)
        {
            ClientLog.Message(msg);                    // log to client

            if (!SF.ServiceFacade.UseRemoteServices)   // if not using remote services then
            {
                ServicesLog.Message(msg, logFileName); // write the message to the local services log also
            }
            return;
        }
Exemple #5
0
        /// <summary>
        /// Start a new instance of the Mobius client
        /// </summary>
        /// <param name="arg"></param>

        public static void StartNewClientProcess(
            string args)
        {
            string command = Application.ExecutablePath + " " + args;

            try
            {
                Process.Start(command);
            }
            catch (Exception ex)
            {
                ServicesLog.Message("UIMisc.StartNewClientProcess error on: " + command + "\n" +
                                    ex.Message);
            }
        }
Exemple #6
0
        /// <summary>
        /// Command entry to execute a query in the background and save the results for later retrieval
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>

        public static string RunBackgroundQuery(
            string args)
        {
            UserObject uo           = null;
            bool       sendEmail    = false;
            string     emailSubject = null;
            string     msg;
            int        queryId = -1;

            string[] sa = args.Split(' ');
            if (sa.Length > 0)
            {
                if (int.TryParse(sa[0].Trim(), out queryId))
                {
                    uo = UserObjectDao.Read(queryId);
                }
            }

            if (uo == null)
            {
                emailSubject = UmlautMobius.String + " background query results error";
                msg          = "RunQueryInBackground failed to read query " + queryId;
                ServicesLog.Message(msg);
                Email.Send(
                    null, SS.I.UserInfo.EmailAddress, emailSubject, msg);
                return(msg);
            }

            if (sa.Length > 1)
            {
                bool.TryParse(sa[1].Trim(), out sendEmail);
            }

            Query q = Query.Deserialize(uo.Content);

            q.UserObject = uo;             // copy user object to get current name, etc.
            q.IncludeRootTableAsNeeded();

            if (sendEmail)
            {
                emailSubject = UmlautMobius.String + " background query results for " + Lex.Dq(q.UserObject.Name);
            }
            return(RunBackgroundQuery(q, emailSubject, "MobiusBackgroundQueryEmailTemplate.htm"));
        }
Exemple #7
0
        /// <summary>
        /// Check for any connection leaks
        /// </summary>

        public static void CheckForConnectionLeaks()
        {
            if (!UserObjectTree.BuildComplete)
            {
                return;                                              // don't check while building tree
            }
            string leakMsg = DbConnection.CheckForConnectionLeaks(); // see if any connection leaks

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

            ServicesLog.Message(leakMsg);     // log it
            if (SS.I.IsDeveloper)             // show to dev
            {
                MessageBoxMx.ShowError(leakMsg);
            }
            return;
        }
Exemple #8
0
        /// <summary>
        /// Start new session to do background export
        /// </summary>
        /// <param name="bgeUoId">The Id of the BackgroundExport userobject </param>
        /// <returns></returns>

        public static string SpawnBackgroundExport(int bgeUoId)
        {
            string msg = "";

            string command = "run background export " + bgeUoId;

            try             // Example: Unattended IniFile = c:\\Mobius\\MobiusServer\\Server\\bin\\Debug\\MobiusServices.ini UserName = <userId> Command = 'run background export 919625'
            {
                CommandLine.StartBackgroundSession(command);
                msg =
                    "The Background Export has been started.\n" +
                    "You will receive an email when it completes.";
            }
            catch (Exception ex)
            {
                msg = "Failed to start background export: " + ex.Message;
                ServicesLog.Message(DebugLog.FormatExceptionMessage(ex, msg));
            }

            return(msg);
        }
Exemple #9
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);
        }
Exemple #10
0
        /// <summary>
        /// This method runs in a background process and exports data to the specified destination
        /// </summary>
        /// <param name="objectIdString">Id of UserObject containing run parameters in a serialized ResultsFormat</param>
        /// <param name="templateFileName">Name of template file to use</param>
        /// <param name="emailResultsHtml">If true then send email otherwise just return html</param>
        /// <returns></returns>

        public static string RunBackgroundExport(
            string objectIdString,
            string templateFileName,
            bool emailResultsHtml,
            out bool copiedToDestinationFile,
            int alertId = 0)
        {
            ResultsFormat rf;
            Query         q;
            string        msg = "";
            int           objId;

            //if (ClientState.IsDeveloper)
            //{
            //  ServicesLog.Message(SS.I.UserName + ": BackgrounExport Debug");
            //  //DataTableManager.AllowCaching = false;
            //  DataTableManager.DebugBasics = true;
            //  DataTableManager.DebugCaching = true;
            //}

            if (String.IsNullOrEmpty(templateFileName))
            {
                templateFileName = "MobiusBackgroundExportEmailTemplate.htm";
            }

            ServicesLog.Message("RunBackgroundExport started: UserObject id = " + objectIdString);
            string emailSubject = UmlautMobius.String + " background export results";

            copiedToDestinationFile = false;

            try
            {
                if (!int.TryParse(objectIdString, out objId))
                {
                    throw new Exception("Invalid UserObjectId");
                }

                UserObject uo = UserObjectDao.Read(objId);
                if (uo == null)
                {
                    throw new Exception("UserObject not found");
                }

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

                string clientFile = rf.OutputFileName;                 // ultimate file we want to go to

                rf.OutputFileName = GetServerFileName(rf, objId);      // get file name to export to on server & use here temporarily

                qm.ResultsFormat = rf;
                rf.QueryManager  = qm;

                q = QbUtil.ReadQuery(rf.QueryId);
                if (q == null)
                {
                    throw new Exception("Failed to read query: " + rf.QueryId);
                }
                q.IncludeRootTableAsNeeded();
                qm.Query       = q;
                q.QueryManager = qm;

                emailSubject += " for query " + Lex.Dq(q.UserObject.Name);                 // include query name in subject

                ResultsFormatFactory rff = new ResultsFormatFactory(rf);
                rff.Build();

                ResultsFormatter fmtr = new ResultsFormatter(qm);

                DataTableManager dtm = new DataTableManager(qm);
                dtm.BeginCaching();                                 // allow caching of DataTable
                dtm.PurgeDataTableWithoutWritingToCacheFile = true; // skip actual writing of cache since it won't be read back in

                qm.DataTableManager = dtm;

                qm.DataTable = DataTableManager.BuildDataTable(rf.Query);                 // build data table to receive data

                QueryExec qex = new QueryExec(rf);
                msg = qex.RunQuery3(rf, false, false);                 // do the export

                int compoundCount = 0;
                int rowCount      = 0;

                QueryEngine qe = qex.QueryEngine;
                if (qe != null)
                {
                    compoundCount = qm.DataTableManager.KeyCount;
                    rowCount      = qm.DataTableManager.TotalRowsTransferredToDataTable;                // use this for accurate row count
                }

                dtm.EndCaching();                        // close cache file (note: resets key/row counts)

                if (compoundCount <= 0 || rowCount <= 0) // any results
                {
                    msg = "Query " + Lex.Dq(q.UserObject.Name) + " returned no results.";
                    Email.Send(
                        null, SS.I.UserInfo.EmailAddress, emailSubject, msg);
                    return(msg);
                }

                if (ServerFile.CanWriteFileFromServiceAccount(clientFile))
                {                 // copy to dest file if possible
                    try
                    {
                        FileUtil.CopyFile(rf.OutputFileName, clientFile);
                        copiedToDestinationFile = true;
                        rf.OutputFileName       = clientFile;
                    }
                    catch (Exception ex)
                    {
                        ServicesLog.Message("Error copying file from service account: " + clientFile + "\n" + DebugLog.FormatExceptionMessage(ex));
                    }
                }

                string viewCmd = "Retrieve Background Export " + uo.Id;
                msg = "RunBackgroundExport ended: UserObjectId = " + objectIdString;

                if (emailResultsHtml)
                {
                    MailBackgroundExportResults(
                        q,
                        clientFile,
                        rowCount,
                        compoundCount,
                        copiedToDestinationFile,
                        viewCmd,
                        SS.I.UserInfo.EmailAddress,
                        emailSubject,
                        templateFileName);

                    ServicesLog.Message(msg);
                    return(msg);
                }

                else                 // just fill in values & return
                {
                    string html = ReadTemplateFile(templateFileName);
                    html = SubstituteBackgroundExportParameters(
                        html, "", rf.OutputFileName, rowCount, compoundCount, copiedToDestinationFile, viewCmd);
                    ServicesLog.Message(msg);
                    return(html);
                }
            }

            catch (Exception ex)
            {
                if (alertId > 0)
                {
                    msg += "Alert: " + alertId + " ";
                }
                msg +=
                    "RunBackgroundExport exception: BackgroundExportId = " + objectIdString + ",\r\n" +
                    DebugLog.FormatExceptionMessage(ex);
                Email.Send(
                    null, SS.I.UserInfo.EmailAddress, emailSubject, msg);
                ServicesLog.Message(msg);
                return(msg);
            }
        }
Exemple #11
0
/// <summary>
/// Method to run query in background and save the results for later retrieval
/// </summary>
/// <param name="q"></param>
/// <param name="emailSubject">Send email if defined</param>
/// <param name="templateName"></param>
/// <returns></returns>

        public static string RunBackgroundQuery(
            Query q,
            string emailSubject,
            string templateName)
        {
            ResultsFormat    rf;
            QueryManager     qm;
            DataTableManager dtm;
            string           msg = "", html = "", resultsFileName;
            string           viewCmd = "View Background Query Results";

            bool notifyUserByEmail = !Lex.IsNullOrEmpty(emailSubject);

            try                                       // execute the query & read in all results
            {
                QbUtil.AddQueryAndRender(q, false);   // add it to the query builder
                q.BrowseSavedResultsUponOpen = false; // be sure query is run rather than using existing results

                msg = QueryExec.RunQuery(q, OutputDest.WinForms);

                qm  = q.QueryManager as QueryManager;
                dtm = qm.DataTableManager;
                DialogResult dr = dtm.CompleteRetrieval();
            }
            catch (Exception ex)              // some exceptions are normal, e.g. no criteria, others may be bugs
            {
                msg = "RunQueryInBackground could not complete due to an unexpected exception: " + DebugLog.FormatExceptionMessage(ex);
                ServicesLog.Message(msg);
                if (notifyUserByEmail)
                {
                    Email.Send(null, SS.I.UserInfo.EmailAddress, emailSubject, msg);
                }

                return(msg);
            }

            if (dtm.KeyCount == 0)
            {
                msg = "Query " + Lex.Dq(q.UserObject.Name) + " returned no results.";
                if (notifyUserByEmail)
                {
                    Email.Send(null, SS.I.UserInfo.EmailAddress, emailSubject, msg);
                }
                return(msg);
            }

            try
            {
                resultsFileName = q.ResultsDataTableFileName;                 // see if name supplied in query
                if (Lex.IsNullOrEmpty(resultsFileName))
                {
                    resultsFileName = "Query_" + q.UserObject.Id + "_Results.bin";
                }
                resultsFileName = ServicesIniFile.Read("BackgroundExportDirectory") + @"\" + resultsFileName;
                dtm.WriteBinaryResultsFile(resultsFileName);                 // write the file
                UserObject cidListUo = SaveBackgroundQueryResultsReferenceObject(qm, "BkgrndQry", resultsFileName);

                if (!Lex.IsNullOrEmpty(templateName))
                {
                    html = ReadTemplateFile(templateName);
                }

                if (notifyUserByEmail)
                {
                    AlertUtil.MailResultsAvailableMessage(                     // send the mail
                        q,
                        dtm.KeyCount,
                        SS.I.UserInfo.EmailAddress,
                        emailSubject,
                        viewCmd,
                        cidListUo.Id,
                        null,
                        html);
                }

                else
                {
                    html = SubstituteBackgroundExportParameters(html, "", "", dtm.RowCount, dtm.KeyCount, false, "");
                    return(html);                    // return the html
                }
            }
            catch (Exception ex)
            {
                msg = "Error sending background query results: " + DebugLog.FormatExceptionMessage(ex);
                ServicesLog.Message(msg);
            }

            return(msg);
        }
Exemple #12
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);
            }
        }
Exemple #13
0
        /// <summary>
        /// Read in the set of standard calculated fields & send to dropdown menu
        /// </summary>

        void SetupStandardCalculatedFields()
        {
            try
            {
                if (StandardCalculatedFields == null)
                {
                    StandardCalculatedFields = new List <CalcField>();

                    string fileName   = "StandardCalculatedFields.xml";
                    string serverFile = @"<MetaDataDir>\" + fileName;
                    string clientFile = ClientDirs.TempDir + @"\" + fileName;
                    ServerFile.CopyToClient(serverFile, clientFile);
                    StreamReader  sr = new StreamReader(clientFile);
                    XmlTextReader tr = new XmlTextReader(sr);

                    tr.MoveToContent();
                    if (!Lex.Eq(tr.Name, "StandardCalculatedFields"))
                    {
                        throw new Exception("SetupStandardCalculatedFields - \"StandardCalculatedFields\" element not found");
                    }

                    while (true)
                    {
                        tr.Read();                         // get CalcField element
                        tr.MoveToContent();
                        if (Lex.Eq(tr.Name, "CalcField"))
                        {
                            CalcField cf = CalcField.Deserialize(tr);
                            StandardCalculatedFields.Add(cf);
                        }
                        else if (Lex.Eq(tr.Name, "StandardCalculatedFields"))
                        {
                            break;
                        }

                        else
                        {
                            throw new Exception("SetupStandardCalculatedFields unexpected element: " + tr.Name);
                        }
                    }

                    tr.Close();
                    sr.Close();
                }

                ToolStripItemCollection items = StandardCalcContextMenu.Items;
                items.Clear();

                foreach (CalcField cf2 in StandardCalculatedFields)
                {
                    ToolStripMenuItem mi = new System.Windows.Forms.ToolStripMenuItem();
                    mi.Image = StandardCalcMenuItem.Image;
                    mi.ImageTransparentColor = System.Drawing.Color.Cyan;
                    mi.Text   = cf2.UserObject.Name;
                    mi.Click += new System.EventHandler(this.StandardCalcMenuItem_Click);
                    items.Add(mi);
                }

                return;
            }

            catch (Exception ex)
            {
                ServicesLog.Message("Error reading StandardCalculatedFields.xml: " + ex.Message);
            }

            return;
        }
Exemple #14
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
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Get the name of a file to Open or Save
        /// </summary>
        /// <param name="action">1=open, 2=save, 3=save without prompt</param>
        /// <param name="title"></param>
        /// <param name="defaultFile"></param>
        /// <param name="filter">filter string, e.g. "Lists (*.lst)|*.lst" </param>
        /// <param name="defaultExtension"></param>
        /// <returns></returns>

        private static string GetFilename(
            int action,
            string title,
            string defaultFile,
            string filter,
            string defaultExt)
        {
            OpenFileDialog openDialog = null;
            SaveFileDialog saveDialog = null;
            FileDialog     dialog;
            DialogResult   result;
            string         initialFolder = "", folder = "", fileName = "", ext = "";

            //ClientLog.Message("GetFileName: action = " + action + ", defaultFile = " + defaultFile); // debug

            if (!String.IsNullOrEmpty(defaultFile))              // split out defaultFile name if specified
            {
                if (Lex.StartsWith(defaultFile, "http"))         // if url just use name part
                {
                    defaultFile = Path.GetFileName(defaultFile); // just get name part
                }

                ext = Path.GetExtension(defaultFile);
                if (ext != "")                 // if extension assume file name is present
                {
                    initialFolder = Path.GetDirectoryName(defaultFile);
                    defaultFile   = Path.GetFileName(defaultFile);
                }

                else                 // if no extension assume just a folder
                {
                    initialFolder = defaultFile;
                    defaultFile   = "";
                }

                //ClientLog.Message("GetFileName modified: initialFolder = " + initialFolder + ", defaultFile = " + defaultFile); // debug
            }

            if (initialFolder == "")             // still need initial folder
            {
                initialFolder = DirectoryMx.RemoveTerminalBackSlash(ClientDirs.DefaultMobiusUserDocumentsFolder);
            }

            if (action == 1)             // open
            {
                openDialog = new OpenFileDialog();
                dialog     = (FileDialog)openDialog;
            }
            else             // save
            {
                saveDialog = new SaveFileDialog();
                if (action == 3)
                {
                    saveDialog.OverwritePrompt = false;
                }
                dialog = (FileDialog)saveDialog;
            }

            dialog.Title            = title;
            dialog.FileName         = defaultFile;
            dialog.InitialDirectory = initialFolder; // if initialFolder doesn't exist the control will use the last folder or the current folder
            dialog.Filter           = filter;
            dialog.FilterIndex      = 1;             // filter show first
            dialog.DefaultExt       = defaultExt;

            try { result = dialog.ShowDialog(SessionManager.ActiveForm); }
            catch (Exception ex)             // may be invalid default name
            {
                ServicesLog.Message("ShowDialog exception: " + ex.Message);
                dialog.FileName = "";                                           // clear default name
                result          = dialog.ShowDialog(SessionManager.ActiveForm); // try again
            }

            fileName = dialog.FileName;
            dialog.Dispose();

            if (result != DialogResult.OK)
            {
                return("");
            }

            ext    = Path.GetExtension(fileName);
            folder = Path.GetDirectoryName(fileName);

            return(fileName);
        }
Exemple #16
0
/// <summary>
/// Load plugin definitions
/// </summary>
/// <param name="pluginRootDir"></param>
/// <returns></returns>

        public static int LoadDefinitions(string pluginRootDir)
        {
            if (PluginList != null)
            {
                return(PluginList.Count);
            }
            PluginList = new List <Plugin>();

            string[] dirs = Directory.GetDirectories(pluginRootDir);
            foreach (string dir in dirs)
            {
                if (Lex.EndsWith(dir, @"\TargetResultsViewerNetwork") || // obsolete
                    Lex.EndsWith(dir, @"\RgroupMatrix"))                 // disabled
                {
                    continue;                                            // ignore
                }
                string fileName = dir + @"\plugin.xml";
//				ClientLog.Message("Loading Plugin: " + fileName); // debug
                if (!File.Exists(fileName))
                {
                    continue;
                }
                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(fileName);
                    XmlNodeList nodes = doc.GetElementsByTagName("plugin");                     // get all plugins in file
                    if (nodes == null || nodes.Count == 0)
                    {
                        return(0);
                    }

                    foreach (XmlNode node in nodes)
                    {
                        Plugin p = new Plugin();
                        p.Directory = dir;


                        foreach (XmlAttribute attr in node.Attributes)
                        {
                            if (Lex.Eq(attr.Name, "Id"))
                            {
                                p.Id = attr.Value;
                            }

                            else if (Lex.Eq(attr.Name, "Name"))
                            {
                                p.Name = attr.Value;
                            }

                            else if (Lex.Eq(attr.Name, "Class"))
                            {
                                p.Class = attr.Value;
                            }

                            else if (Lex.Eq(attr.Name, "Provider-Name"))
                            {
                                p.ProviderName = attr.Value;
                            }

                            else if (Lex.Eq(attr.Name, "Version"))
                            {
                                p.Version = attr.Value;

                                if (Lex.Eq(attr.Value, "Hidden"))
                                {
                                    p.Visible = false;                                                               // temp workaround to hide a plugin
                                }
                            }

                            else if (Lex.Eq(attr.Name, "Enabled"))
                            {
                                bool.TryParse(attr.Value, out p.Enabled);
                            }

                            else if (Lex.Eq(attr.Name, "Visible"))
                            {
                                bool.TryParse(attr.Value, out p.Visible);
                            }

                            else
                            {
                                throw new Exception("Unrecognized attribute: " + attr.Name);
                            }
                        }

                        if (p.Id == "")
                        {
                            throw new Exception("Id missing");
                        }

                        if (p.Class == "")
                        {
                            throw new Exception("Class name missing");
                        }

                        XmlNodeList libraryNodes = node.SelectNodes(".//library");                         // get library nodes (case sensitive)
                        if (libraryNodes.Count == 0)
                        {
                            libraryNodes = node.SelectNodes(".//Library");
                        }
                        if (libraryNodes.Count == 0)
                        {
                            libraryNodes = node.SelectNodes(".//LIBRARY");
                        }

                        foreach (XmlNode node2 in libraryNodes)
                        {
                            if (node2.Attributes == null || node2.Attributes.Count < 1 ||
                                !Lex.Eq(node2.Attributes[0].Name, "Name"))
                            {
                                throw new Exception("Runtime Library Name missing");
                            }
                            p.RunTimeLibraries.Add(node2.Attributes[0].Value);
                        }

                        if (p.RunTimeLibraries.Count == 0)
                        {
                            throw new Exception("Runtime library missing");
                        }

                        XmlNodeList eNodes = node.SelectNodes(".//extension");                         // get extension point nodes
                        if (eNodes == null || eNodes.Count == 0)
                        {
                            throw new Exception("Extension points missing");
                        }

                        foreach (XmlNode eNode in eNodes)
                        {
                            ExtensionPoint ep = new ExtensionPoint();
                            ep.Plugin = p;

                            foreach (XmlAttribute attr in eNode.Attributes)
                            {
                                if (Lex.Eq(attr.Name, "Point"))
                                {
                                    if (Lex.Ne(attr.Value, "Mobius.Action") && Lex.Ne(attr.Value, "Mobius.ClientDialog") &&
                                        Lex.Ne(attr.Value, "Mobius.Method"))
                                    {
                                        throw new Exception("Invalid extension point type " + attr.Value);
                                    }
                                    ep.Type = attr.Value;
                                }

                                else if (Lex.Eq(attr.Name, "Id"))
                                {
                                    ep.Id = attr.Value;
                                }

                                else if (Lex.Eq(attr.Name, "Class"))
                                {
                                    ep.Class = attr.Value;
                                }

                                else if (Lex.Eq(attr.Name, "MenuBarPath"))
                                {
                                    if (Lex.Ne(attr.Value, "Tools"))
                                    {
                                        throw new Exception("Unsupported MenubarPath " + attr.Value);
                                    }
                                    ep.MenuBarPath = attr.Value;
                                }

                                else if (Lex.Eq(attr.Name, "CommandLineCommand"))
                                {
                                    ep.CommandName = attr.Value;
                                }

                                else if (Lex.Eq(attr.Name, "MethodName"))
                                {
                                    ep.MethodName = attr.Value;
                                }

                                else if (Lex.Eq(attr.Name, "Label"))
                                {
                                    ep.Label = attr.Value;
                                }

                                else
                                {
                                    throw new Exception("Unrecognized extension point attribute: " + attr.Name);
                                }
                            }

                            if (ep.Id == "")
                            {
                                throw new Exception("Extension point Id missing");
                            }
                            if (ep.Type == "")
                            {
                                throw new Exception("Extension point type missing");
                            }
                            if (ep.Class == "")
                            {
                                if (p.Class != "")
                                {
                                    ep.Class = p.Class;                                                // use plugin class if defined
                                }
                                else
                                {
                                    throw new Exception("Extension point class name missing");
                                }
                            }

                            fileName = dir + @"\" + ep.Id + ".bmp";
                            if (File.Exists(fileName))
                            {
                                try { ep.Image = Bitmap.FromFile(fileName); }
                                catch (Exception ex) { ex = ex; }
                            }

                            p.ExtensionPoints.Add(ep);                             // add extension point to plugin
                        }

                        PluginList.Add(p);                         // add plugin to list
                    }
                }
                catch (Exception ex)
                {
                    ServicesLog.Message(DebugLog.FormatExceptionMessage(ex));
                    string msg = "Error in file \"" + fileName + "\"\r\n" + ex.Message;
                    throw new Exception(msg, ex);
                }
            }

            PluginCaller.CallRef =             // alloc PluginDao to call up to us
                                   new PluginCaller.CallMethodDelegate(CallStringExtensionPointMethod);

            return(PluginList.Count);
        }
Exemple #17
0
/// Edit criteria for a query column
/// </summary>
/// <param name="qc"></param>
/// <returns>True if criteria has been successfully edited</returns>

        public static bool EditCriteria(
            QueryColumn qc)
        {
            MetaColumn mc    = qc.MetaColumn;
            Query      Query = qc.QueryTable.Query;
            bool       sameQ = Query == QueriesControl.Instance.CurrentQuery;       // debug

            if (Lex.Contains(qc.MetaColumn.ColumnMap, ToolUtil.ToolParametersColumnMapValue))
            {
                DialogResult dr = ToolHelper.InvokeToolCriteriaEditor(qc);
                return(dr == DialogResult.OK);
            }

            try
            {
                if (!mc.IsSearchable)
                {
                    MessageBoxMx.ShowError("The " + qc.ActiveLabel + " data item is not currently searchable.");
                    return(false);
                }

                if (mc.IsKey)                              // edit key criteria
                {
                    qc.CopyCriteriaFromQueryKeyCriteria(); // be sure qc is in sync with Query.KeyCriteria
                    if (!CriteriaCompoundId.Edit(qc))
                    {
                        return(false);
                    }

                    qc.CopyCriteriaToQueryKeyCritera();                     // update Query.KeyCriteria
                    return(true);
                }

                switch (mc.DataType)
                {
                // Compound Number criteria

                case MetaColumnType.CompoundId:

                    if (!CriteriaCompoundId.Edit(qc))
                    {
                        return(false);
                    }
                    else
                    {
                        break;
                    }

                // Structure criteria

                case MetaColumnType.Structure:
                    if (!CriteriaStructure.Edit(qc))
                    {
                        return(false);
                    }
                    break;

                // Mol. formula criteria

                case MetaColumnType.MolFormula:
                    if (!CriteriaMolFormula.Edit(qc))
                    {
                        return(false);
                    }
                    break;


                // General criteria

                case MetaColumnType.Integer:
                case MetaColumnType.Number:
                case MetaColumnType.QualifiedNo:
                case MetaColumnType.String:
                case MetaColumnType.Date:
                case MetaColumnType.DictionaryId:

                    if (!CriteriaDialog.Edit(qc))
                    {
                        return(false);
                    }
                    else
                    {
                        break;
                    }

                default:
                    MessageBoxMx.ShowError("The " + qc.ActiveLabel + " data item is not currently searchable.");
                    return(false);
                }

                return(true);
            }

            catch (Exception ex)
            {
                string msg = "Unexpected error editing criteria: \r\n\r\n" +
                             DebugLog.FormatExceptionMessage(ex);
                ServicesLog.Message(msg);
                MessageBoxMx.ShowError(msg);
                return(false);
            }
        }
Exemple #18
0
        /// <summary>
        /// Convert an .xls file to a csv file
        /// </summary>
        /// <param name="xlsFile"></param>
        /// <param name="csvFile"></param>

        public static void XlsToCsv(
            string xlsFile,
            string csvFile)
        {
            if (LogCalls)
            {
                DebugLog.Message("XlsToCsv " + xlsFile + ", " + csvFile);
            }

            string xlsFile2 = "", tok;

            for (int i = 1; i <= 3; i++)             // try up to three times since the conversion sometimes fails for unknown reasons
            {
                try
                {
                    if (xlsFile.StartsWith(@"\\"))
                    {                     // copy from share to local file
                        string ext = Path.GetExtension(xlsFile);
                        xlsFile2 = TempFile.GetTempFileName(ClientDirs.TempDir, ext, false);
                        File.Copy(xlsFile, xlsFile2, true);
                    }

                    else
                    {
                        xlsFile2 = xlsFile;
                    }

                    CreateObject();
                    //ScreenUpdating(false); // no screen updating during sheet build
                    Open(xlsFile2);                     // "The remote procedure call failed" or "Call was rejected by callee (on get_ActiveSheet)" may occur here
                    SaveAsCsv(csvFile);
                    try { Close(); }
                    catch (Exception ex) { ex = ex; }                     // "Call was rejected by callee" may occur here, ignore if so
                    try { Quit(); }
                    catch (Exception ex) { ex = ex; }
                    try { DeleteObject(); }
                    catch (Exception ex) { ex = ex; }

                    if (xlsFile2 != xlsFile)
                    {
                        try { File.Delete(xlsFile2); }
                        catch (Exception ex) { ex = ex; }
                    }

                    //SystemUtil.Beep(); // debug
                    return;                     // success
                }

                catch (Exception ex)
                {
                    if (i < 3)                     // allow two retries
                    {
                        try
                        {
                            Quit();
                            DeleteObject();
                            Thread.Sleep(500);                             // sleep a bit before retry
                        }
                        catch (Exception ex2) { ex2 = ex2; }
                    }

                    else                     // log and throw exception if final try fails
                    {
                        ServicesLog.Message("XlsToCsv failed for file: " + xlsFile + ", " + xlsFile2 + "\r\n\r\n" +
                                            DebugLog.FormatExceptionMessage(ex));
                        throw new Exception(ex.Message, ex);
                    }
                }
            }

            return;
        }