Beispiel #1
0
        /// <summary>
        /// Get a metatable from MySql catalog
        /// </summary>
        /// <param name="tableName">schema.table</param>
        /// <returns></returns>

        public static MetaTable GetMetaTableFromDatabaseDictionary(
            DbConnectionMx conn,
            string schema,
            string tableName)
        {
            int t0 = TimeOfDay.Milliseconds();

            MetaTable mt = new MetaTable();

            mt.MetaBrokerType = MetaBrokerType.Generic;
            mt.Name           = tableName;
            mt.Label          = MetaTable.IdToLabel(tableName);
            mt.TableMap       = schema + "." + tableName;

            List <DbColumnMetadata> cmdList = GetTableMetadataFromMySqlDictionary(conn, schema, tableName);

            for (int ci = 0; ci < cmdList.Count; ci++)
            {
                DbColumnMetadata cmd = cmdList[ci];

                MetaColumn mc = new MetaColumn();
                mc.Name      = cmd.Name;
                mc.ColumnMap = mc.Name;
                mc.Label     = MetaTable.IdToLabel(cmd.Name);

                if (Lex.Contains(cmd.Type, "CHAR") ||
                    Lex.Contains(cmd.Type, "TEXT"))
                {
                    mc.DataType = MetaColumnType.String;
                }

                else if (Lex.Contains(cmd.Type, "INT") ||
                         Lex.Contains(cmd.Type, "ENUM"))
                {
                    mc.DataType = MetaColumnType.Integer;
                }

                else if (cmd.Type == "FLOAT" ||
                         cmd.Type == "REAL" ||
                         cmd.Type == "DOUBLE" ||
                         cmd.Type == "DECIMAL" ||
                         cmd.Type == "NUMERIC")
                {
                    mc.DataType = MetaColumnType.Number;
                    mc.Format   = ColumnFormatEnum.Decimal;
                    mc.Decimals = cmd.Scale;
                }

                else if (cmd.Type == "DATE" ||
                         cmd.Type == "DATETIME" ||
                         cmd.Type == "TIMESTAMP")
                {
                    mc.DataType = MetaColumnType.Date;
                }

                else
                {
                    continue;                  // unrecognized
                }
                mc.InitialSelection = ColumnSelectionEnum.Selected;
                mc.Width            = 12;
                mc.MetaTable        = mt;
                mc.Description      = cmd.Comment;

                mt.AddMetaColumn(mc);
            }

            t0 = TimeOfDay.Milliseconds() - t0;
            return(mt);
        }
Beispiel #2
0
        public static DialogResult Show(
            QueryColumn qc)
        {
            string tok;

            if (Instance == null)
            {
                Instance = new DateFormatDialog();
            }
            DateFormatDialog dfd = Instance;

            MetaColumn mc = qc.MetaColumn;

            if (mc.DataType != MetaColumnType.Date)
            {
                XtraMessageBox.Show(mc.Label + " is not a date field");
                return(DialogResult.Cancel);
            }

            // Setup

            new JupyterGuiConverter().ConvertFormOrUserControl(Instance);

            string fmt = qc.DisplayFormatString;

            if (Lex.IsNullOrEmpty(fmt))
            {
                fmt = "d-MMM-yyyy";                                     // default format
            }
            if (Lex.Contains(fmt, "d-MMM-yyyy"))
            {
                dfd.d_MMM_yyyy.Checked = true;
            }
            else if (Lex.Contains(fmt, "d-MMM-yy"))
            {
                dfd.d_MMM_yy.Checked = true;
            }
            else if (Lex.Contains(fmt, "M/d/yyyy"))
            {
                dfd.M_d_yyyy.Checked = true;
            }
            else if (Lex.Contains(fmt, "M/d/yy"))
            {
                dfd.M_d_yy.Checked = true;
            }
            else if (Lex.Contains(fmt, "none"))
            {
                dfd.DateNone.Checked = true;
            }
            else
            {
                dfd.d_MMM_yyyy.Checked = true;              // in case of no match
            }
            if (Lex.Contains(fmt, "h:mm:ss tt"))
            {
                dfd.h_mm_ss_tt.Checked = true;                                              // check in reverse order to get correct hit
            }
            else if (Lex.Contains(fmt, "h:mm tt"))
            {
                dfd.h_mm_tt.Checked = true;
            }
            else if (Lex.Contains(fmt, "H:mm:ss"))
            {
                dfd.H_mm_ss.Checked = true;
            }
            else if (Lex.Contains(fmt, "H:mm"))
            {
                dfd.H_mm.Checked = true;
            }
            else
            {
                dfd.TimeNone.Checked = true;
            }

// Show form & get new values

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

            if (dr == DialogResult.OK)
            {
                if (dfd.d_MMM_yyyy.Checked)
                {
                    fmt = "d-MMM-yyyy";
                }
                else if (dfd.d_MMM_yy.Checked)
                {
                    fmt = "d-MMM-yy";
                }
                else if (dfd.M_d_yyyy.Checked)
                {
                    fmt = "M/d/yyyy";
                }
                else if (dfd.M_d_yy.Checked)
                {
                    fmt = "M/d/yy";
                }
                else if (dfd.DateNone.Checked)
                {
                    fmt = "none";
                }

                if (dfd.H_mm.Checked)
                {
                    fmt += " H:mm";
                }
                else if (dfd.H_mm_ss.Checked)
                {
                    fmt += " H:mm:ss";
                }
                else if (dfd.h_mm_tt.Checked)
                {
                    fmt += " h:mm tt";
                }
                else if (dfd.h_mm_ss_tt.Checked)
                {
                    fmt += " h:mm:ss tt";
                }
                else if (dfd.TimeNone.Checked)
                {
                }
                ;                                                   // nothing if no time

                qc.DisplayFormatString = fmt;
            }

            return(dr);
        }
Beispiel #3
0
/// <summary>
/// Get the image index corresponding to node type
/// </summary>
/// <returns></returns>

        public Bitmaps16x16Enum GetImageIndexEnum()
        {
            MetaTreeNode mtn = this;

            //if (mtn.Label == "CorpId Structures") mtn = mtn; // debug

            if (IsFolderType)
            {
                switch (Type)
                {
                case MetaTreeNodeType.Root:
                    return(Bitmaps16x16Enum.World);

                case MetaTreeNodeType.Database:
                    return(Bitmaps16x16Enum.Books);

                case MetaTreeNodeType.Target:
                    return(Bitmaps16x16Enum.Target);

                case MetaTreeNodeType.UserFolder:
                    if (Lex.Eq(mtn.Label, "Queries"))
                    {
                        return(Bitmaps16x16Enum.QueryFolder);
                    }
                    else if (Lex.Eq(mtn.Label, "Lists"))
                    {
                        return(Bitmaps16x16Enum.ListFolder);
                    }
                    else if (Lex.Eq(mtn.Label, "Annotations"))
                    {
                        return(Bitmaps16x16Enum.AnnotationFolder);
                    }
                    else if (Lex.Eq(mtn.Label, "Calculated Fields"))
                    {
                        return(Bitmaps16x16Enum.CalcFieldFolder);
                    }
                    else if (Lex.StartsWith(mtn.Label, "Shared ") || Lex.StartsWith(mtn.Label, "Public "))
                    {
                        return(Bitmaps16x16Enum.People);
                    }
                    else
                    {
                        return(Bitmaps16x16Enum.Folder);
                    }

                case MetaTreeNodeType.Project:
                    return(Bitmaps16x16Enum.Project);

                default:
                    return(Bitmaps16x16Enum.Folder);
                }
            }

            // Leaf-type nodes

            switch (Type)
            {
            case MetaTreeNodeType.Url:
                if (Lex.Contains(Target, "Spotfire"))                         // link to Spotfire webplayer
                {
                    return(Bitmaps16x16Enum.Spotfire);
                }

                else if (Lex.Contains(Target, "Show") && Lex.Contains(Target, "Description"))                         // use help image for showing descriptions
                {
                    return(Bitmaps16x16Enum.Info);
                }

                else
                {
                    return(Bitmaps16x16Enum.URL);                         // generic URL
                }

            case MetaTreeNodeType.Action:
                return(Bitmaps16x16Enum.Action);

            case MetaTreeNodeType.CnList:
                if (Shared)
                {
                    return(Bitmaps16x16Enum.CidListPublic);
                }
                else
                {
                    return(Bitmaps16x16Enum.CidList);
                }

            case MetaTreeNodeType.Query:
                if (Lex.StartsWith(Name, "MULTITABLE_"))                         // use tables icon for multitable
                {
                    return(Bitmaps16x16Enum.Tables);
                }
                else
                {
                    if (Shared)
                    {
                        return(Bitmaps16x16Enum.QueryPublic);
                    }
                    else
                    {
                        return(Bitmaps16x16Enum.SarTable);
                    }
                }

            case MetaTreeNodeType.CalcField:
                if (Shared)
                {
                    return(Bitmaps16x16Enum.CalcFieldPublic);
                }
                else
                {
                    return(Bitmaps16x16Enum.CalcField);
                }

            case MetaTreeNodeType.Annotation:
                if (Lex.Contains(Label, "STRUCTURES"))                          // special case for structure annotation in user databases
                {
                    return(Bitmaps16x16Enum.Structure);
                }
                else
                {
                    if (Shared)
                    {
                        return(Bitmaps16x16Enum.AnnotationPublic);
                    }
                    else
                    {
                        return(Bitmaps16x16Enum.AnnotationTable);
                    }
                }

            case MetaTreeNodeType.CondFormat:
                return(Bitmaps16x16Enum.CondFormat);

            case MetaTreeNodeType.MetaTable:                     // must be metatable
                if (Lex.Contains(Name, "_STRUCTURE2") &&         // special case for struct "plus"
                    !Lex.StartsWith(Name, "ORACLE"))             // but not in direct Oracle references
                {
                    return(Bitmaps16x16Enum.StructurePlus);
                }

                else if (Lex.Contains(Name, "_STRUCTURE") &&                     // special case for struct
                         !Lex.StartsWith(Name, "ORACLE"))                        // but not in direct Oracle references
                {
                    return(Bitmaps16x16Enum.Structure);
                }

                else if (Lex.Eq(Name, MetaTable.SmallWorldMetaTableName))
                {
                    return(Bitmaps16x16Enum.Structure);
                }

                else
                {
                    return(Bitmaps16x16Enum.DataTable);
                }

            case MetaTreeNodeType.Library:
                return(Bitmaps16x16Enum.Library);

            case MetaTreeNodeType.ResultsView:
                return(Bitmaps16x16Enum.Spotfire);

            default:
                return(Bitmaps16x16Enum.World);
            }
        }
Beispiel #4
0
        /// <summary>
        /// Scan all loaded assemblies and get list of those that contain Mobius types
        /// </summary>

        static void GetMobiusAssemblies()
        {
            HashSet <Assembly> aDict                   = new HashSet <Assembly>();
            HashSet <string>   aNamesTriedDict         = new HashSet <string>();
            Assembly           serviceFacadeAssembly   = null;                   // assembly that contains the ServiceFacade classes
            HashSet <string>   serviceFacadeClassNames = new HashSet <string>(); // names of classes in ServiceFacade

            Type[] types;

            Assembly[] initialAssemblies = AppDomain.CurrentDomain.GetAssemblies();

            foreach (Assembly a in initialAssemblies)             // Get all Mobius assemblies from initial set
            {
                aNamesTriedDict.Add(a.FullName);
                if (!IsMobiusAssembly(a))
                {
                    continue;
                }
                aDict.Add(a);
            }

            MobiusAssemblies = new List <Assembly>(aDict);       // initial set of Mobius assemblies
            foreach (Assembly a in MobiusAssemblies)             // Check referenced assemblies not initially loaded
            {
                CheckReferencedAssemblies(a, aDict, aNamesTriedDict);
            }

            MobiusAssemblies = new List <Assembly>(aDict);       // get full set of Mobius assemblies

            foreach (Assembly a in MobiusAssemblies)             // look for ServiceFacade assembly
            {
                if (Lex.Contains(a.FullName, "ServiceFacade"))
                {
                    serviceFacadeAssembly = a;
                    continue;
                }
            }

            ServiceAssemblyNames = new HashSet <string>();

            if (serviceFacadeAssembly == null)
            {
                return;                                            // just return if no serviceFacadeAssembly
            }
            MobiusAssemblies.Remove(serviceFacadeAssembly);

// Get list of assemblies that are primarily service assemblies

            serviceFacadeClassNames = new HashSet <string>();            // build hash set of service facade class names
            types = serviceFacadeAssembly.GetTypes();
            for (int ti = 0; ti < types.Length; ti++)
            {
                Type t = types[ti];
                serviceFacadeClassNames.Add(t.Name);
            }

            foreach (Assembly a in MobiusAssemblies)             // see if any class in assemble matches a class name in the service facade
            {
                types = a.GetTypes();
                for (int ti = 0; ti < types.Length; ti++)
                {
                    Type t = types[ti];
                    if (serviceFacadeClassNames.Contains(t.Name))
                    {
                        ServiceAssemblyNames.Add(a.FullName);
                        break;
                    }
                }
            }

            // Put ServiceFacade assembly last so non-facade classes are found first first

            MobiusAssemblies.Add(serviceFacadeAssembly);

            return;
        }
Beispiel #5
0
        /// <summary>
        /// Deserialize an alert header in a user object
        /// </summary>
        /// <param name="uo"></param>
        /// <returns></returns>

        private static Alert DeserializeHeader(
            UserObject uo)
        {
            Alert alert = new Alert();

            alert.Id = uo.Id;

            string serializedForm = uo.Description;

            if (String.IsNullOrEmpty(serializedForm))
            {
                return(alert);
            }

            if (!Lex.Contains(serializedForm, "<Alert"))
            {
                return(DeserializeHeaderOld(uo));
            }

            XmlMemoryStreamTextReader mstr = new XmlMemoryStreamTextReader(serializedForm);
            XmlTextReader             tr   = mstr.Reader;

            tr.Read();             // get CondFormat element
            tr.MoveToContent();
            if (!Lex.Eq(tr.Name, "Alert"))
            {
                throw new Exception("\"Alert\" element not found");
            }

            XmlUtil.GetStringAttribute(tr, "Owner", ref alert.Owner);
            XmlUtil.GetIntAttribute(tr, "QueryObjId", ref alert.QueryObjId);
            XmlUtil.GetIntAttribute(tr, "Interval", ref alert.Interval);
            XmlUtil.GetStringAttribute(tr, "MailTo", ref alert.MailTo);
            XmlUtil.GetDateAttribute(tr, "LastCheck", ref alert.LastCheck);
            XmlUtil.GetIntAttribute(tr, "LastCheckElapsedTime", ref alert.LastCheckExecutionTime);
            XmlUtil.GetIntAttribute(tr, "NewCompounds", ref alert.NewCompounds);
            XmlUtil.GetIntAttribute(tr, "ChangedCompounds", ref alert.ChangedCompounds);
            XmlUtil.GetIntAttribute(tr, "NewRows", ref alert.NewRows);
            XmlUtil.GetIntAttribute(tr, "TotalRows", ref alert.TotalRows);
            XmlUtil.GetIntAttribute(tr, "TotalCompounds", ref alert.TotalCompounds);
            XmlUtil.GetBoolAttribute(tr, "CheckTablesWithCriteriaOnly", ref alert.CheckTablesWithCriteriaOnly);
            XmlUtil.GetDateAttribute(tr, "LastNewData", ref alert.LastNewData);
            XmlUtil.GetBoolAttribute(tr, "HighlightChangedCompounds", ref alert.HighlightChangedCompounds);
            XmlUtil.GetBoolAttribute(tr, "RunImmediately", ref alert.RunImmediately);

            XmlUtil.GetStringAttribute(tr, "Days", ref alert.Days);
            XmlUtil.GetIntAttribute(tr, "DayInterval", ref alert.DayInterval);
            XmlUtil.GetDateAttribute(tr, "StartTime", ref alert.StartTime);
            alert.StartTime = GetLocalFromEasternStandardTime(alert.StartTime);
            XmlUtil.GetStringAttribute(tr, "Pattern", ref alert.Pattern);
            if (string.IsNullOrEmpty(alert.Pattern))
            {
                alert.Pattern = PatternEnum.Daily.ToString();
            }

            if (!tr.IsEmptyElement)
            {
                tr.Read();                 // move to Export options or end of Alert element
                tr.MoveToContent();

                if (tr.NodeType == XmlNodeType.Element && Lex.Eq(tr.Name, "ResultsFormat"))
                {
                    alert.ExportParms = ResultsFormat.Deserialize(tr);
                    tr.Read();                     // get Alert end element
                    tr.MoveToContent();
                }

                if (!Lex.Eq(tr.Name, "Alert") || tr.NodeType != XmlNodeType.EndElement)
                {
                    throw new Exception("Alert.Deserialize - Expected Alert end element");
                }
            }

            mstr.Close();

            double daysSinceLastCheckwithDecimal = (alert.LastCheck == DateTime.MinValue) ? alert.Interval : (DateTime.Now - alert.LastCheck).TotalDays;
            double daysSinceNewDatawithDecimal   = (alert.LastNewData == DateTime.MinValue) ? 0 : (DateTime.Now - alert.LastNewData).TotalDays;

            //Round these calculations so .5 days will become 1 day, effectively 12 hours or more will count as a whole day.
            alert.DaysSinceLastCheck = (int)Math.Round(daysSinceLastCheckwithDecimal, MidpointRounding.AwayFromZero);
            alert.DaysSinceNewData   = (int)Math.Round(daysSinceNewDatawithDecimal, MidpointRounding.AwayFromZero);

            //DebugLog.Message("Alert: " + alert.Id + " daysSinceLastCheckwithDecimal: " + daysSinceLastCheckwithDecimal);
            //DebugLog.Message("Alert: " + alert.Id + " new DaysSinceLastCheck: " + alert.DaysSinceLastCheck);
            //DebugLog.Message("Alert: " + alert.Id + " daysSinceNewDatawithDecimal: " + daysSinceNewDatawithDecimal);
            //DebugLog.Message("Alert: " + alert.Id + " DaysSinceNewData: " + alert.DaysSinceNewData);

            return(alert);
        }
Beispiel #6
0
 static bool ContainsPriv(string content, string s)
 {
     s = "<" + s + ">";
     return(Lex.Contains(content, s));
 }
Beispiel #7
0
        /// <summary>
        /// Do setup in preparation for decompose
        /// </summary>
        /// <param name="qt"></param>
        /// <param name="q"></param>

        public void PrepareForDecompose(
            QueryTable qt,
            Query q)
        {
            throw new NotImplementedException();
#if false
            Stopwatch sw = Stopwatch.StartNew();

            MetaTable mt = qt.MetaTable;

            QueryColumn qc = qt.GetQueryColumnByName("core");
            if (qc == null)
            {
                throw new UserQueryException("Core column not defined in rgroup_decomposition table");
            }
            string molfile = qc.MolString;
            if (molfile == null || molfile == "")
            {             // core not defined in Rgroup decomposition table, try to get from structure search in rest of query
                foreach (QueryTable qt3 in q.Tables)
                {
                    if (!qt3.MetaTable.IsRootTable)
                    {
                        continue;
                    }
                    MetaColumn mc3 = qt3.MetaTable.FirstStructureMetaColumn;
                    if (mc3 != null)
                    {
                        QueryColumn qc3 = qt3.GetQueryColumnByName(mc3.Name);
                        molfile = qc3.MolString;
                        break;
                    }
                }
            }

            if (molfile == null || molfile == "")
            {
                throw new UserQueryException("R-group decomposition core structure is not defined");
            }

            bool allowHydrogenSubstituents = true;
            qc = qt.GetQueryColumnByName("AllowHydrogenSubstituents");
            if (Lex.Contains(qc?.Criteria, "'N'"))
            {
                allowHydrogenSubstituents = false;                                                // set to false if "no" criteria specified
            }
            TerminateOptionString = "First mapping";
            bool allowMultipleCoreMappings = false;

            qc = qt.GetQueryColumnByName("Terminate_Option");
            if (qc != null && qc.Criteria != "")
            {
                ParsedSingleCriteria psc = MqlUtil.ParseSingleCriteria(qc.Criteria);
                TerminateOptionString     = psc.Value;
                allowMultipleCoreMappings = Lex.Contains(TerminateOptionString, "All");
            }

            MoleculeMx cs = new MoleculeMx(MoleculeFormat.Molfile, molfile);
            cs.GetCoreRGroupInfo(out RgCounts, out RgTotalCount);             // need to redefine these

            RGroupDecomp.Initialize();

            RGroupDecomp.SetAlignStructuresToCore(true);
            RGroupDecomp.SetAllowMultipleCoreMappings(allowMultipleCoreMappings);
            RGroupDecomp.SetIncludeHydrogenFragments(allowHydrogenSubstituents);

            if (DebugMx.True)             // debug
            {
                String  coreSmiles = "[R1]c1cn2c3c(c1= O)cc(c(c3SC(C2)[R4])[R3])[R2]";
                string  coreChime  = "CYAAFQwAUewQeV58YHemfM^EQqPRfIYlJGEkx6M7e4db95jjK5HrNFVP2e1qHphWPL98KvcvrsF7bP9bRcW4QH$si9PXkkuwre6Q5UkHZjciQqeAKVLSHNAeQTAMlkiXEBD$BePpbNQCPD3BkklFEaQqwokeI$FwUoS5cAixQXkMbLTWDaAK7t7cOkSmt3RhwQedbrba6OHKBq3OF4Dhlz$0BfLeKCUUo8ixle176M2aIzXUccTOU8Xy8ARwE3bTyMfjuI3UunZceJf4iZELvsj3PX2MHZG73baUvQGS4DaxUaBGps81PPiDljfvxwFv8OfdOyIRlOBeuEAvk2rT9SRT6oMZIV6UtLFvmCHdwKnu9WtrfV1rEctydNUVxW4qKVlV0rZtpK1oZXuKcv6WVdl6r2hrjVLxBhblTVKO7w1qGRoziquOnPQkKd9H4EQfV0rP6mzI8Au8ulti2fu3YKB94lPXftPGbwr5yA";
                IMolLib coreMol    = MolLibFactory.NewMolLib(MoleculeFormat.Molfile, molfile);
                coreChime = MoleculeMx.MolfileStringToChimeString(molfile);
                molfile   = coreMol.MolfileString;
            }

            CoreMolecule = CdkMol.Util.MolfileStringToMolecule(molfile);
            RGroupDecomp.SetCoreStructure(CoreMolecule, false);

            CoreChemicalStructure = new MoleculeMx(MoleculeFormat.Molfile, molfile);
            StrMatcher            = null;

            int msTime = (int)sw.ElapsedMilliseconds;
            if (RGroupDecomp.Debug)
            {
                DebugLog.Message("Time(ms): " + msTime);
            }

            return;
#endif
        }
Beispiel #8
0
        /// <summary>
        /// Open the specified target
        /// </summary>
        /// <param name="mtn"></param>

        public static void OpenMetaTreeNode(
            MetaTreeNode mtn)
        {
            UserObject uo;
            string     tok;
            int        i1;

            if (mtn == null)
            {
                return;
            }
            MetaTreeNodeType nodeType = mtn.Type;
            string           target   = mtn.Target;

            //if (!Permissions.UserHasReadAccess(SS.I.UserName, target))
            //{
            //  MessageBoxMx.ShowError("You are not authorized to open: " + mtn.Label);
            //  return;
            //}

            if (nodeType == MetaTreeNodeType.MetaTable ||             // data table types
                nodeType == MetaTreeNodeType.CalcField ||
                nodeType == MetaTreeNodeType.CondFormat ||
                nodeType == MetaTreeNodeType.Annotation ||
                nodeType == MetaTreeNodeType.ResultsView)
            {
                QbUtil.CallCurrentProcessTreeItemOperationMethod("Open", target);
            }

            else if (MetaTreeNode.IsFolderNodeType(nodeType))
            {
                if (Lex.StartsWith(target, "USERDATABASE_"))                 // edit a user compound database
                {
                    uo = ParseAndReadUserObject(target);
                    if (uo == null)
                    {
                        return;
                    }
                    UserData.OpenExistingUserDatabase(uo);
                }
            }

            else if (nodeType == MetaTreeNodeType.Url)
            {             // open url or execute click function
                if ((i1 = Lex.IndexOf(target, "ClickFunction")) >= 0)
                {
                    string cmd = target.Substring(i1 + "ClickFunction".Length + 1);                     // get function name
                    ClickFunctions.Process(cmd, null);
                }

                else if (Lex.Contains(target, "SpotfireWeb"))                 // link to Spotfire webplayer
                {
                    SpotfireLinkUI.OpenLink(target);
                }

                else
                {
                    SystemUtil.StartProcess(target);                  // open in default user browser
                }
            }

            else if (nodeType == MetaTreeNodeType.Action)
            {             // execute action
                return;   //  CommandLineControl.Execute(mtn.Target);
            }

            else if (nodeType == MetaTreeNodeType.CnList)             // open list
            {
                uo = ParseAndReadUserObject(target);
                if (uo == null)
                {
                    return;
                }
                tok = uo.InternalName;
                CidListEditor.Edit(tok);
            }

            else if (nodeType == MetaTreeNodeType.Query)             // open query
            {
                uo = ParseAndReadUserObject(target);
                if (uo == null)
                {
                    return;
                }

                if (uo.Type == UserObjectType.Query)                 // normal query
                {
                    tok = uo.InternalName;

                    string nextCommand = QbUtil.OpenQuery(tok);
                    while (!(String.IsNullOrEmpty(nextCommand)))
                    {
                        nextCommand = CommandExec.ExecuteCommand(nextCommand);
                    }
                }

                else if (uo.Type == UserObjectType.MultiTable)                 // multitable query
                {
                    QbUtil.AddAndRenderTables(target);
                }
            }

            else if (nodeType == MetaTreeNodeType.Library)
            {
                CommandExec.ExecuteCommandAsynch("ContentsViewLibAsList " + mtn.Name);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Handle a click on a link to a 3D structure & open in Vida
        /// If clicked from an XtraGrid give the user a range of options for the data
        /// to be exported. If clicked from a HTML page give limited options.
        /// </summary>
        /// <param name="mtName"></param>
        /// <param name="mcName"></param>
        /// <param name="url"></param>

        public void ClickFunction(
            string mtName,
            string mcName,
            string url)
        {
            ResultsFormatter fmtr = null;
            ResultsField     rfld = null;
            //DataRowMx dr;
            StringMx     sx;
            StreamWriter sw;
            int          markedCount   = 0;
            string       densityMapUrl = null;
            string       target        = null;

            _currentMetaTable     = mtName;
            _currentPdbColumnName = mcName;

            IncludeElectronDensityPyMol.Checked = false;

            MetaTable mt = MetaTableCollection.Get(mtName);

            if (mt == null)
            {
                return;
            }

            MetaColumn mc = mt.GetMetaColumnByName(mcName);

            if (mc == null)
            {
                return;
            }

            _xRay2Request = Lex.Contains(mtName, "XRay2");    // newer XRay2 database table?
            _urlFileName  = Path.GetFileName(url);            // extract file name from url

            QueryManager qm = ClickFunctions.CurrentClickQueryManager;

            if (qm != null)
            {
                Query         q  = qm.Query;
                ResultsFormat rf = qm.ResultsFormat;
                fmtr = qm.ResultsFormatter;

                rfld = rf.GetResultsField(mc);
                if (rfld == null)
                {
                    return;
                }

                QueryTable qt = q.GetQueryTableByNameWithException(mtName);
                _qcProtein = qt.GetQueryColumnByNameWithException(mcName);

                if (_xRay2Request)                 // newer XRay2 database
                {
                    string mapUrl = "";
                    if (mcName == "ALIGNED_SPLIT_COMPLEX_URL")
                    {
                        mapUrl = "ALIGNED_SPLIT_MAP_URL";
                    }
                    else if (mcName == "ALIGNED_FULL_COMPLEX_URL")
                    {
                        mapUrl = "ALIGNED_FULL_MAP_URL";
                    }
                    else if (mcName == "ORIGINAL_PDB_URL")
                    {
                        mapUrl = "ORIGINAL_MAP_URL";
                    }                                                                 //{ mapUrl = "ORIGINAL_MAP_URL"; }

                    _qcDensity = qt.GetQueryColumnByName(mapUrl);                     //("ALIGNED_SPLIT_MAP_URL");
                    if (_qcDensity != null && !_qcDensity.Selected)
                    {
                        _qcDensity = null;
                    }

                    _qcTarget = qt.GetQueryColumnByName("primary_gene_name_alias");
                    if (_qcTarget != null && !_qcTarget.Selected)
                    {
                        _qcTarget = null;
                    }
                }

                if (_qcDensity != null)
                {
                    // if there is a density map url located in the density column, enable the PyMol CheckEdit
                    DataRowMx dr = qm.DataTable.Rows[qm.MoleculeGrid.LastMouseDownCellInfo.DataRowIndex];
                    densityMapUrl = Lex.ToString(dr[_qcDensity.VoPosition]);
                }
                else
                {
                    // user did not select the map column, try to retrieve the XRay1 or Xray2 density map url fromt he metatable
                    densityMapUrl = _xRay2Request ? GetXray2DensityMapUrl(url, qt.MetaTable.Name, mcName) : GetXray1DensityMapUrl(url, qt.MetaTable.Name);
                }

                // default checkbox to false so user does not load electron density maps everytime, since these take
                // extra time to load.
                IncludeElectronDensityPyMol.Checked = false;

                IncludeElectronDensityPyMol.Enabled = !string.IsNullOrEmpty(densityMapUrl);

                if (_qcProtein == null && _qcDensity == null)
                {
                    throw new Exception("Neither the PDB nor the MAP column is selected in the query");
                }

                markedCount = fmtr.MarkedRowCount;
                int unmarkedCount = fmtr.UnmarkedRowCount;

                if (markedCount == 0 || unmarkedCount == 0)                 // if no specific selection assume user wants single structure
                {
                    ExportSingle.Checked = true;
                    FileName.Text        = _urlFileName;
                }
                else
                {
                    ExportMarked.Checked = true;                  // assume wants marked structures
                }
                ExportMarked.Enabled = true;
            }

            else              // simple setup for click from HTML display
            {
                ExportSingle.Checked = true;
                ExportMarked.Enabled = false;
                FileName.Text        = _urlFileName;

                densityMapUrl = GetXray2DensityMapUrl(url, _currentMetaTable, mcName);
                target        = GetTarget(url, _currentMetaTable, mcName);


                ////IncludeProtein.Enabled = IncludeElectronDensityEnabled = false;

                ////if (Lex.Eq(mcName, "bsl_xray_cmplx_url"))
                ////  IncludeProtein.Checked = true;

                ////else if (Lex.Eq(mcName, "bsl_xray_edensity_url"))
                ////  IncludeElectronDensityChecked = true;
            }

            if (mcName == "ALIGNED_SPLIT_MAP_URL" || mcName == "ALIGNED_FULL_MAP_URL" || mcName == "ORIGINAL_MAP_URL")              // not viewable fileds
            {
                DisablePymol();
                DisableMoe();
                ExportToFile.Enabled = ExportToFile.Checked = true;
            }

            else if (mcName == "ALIGNED_FULL_COMPLEX_URL" || mcName == "ORIGINAL_PDB_URL" || mcName == "ALIGNED_SPLIT_COMPLEX_URL")             // viewable by PyMol
            {
                EnableMoe();
                EnablePymol();
                ExportToFile.Enabled = true;
                ExportToFile.Checked = false;
            }
            else             //everything else should be viewable by MOE
            {
                EnableMoe();
                DisablePymol();
                ExportToFile.Enabled = true;
                ExportToFile.Checked = false;
            }

            DialogResult dlgRslt = ShowDialog(SessionManager.ActiveForm);

            if (dlgRslt == DialogResult.Cancel)
            {
                return;
            }

            bool exportSingle = ExportSingle.Checked;
            bool exportMarked = !exportSingle;

            if (!IncludeElectronDensityPyMol.Checked)
            {
                densityMapUrl = null;
            }

            if (exportMarked)             // see if reasonable count if exporting marked rows
            {
                string msg;
                if (markedCount == 0)
                {
                    msg = "No rows have been marked for export";
                    MessageBoxMx.Show(msg, "Mobius", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                if (markedCount > 10)
                {
                    msg =
                        markedCount + " structures have been selected out export.\n" +
                        "Are you sure these are the structures you want to export?";
                    dlgRslt = MessageBoxMx.Show(msg, "Mobius", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                    if (dlgRslt != DialogResult.Yes)
                    {
                        return;
                    }
                }
            }

            // Export to PyMol (Schrodinger) - Collab with Paul Sprengeler and Ken Schwinn
            // Relavant Files:
            // 1. Plugin: CorpView.py (in Mobius config dir)
            // 2. Script: CorpView.pml - Runs the plugin and then passes in the .csv file (in Mobius config dir)
            //		 Expected content (note: <csv-file-name> gets replaced):
            //			import pymol
            //			pluginLocation = 'C:\Progra~1\PyMOL\PyMOL\modules\pmg_tk\startup\CorpView.py'
            //			cmd.do('run ' + pluginLocation)
            //			cmd.do('lv_create_environment')
            //			cmd.do('lv_import_mobius <csv-file-name>')
            //			cmd.do('lv_destroy_environment')
            // 3. Csv file: PyMolBatchLoad.csv - Csv file in format expected by plugin (in Mobius temp dir)

            if (ExportToPyMol.Checked)
            {
                ExportToPyMolMethod(url, densityMapUrl, target, qm);
            }

            else if (ExportToMOE.Checked)             // Export to MOE
            {
                ExportToMOEMethod(url, qm, fmtr, rfld);
            }

            else
            {
                ExportToFilesMethod(url, qm, fmtr, rfld);
            }
        }
Beispiel #10
0
        /// <summary>
        /// ExportToPyMolMethod
        /// </summary>
        /// <param name="url"></param>
        /// <param name="qm"></param>
        void ExportToPyMolMethod(
            string url,
            string densityMapUrl,
            string target,
            QueryManager qm)
        {
            StreamWriter sw;

            string rec, msg, scriptSourceFile, pluginSourceFile, script;

            bool includeProtein = true;             // always include protein

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

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



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

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

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

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

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

            // Get the path to the plugin file

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

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

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

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

            // Get the proper plugin directory

            string pluginFolder = Path.GetDirectoryName(pluginFile);

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

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

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

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

            // Be sure the plugin is up to date

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

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

            // Plug the csv file name into the script

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

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

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

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

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

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

            System.Threading.Thread.Sleep(3000);             // leave message up a bit while PyMOL is starting/being activated
            Progress.Hide();
        }
Beispiel #11
0
        /// <summary>
        /// Execute query in preparation for retrieving rows
        /// </summary>
        /// <param name="parms"></param>

        public override void ExecuteQuery(
            ExecuteQueryParms eqp)
        {
            BufferedRows = new List <UnpivotedAssayResult>();

            MultiTablePivotBrokerTypeData mpd = null;
            MetaTable mt;
            List <MultiDbAssayMetaBroker> mbList = null;
            MultiDbAssayMetaBroker        mb, mb2 = null;
            UnpivotedAssayResult          rr, rr2;
            List <UnpivotedAssayResult>   rrList = new List <UnpivotedAssayResult>(); // list of results summarized by target & result type
            bool unpivotedTableIsFirst;

            object[] vo;
            string   mtName = null;

            int t0 = TimeOfDay.Milliseconds();

            mt = eqp.QueryTable.MetaTable;

            Dictionary <string, MultiTablePivotBrokerTypeData> mbsi = eqp.Qe.MetaBrokerStateInfo;

            if (PivotInCode)
            {
                mpd = mbsi[MpGroupKey];

                if (PivotInCode && mpd.MbInstances.Count == 1 && UnpivotedAssayResult.IsUnpivotedSummarizedMdbAssayTable(mt.Name))
                {
                    PivotInCode = false; // don't multipivot if single unpivoted summary table
                }
            }

            if (!PivotInCode)     // if not multipivot then call generic broker
            {
                base.ExecuteQuery(eqp);
                return;
            }

            if (mpd.FirstTableName != Qt.MetaTable.Name)
            {
                return;                                              // retrieve data for all tables when we see first table
            }
            SetupSecondaryMetaBroker(eqp, mpd, out unpivotedTableIsFirst);
            mb2 = SecondaryMetaBroker;

            mpd.ClearBuffers();

            // Retrieve data & store for associated metabrokers

            if (mb2 == this)
            {
                base.ExecuteQuery(eqp);                  // execute with the base generic broker
            }
            else
            {
                mb2.ExecuteQuery(Eqp2);      // use the secondary broker that was created
            }
            AssayDict dict = new AssayDict();

            rr = new UnpivotedAssayResult();
            int  readCnt             = 0;
            bool includeResultDetail = MdbAssayVoMap.ResultDetailId.Voi >= 0;

            while (true)
            {
                if (mb2 == this)
                {
                    vo = base.NextRow();                      // get data via generic broker
                }
                else
                {
                    vo = mb2.NextRow();          // get data with secondary broker
                }
                if (vo == null)
                {
                    break;
                }

                rr.FromValueObject(vo, mb2.MdbAssayVoMap);         // parse values into a UnpivotedAssayResult
                int rowsFetched = 0, vosCreated = 0;

                for (int pup = 0; pup < 2; pup++)         // first pass for unpivoted table, 2nd for pivoted by gene
                {
                    //try
                    //{
                    if (pup == 0)
                    {
                        if (!unpivotedTableIsFirst)
                        {
                            continue;                                // if no unpivoted first table skip this
                        }
                        mtName = mpd.FirstTableName;                 // unpivoted table should be first
                    }

                    else             // pivoted table
                    {
                        if (Lex.IsNullOrEmpty(rr.GeneSymbol))
                        {
                            continue;                                                                      // skip if no target symbol
                        }
                        if (Lex.Contains(mpd.FirstTableName, "CORP"))                                      // mapped to pivoted corp only table
                        {
                            mtName = MultiDbAssayDataNames.BasePivotTablePrefix + rr.GeneSymbol.ToUpper(); // name of table mapped to
                        }
                        else                                                                               // combined tables
                        {
                            mtName = MultiDbAssayDataNames.CombinedPivotTablePrefix + rr.GeneSymbol.ToUpper();
                        }
                    }
                    //}
                    //catch (Exception ex) { ex = ex; }
                    mt = MetaTableCollection.Get(mtName);
                    if (mt == null)
                    {
                        continue;
                    }
                    if (!mpd.MbInstances.ContainsKey(mt.Name))
                    {
                        continue;                                                    // have row hash for broker?
                    }
                    int mbIdx = 0;
                    if (mpd.MbInstances[mtName] is MultiDbAssayMetaBroker)
                    {
                        mb = (MultiDbAssayMetaBroker)mpd.MbInstances[mtName];                 // broker assoc w/table
                    }
                    else
                    {
                        mbList = (List <MultiDbAssayMetaBroker>)mpd.MbInstances[mtName];
                        mb     = (MultiDbAssayMetaBroker)mbList[0];
                    }

                    while (true)             // copy out for each metabroker for metatable
                    {
                        UnpivotedAssayResultFieldPositionMap voMap = mb.MdbAssayVoMap;
                        vo = rr.ToValueObject(mb.Qt.SelectedCount, voMap);

                        if (mb.MultipivotRowList == null)
                        {
                            mb.MultipivotRowList = new List <object[]>();
                        }
                        mb.MultipivotRowList.Add(vo);

                        if (mbList == null)
                        {
                            break;               // single broker
                        }
                        mbIdx++;                 // go to next broker
                        if (mbIdx >= mbList.Count)
                        {
                            break;                                        // at end of brokers?
                        }
                        mb = (MultiDbAssayMetaBroker)mbList[mbIdx];
                    }
                } // tables to copy data to loop
            }     // row fetch loop

            return;
        }