Beispiel #1
0
        bool Save(bool prompt)
        {
            UserObject uo2;

            if (!IsValidCalcField())
            {
                return(false);
            }
            if (!GetCalcFieldForm())
            {
                return(false);
            }
            if (prompt)
            {
                uo2 = UserObjectSaveDialog.Show("Save Calculated Field Definition", UoIn);
                if (uo2 == null)
                {
                    return(false);
                }
            }
            else
            {
                uo2 = UoIn.Clone();
            }

            if (!UserObjectUtil.UserHasWriteAccess(uo2))
            {             // is the user authorized to save this?
                MessageBoxMx.ShowError("You are not authorized to save this calculated field");
                return(false);
            }

            SessionManager.DisplayStatusMessage("Saving calculated field...");

            string content = CalcField.Serialize();

            uo2.Content = content;

            //need the name of the folder to which the object will be saved
            MetaTreeNode targetFolder = UserObjectTree.GetValidUserObjectTypeFolder(uo2);

            if (targetFolder == null)
            {
                MessageBoxMx.ShowError("Failed to save your calculated field.");
                return(false);
            }

            UserObjectDao.Write(uo2);

            string tName = "CALCFIELD_" + uo2.Id.ToString();

            QbUtil.UpdateMetaTableCollection(tName);
            MainMenuControl.UpdateMruList(tName);

            string title = "Edit Calculated Field - " + uo2.Name;

            Text = title;
            UoIn = uo2.Clone();             // now becomes input object
            SessionManager.DisplayStatusMessage("");
            return(true);
        }
Beispiel #2
0
/// <summary>
/// Setup the form
/// </summary>

        void Setup()
        {
            // Temporary surrogates for current and other temp lists that gets added to the preferred project

            TempNodes = new List <MetaTreeNode>();

            foreach (TempCidList tcl in SS.I.TempCidLists)
            {
                UserObject uo = new UserObject(UserObjectType.CnList);
                uo.ParentFolder     = SS.I.PreferredProjectId;
                uo.ParentFolderType = (uo.ParentFolder.ToUpper().StartsWith("FOLDER_")) ? FolderTypeEnum.User : FolderTypeEnum.System;
                uo.Id          = tcl.Id;
                uo.Name        = "*" + tcl.Name;
                uo.AccessLevel = UserObjectAccess.Private;
                uo.Count       = tcl.Count;
                MetaTreeNode mtn = UserObjectTree.GetValidUserObjectTypeFolder(uo);
                mtn          = UserObjectTree.AddObjectToTree(uo);
                ParentFolder = uo.ParentFolder;
                TempNodes.Add(mtn);
            }

            ListTree1.FillTree(UserObjectType.CnList);
            ListTree2.FillTree(UserObjectType.CnList);

            StatusMessage.Caption = "";

            return;
        }
Beispiel #3
0
        /// <summary>
        /// Change the owner of a UserObject
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>

        public static string ChangeOwner(
            int objId,
            string newOwner)
        {
            newOwner = newOwner.ToUpper();

            UserObject uo = UserObjectDao.ReadHeader(objId);

            if (uo == null)
            {
                return("User object not found: " + objId);
            }
            if (uo.Owner == newOwner)
            {
                return("This user object is already owned by " + newOwner);
            }
            if (!Security.IsAdministrator(SS.I.UserName) && Lex.Ne(uo.Owner, SS.I.UserName))
            {
                return("You're not authorized to change the owner of this user object");
            }

            if (!Security.CanLogon(newOwner))
            {
                return("Not a valid userId: " + newOwner);
            }

            UserInfo ui  = Security.GetUserInfo(newOwner);
            string   msg = "Are you sure you want to transfer ownership of " + Lex.AddDoubleQuotes(uo.Name) + "\n" +
                           "to " + ui.FullName + "?";
            DialogResult dr = MessageBoxMx.Show(msg, "Change Owner", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

            if (dr != DialogResult.Yes)
            {
                return("");
            }

            UserObject uo2 = uo.Clone();

            uo2.Owner = newOwner;
            UserObjectTree.GetValidUserObjectTypeFolder(uo2);          // set valid parent folder
            Permissions.UpdateAclForNewOwner(uo2, uo.Owner, newOwner); // Set the ACL to give us r/w access
            uo2.Content = "ChangeOwner";                               // indicate changing owner
            if (UserObjectDao.ReadHeader(uo2) != null)
            {
                return("A user object with that name already exists for the specified new user");
            }
            UserObjectDao.UpdateHeader(uo2, false, false);

            if (Data.InterfaceRefs.IUserObjectIUD != null)
            {
                Data.InterfaceRefs.IUserObjectIUD.UserObjectDeleted(uo);                                                        // remove from view
            }
            string newOwnerName = SecurityUtil.GetPersonNameReversed(newOwner);

            return("Ownership of \"" + uo2.Name + "\" has been changed to " + newOwnerName);
        }
Beispiel #4
0
/// <summary>
/// Save the SpotfireLink UserObject
/// </summary>
/// <param name="prompt"></param>
/// <returns></returns>

        bool Save(bool prompt)
        {
            UserObject uo2;

            if (!IsValidSpotfireLink())
            {
                return(false);
            }
            if (!GetSpotfireLinkForm())
            {
                return(false);
            }
            if (prompt)
            {
                uo2 = UserObjectSaveDialog.Show("Save Spotfire link Definition", UoIn);
                if (uo2 == null)
                {
                    return(false);
                }
            }

            else
            {
                uo2 = UoIn.Clone();
            }

            uo2.Content = SpotfireViewProps.Serialize();

            if (!UserObjectUtil.UserHasWriteAccess(uo2))
            {             // is the user authorized to save this?
                MessageBoxMx.ShowError("You are not authorized to save this Spotfire link");
                return(false);
            }

            SessionManager.DisplayStatusMessage("Saving Spotfire link...");

            //need the name of the folder to which the object will be saved
            MetaTreeNode targetFolder = UserObjectTree.GetValidUserObjectTypeFolder(uo2);

            if (targetFolder == null)
            {
                MessageBoxMx.ShowError("Failed to save your Spotfire link.");
                return(false);
            }

            UserObjectDao.Write(uo2);

            MainMenuControl.UpdateMruList(uo2.InternalName);

            string title = "Edit Spotfire Link - " + uo2.Name;

            Text = title;
            UoIn = uo2.Clone();             // now becomes input object
            SessionManager.DisplayStatusMessage("");
            return(true);
        }
Beispiel #5
0
        /// <summary>
/// Create an annotation table given its metatable and user object
/// </summary>
/// <param name="mt"></param>
/// <param name="uo"></param>

        public static void CreateAnnotationTable(
            MetaTable mt,
            UserObject uo)
        {
            uo.Type    = UserObjectType.Annotation; // be sure type is set
            uo.Content = mt.Serialize();            // serialize the metatable to the user object
            UserObjectTree.GetValidUserObjectTypeFolder(uo);
            UserObjectDao.Write(uo);                // write the user object

            MetaTableCollection.UpdateGlobally(mt); // update map with modified metatable
            return;
        }
Beispiel #6
0
        /// <summary>
        /// Save the specified list object
        /// </summary>
        /// <returns></returns>

        public static UserObject SaveList(
            CidList list,
            string caption,
            bool saveToTempList,
            string tempListName)
        {
            UserObject uo = null;
            String     name, txt;

            uo = new UserObject(UserObjectType.CnList);
            if (saveToTempList)
            {
                if (Lex.IsNullOrEmpty(tempListName))
                {
                    tempListName = InputBoxMx.Show("Enter the name of the temporary list to be saved to:", caption);
                }
                if (Lex.IsNullOrEmpty(tempListName))
                {
                    return(null);
                }

                uo.Owner        = SS.I.UserName;
                uo.ParentFolder = UserObject.TempFolderName;
                uo.Name         = tempListName;
            }

            else
            {
                uo = UserObjectSaveDialog.Show(caption, uo);              // save to permanent list
            }
            if (uo == null)
            {
                return(null);
            }
            if (!uo.IsTempObject)             // assign valid folder unless current list
            {
                UserObjectTree.GetValidUserObjectTypeFolder(uo);
            }

            SessionManager.DisplayStatusMessage("Saving List " + uo.Name + "...");

            list.UserObject = uo;
            int rc = Write(list);

            MainMenuControl.UpdateMruList(uo.InternalName);

            SessionManager.DisplayStatusMessage("");
            return(uo);
        }
Beispiel #7
0
        /// <summary>
        /// Create an annotation table from a DataTable
        /// </summary>
        /// <param name="fullyQualifiedName">Fully qualified name to assign to table</param>
        /// <param name="dataTable">DataTable containing table definition & data</param>
        /// <param name="showProgress">Display dialog box showing progress of creation</param>
        /// <returns>Internal name assigned to annotation table (ANNOTATION_12345)</returns>

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

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

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

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

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

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

            MetaTable mt = new MetaTable();

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

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

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

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

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

                mt.MetaColumns.Add(mc);
            }

            ToolHelper.CreateAnnotationTable(mt, auo);

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

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

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

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

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

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

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

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

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

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

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

                writeCount++;

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

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

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

            if (showProgress)
            {
                Progress.Hide();
            }
            return(mt);            // return metatable name
        }
Beispiel #8
0
/// <summary>
/// Right-click commands on objects in a tree
/// </summary>
/// <param name="command">The command to process</param>
        /// <param name="mtn">MetaTreeNode</param>
        /// <param name="uo">Any associated user object</param>
        /// <param name="ctc">ContentsTreeControl</param>
/// <returns></returns>

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

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

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

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

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

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

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

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

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

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

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

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

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

                    Progress.Hide();
                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    newAccess = UserObjectAccess.Private;
                }

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

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

                return(true);
            }

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

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

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

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

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

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

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

            else
            {
                return(false);       // command not recognized
            }
            return(true);            // command recognized and processed
        }
Beispiel #9
0
        /// <summary>
        /// Search button clicked, process input
        /// </summary>
        /// <returns></returns>

        DialogResult ProcessInput()
        {
            CidList      cidList             = null;
            StreamReader structureFileReader = null;
            string       qid;       // query identifier, compoundId, file name or sdFile key value
            QueryManager qm;
            DataTableMx  dt;
            DataColumn   dc;
            DataRowMx    dr;
            //object[] dr; // if using Qe
            DialogResult   dlgRslt = DialogResult.OK;
            Query          q = null;
            QueryTable     qt = null;
            QueryColumn    simScoreQc, structQc;          // query column containing latest query settings
            MetaTable      mt = null;
            MetaColumn     keyMc = null, structMc = null, dbSetMc = null, simScoreMc = null, mc;
            MetaColumnType storageType;
            string         txt, tok;

            if (DatabasesToSearch.Text == "")
            {
                MessageBoxMx.ShowError("Databases to search must be defined.");
                DatabasesToSearch.Focus();
                return(DialogResult.Cancel);
            }

            // Get list of databases

            string[]         dba    = DatabasesToSearch.Text.Split(',');
            List <MetaTable> tables = new List <MetaTable>();

            foreach (string dbLabel0 in dba)
            {
                string dbLabel = dbLabel0.Trim();

                RootTable dbInfo = RootTable.GetFromTableLabel(dbLabel);
                if (dbInfo == null)
                {
                    MessageBoxMx.ShowError("Can't find database " + DatabasesToSearch.Text);
                    DatabasesToSearch.Focus();
                    return(DialogResult.Cancel);
                }

                mt = MetaTableCollection.Get(dbInfo.MetaTableName);
                if (mt == null)
                {
                    MessageBoxMx.ShowError("Unable to locate parent structure table for database: " + DatabasesToSearch.Text);
                    DatabasesToSearch.Focus();
                    return(DialogResult.Cancel);
                }

                if (dbSetMc == null)
                {
                    dbSetMc = mt.DatabaseListMetaColumn;
                }

                tables.Add(mt);
            }

            if (dbSetMc == null)
            {
                throw new Exception("\"Databases\" metacolumn not found for any of the databases to search");
            }

            // Validate other form values

            RetrieveStructures = RetrieveMatchingStructures.Checked;

            bool fromList        = FromList.Checked;
            int  listCidsRead    = 0;
            int  inputQueryCount = -1;

            if (fromList)             // using list, validate list name
            {
                if (SavedListUo == null)
                {
                    MessageBoxMx.ShowError("Compound list must be defined.");
                    ListName.Focus();
                    return(DialogResult.Cancel);
                }

                cidList = CidListCommand.Read(SavedListUo);
                if (cidList == null)
                {
                    MessageBoxMx.ShowError("Error reading list.");
                    ListName.Focus();
                    return(DialogResult.Cancel);
                }

                inputQueryCount = cidList.Count;
            }

            else             // Using SdFile, validate SdFile name
            {
                StructureFile = FileName.Text;
                if (StructureFile == "")
                {
                    MessageBoxMx.ShowError("File must be defined.");
                    FileName.Focus();
                    return(DialogResult.Cancel);
                }

                try { structureFileReader = new StreamReader(StructureFile); structureFileReader.Close(); }
                catch (Exception ex)
                {
                    MessageBoxMx.ShowError("Can't read file: " + Lex.Dq(StructureFile));
                    FileName.Focus();
                    return(DialogResult.Cancel);
                }

                keyField = KeyField.Text;             // get key, blank to use name in 1st line

                inputQueryCount = -1;                 // don't know how many queries unless we read the file (todo?)
            }

            tok = ResultsName.Text.Trim();             // name to store results under
            if (tok == "")
            {
                MessageBoxMx.ShowError("A name for the results must be provided.");
                ResultsName.Focus();
                return(DialogResult.Cancel);
            }

            if (SubStruct.Checked)
            {
                Psc.SearchType = StructureSearchType.Substructure;
            }
            else if (Full.Checked)
            {
                Psc.SearchType = StructureSearchType.FullStructure;
            }
            else if (Similarity.Checked)
            {
                Psc.SearchType = StructureSearchType.MolSim;
            }
            else
            {
                throw new Exception("Unrecognized search type");
            }

            // Write initial log entries

            SearchCount++;
            string logFileName = ClientDirs.DefaultMobiusUserDocumentsFolder + @"\Multistructure Search " + SearchCount + ".txt";

            if (!UIMisc.CanWriteFileToDefaultDir(logFileName))
            {
                return(DialogResult.Cancel);
            }
            LogStream = new StreamWriter(logFileName);

            if (ResultsUo == null)
            {
                ResultsUo = new UserObject(UserObjectType.Annotation);
            }
            ResultsUo.Name = tok;
            UserObjectTree.GetValidUserObjectTypeFolder(ResultsUo);

            DateTime startTime = DateTime.Now;

            WriteToLog("Multiple " + Psc.SearchType + " Search");
            WriteToLog("Databases: " + DatabasesToSearch.Text);
            WriteToLog("Date: " + startTime);
            if (fromList)
            {
                WriteToLog("Input List: " + SavedListUo.Name);
            }
            else
            {
                WriteToLog("Input Structure File: " + StructureFile);
            }
            WriteToLog("Output List: " + ResultsUo.Name);

            WriteToLog("Log File: " + logFileName);
            WriteToLog("");
            WriteToLog("Query, Match, Score");

            int              queryCount           = 0;
            int              matchAtLeastOneCount = 0;
            MoleculeMx       queryStructure       = null; // current structure being searched
            CidList          matchList            = new CidList();
            List <MatchData> matchData            = new List <MatchData>();

            if (FromFile.Checked)             // open SdFile as required
            {
                structureFileReader = new StreamReader(StructureFile);
            }

            // Search of structures one at a time

            while (true)
            {
                if (fromList)                 // get next structure from list
                {
                    if (listCidsRead >= cidList.Count)
                    {
                        break;
                    }
                    qid = cidList[listCidsRead].Cid;
                    listCidsRead++;
                    if (qid.Trim() == "")
                    {
                        continue;
                    }
                    if (qid.ToLower().IndexOf(".mol") > 0 || qid.ToLower().IndexOf(".skc") > 0)
                    {                     // file reference
                        if (!File.Exists(qid))
                        {
                            continue;
                        }
                        if (qid.ToLower().IndexOf(".mol") > 0)
                        {
                            queryStructure = MoleculeMx.ReadMolfile(qid);
                        }
                        else
                        {
                            queryStructure = MoleculeMx.ReadSketchFile(qid);
                        }
                    }

                    else
                    {
                        queryStructure = MoleculeUtil.SelectMoleculeForCid(qid);
                    }
                    if (queryStructure == null || queryStructure.AtomCount == 0)
                    {
                        continue;                                                                              // oops
                    }
                }

                else                 // get next structure from input file
                {
                    qid = null;

                    if (StructureFile.ToLower().EndsWith(".sdf"))
                    {
                        List <SdFileField> fList = SdFileDao.Read(structureFileReader);
                        if (fList == null)                         // end of sdFile
                        {
                            structureFileReader.Close();
                            break;
                        }
                        if (fList.Count == 0)
                        {
                            continue;
                        }

                        queryStructure = new MoleculeMx(MoleculeFormat.Molfile, fList[0].Data);
                        if (queryStructure == null || queryStructure.AtomCount == 0)
                        {
                            continue;
                        }

                        if (keyField != "")                         // key field specified?
                        {
                            qid = SdFileDao.GetDataField(fList, keyField);
                        }
                        else                         // get name from 1st line of molfile
                        {
                            string molFile = fList[0].Data;
                            int    i1      = molFile.IndexOf("\n");
                            if (i1 == 0)
                            {
                                qid = "";
                            }
                            else
                            {
                                qid = molFile.Substring(0, i1).Trim();
                            }
                        }
                        if (string.IsNullOrEmpty(qid))
                        {
                            qid = SdFileDao.GetDataField(fList, "compound_id");
                        }
                    }

                    else                     // assume smiles file
                    {
                        string smiles = structureFileReader.ReadLine();
                        if (smiles == null)                         // end of sdFile
                        {
                            structureFileReader.Close();
                            break;
                        }
                        smiles = smiles.Trim();
                        if (smiles.Length == 0)
                        {
                            continue;
                        }

                        int i1 = smiles.IndexOf(",");                         // get any preceeding queryId
                        if (i1 < 0)
                        {
                            i1 = smiles.IndexOf("\t");
                        }
                        if (i1 >= 0)
                        {
                            qid    = smiles.Substring(0, i1).Trim();
                            smiles = smiles.Substring(i1 + 1).Trim();
                        }

                        queryStructure = new MoleculeMx(MoleculeFormat.Smiles, smiles);
                        if (queryStructure == null || queryStructure.AtomCount == 0)
                        {
                            continue;
                        }
                    }

                    if (qid == null || qid.Trim() == "")
                    {
                        qid = (queryCount + 1).ToString();                                                      // be sure we have a query id
                    }
                }

                queryCount++;                 // count the query
                if (queryStructure == null || queryStructure.AtomCount == 0)
                {
                    WriteToLog("Error converting specific structure " + queryCount.ToString() + ", " + qid);
                    continue;
                }

                queryStructure.RemoveStructureCaption();                 // remove any Mobius-added caption
                Psc.Molecule = queryStructure;

                string msg =
                    "Searching Structure: " + queryCount.ToString();
                if (inputQueryCount > 0)
                {
                    msg += " of " + inputQueryCount.ToString();
                }
                msg += "\n" +
                       "Structures with one or more matches: " + matchAtLeastOneCount.ToString() + "\n" +
                       "Total Matches: " + matchList.Count.ToString();

                Progress.Show(msg);

                // Do the search over the list of databases

                for (int ti = 0; ti < tables.Count; ti++)
                {
                    mt = tables[ti];

                    q = new Query();                     // build basic query
                    //q.SingleStepExecution = true; // do in single step (doesn't currently return sim score)
                    q.ShowStereoComments = false;

                    qt = new QueryTable(mt);

                    q.AddQueryTable(qt);
                    qt.SelectKeyOnly();                     // start selecting desired cols

                    keyMc = mt.KeyMetaColumn;

                    structMc          = mt.FirstStructureMetaColumn;
                    structQc          = qt.GetQueryColumnByName(structMc.Name);
                    structQc.Selected = RetrieveStructures;

                    dbSetMc = mt.DatabaseListMetaColumn;
                    if (dbSetMc == null)
                    {
                        throw new Exception("\"Databases\" metacolumn not found for table: " + mt.Label);
                    }
                    QueryColumn dbSetQc = qt.GetQueryColumnByName(dbSetMc.Name);
                    dbSetQc.Selected = true;                     // select the database name
                    RootTable root = RootTable.GetFromTableName(mt.Name);
                    txt = " in (" + root.Label + ")";
                    dbSetQc.Criteria        = dbSetMc.Name + txt;
                    dbSetQc.CriteriaDisplay = txt;

                    simScoreMc = mt.SimilarityScoreMetaColumn;
                    simScoreQc = null;
                    if (simScoreMc != null)                     // get sim score if it exists
                    {
                        simScoreQc          = qt.GetQueryColumnByName(simScoreMc.Name);
                        simScoreQc.Selected = true;                         // return sim score
                    }

                    Psc.QueryColumn = structQc;
                    ParsedStructureCriteria psc2 = AdjustSearchForSmallWorldAsNeeded(Psc);
                    psc2.ConvertToQueryColumnCriteria(structQc);                     // format the QC for the structure search

                    DateTime t0 = DateTime.Now;

                    //QueryEngine qe = new QueryEngine();
                    //qe.NextRowsMin = 1000; // minimum number of rows to prefetch
                    //qe.NextRowsMax = -1; // maximum number of rows to prefetch
                    //qe.NextRowsMaxTime = 10000; // max time in milliseconds for next fetch
                    //qe.ExecuteQuery(q);

                    qm = new QueryManager();
                    try { dlgRslt = qm.ExecuteQuery(ref q); }
                    catch (Exception ex)
                    {
                        WriteToLog("Error searching structure: " + ex.Message + ", " + queryCount.ToString() + ", " + qid);
                        continue;
                    }

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

                    double executeTime = TimeOfDay.Delta(ref t0);

                    int offset = qm.DataTableManager.KeyValueVoPos + 1;
                    //int offset = 0; // for QE
                    int keyPos = offset++;
                    int strPos = RetrieveStructures ? offset++ : -1;
                    int dbPos  = offset++;
                    int simPos = offset++;

                    int fetchCnt = 0;
                    while (true)
                    {
                        dr = qm.NextRow();
                        //dr = qe.NextRow(); // for Qe
                        if (dr == null)
                        {
                            break;
                        }

                        fetchCnt++;

                        if (fetchCnt == 1)
                        {
                            matchAtLeastOneCount++;                             // number of queries that have at least one match
                        }
                        MatchData md = new MatchData();
                        md.Qno = queryCount;
                        md.Qid = qid;
                        if (RetrieveStructures)
                        {
                            md.Qstr = "Chime=" + queryStructure.GetChimeString();
                        }

                        CompoundId cid = CompoundId.ConvertTo(dr[keyPos]);
                        md.Mid = cid.Value;

                        if (RetrieveStructures)
                        {
                            MoleculeMx ms = MoleculeMx.ConvertTo(dr[strPos]);
                            if (!NullValue.IsNull(ms))
                            {
                                md.Mstr = "Chime=" + ms.GetChimeString();
                            }
                        }

                        StringMx db = StringMx.ConvertTo(dr[dbPos]);
                        if (!NullValue.IsNull(db))
                        {
                            md.Db = db.Value;
                        }

                        if (Psc.SearchType == StructureSearchType.MolSim)
                        {
                            NumberMx nex = NumberMx.ConvertTo(dr[simPos]);
                            if (!NullValue.IsNull(nex))
                            {
                                md.Score = nex.Value;
                            }
                        }

                        if (matchList.Contains(cid.Value))                         // already have compound id as match for other query?
                        {
                            if (Psc.SearchType != StructureSearchType.MolSim)
                            {
                                continue;                                                             // if similarity search see if more similar
                            }
                            CidListElement le = matchList.Get(cid.Value);                             // reference current score
                            if (le.Tag > md.Score)
                            {
                                continue;                                         // only replace if more similar
                            }
                            matchList.Remove(le.Cid);                             // remove from list
                            for (int mi = 0; mi < matchData.Count; mi++)          // remove from data
                            {
                                if (matchData[mi].Mid == md.Mid)
                                {
                                    matchData.RemoveAt(mi);
                                    break;
                                }
                            }
                        }

                        matchList.Add(md.Mid);
                        matchList.Get(md.Mid).Tag = md.Score;      // keep score in list
                        matchData.Add(md);                         // add to results

                        txt = md.Qid + ", " + md.Mid + ", " + md.Score.ToString();
                        WriteToLog(txt);
                    }                     // Fetch result loop

                    double fetchTime = TimeOfDay.Delta(ref t0);
                }                 // DB loop

                if (Progress.CancelRequested)
                {
                    Progress.Hide();
                    MessageBoxMx.ShowError("Search cancelled.");
                    try { LogStream.Close(); } catch { }
                    return(DialogResult.Cancel);
                }
            }                                           // key loop

            CidListCommand.WriteCurrentList(matchList); // write the list of numbers

            UsageDao.LogEvent("MultipleStructSearch");

            txt =
                "=== Multiple structure search complete ===\r\n\r\n" +

                "Structures Searched: " + queryCount.ToString() + "\r\n";

            txt +=
                "Structures with one or more matches: " + matchAtLeastOneCount.ToString() + "\r\n" +
                "Total Matches: " + matchList.Count.ToString() + "\r\n";

            TimeSpan ts = DateTime.Now.Subtract(startTime);

            ts   = new TimeSpan(ts.Hours, ts.Minutes, ts.Seconds);
            txt += "Total Time: " + ts + "\r\n\r\n";

            WriteToLog("\r\n" + txt);
            try { LogStream.Close(); } catch { }

            if (matchList.Count == 0)
            {
                Progress.Hide();
                MessageBoxMx.ShowError("No matches have been found.");
                return(DialogResult.Cancel);
            }

            tok = "Matching compound ids";
            if (Psc.SearchType == StructureSearchType.MolSim)
            {
                tok = "Similar compound ids";
            }
            txt += tok + " have been written to the current list: " + ResultsUo.Name + "\n" +
                   "Log file written to: " + logFileName + "\n\n" +
                   "Do you want to view the match results?";

            DialogResult dRslt = MessageBoxMx.Show(txt, "Multiple Structure Search", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

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

            else if (dRslt == DialogResult.No)             // show log
            {
                SystemUtil.StartProcess(logFileName);
                return(DialogResult.Cancel);
            }

            // Display results

            Progress.Show("Formatting results...");

            mt                = new MetaTable();
            mt.Name           = "MULTSTRUCTSEARCH_" + SearchCount;
            mt.Label          = "Multiple Structure Search " + SearchCount;
            mt.TableMap       = "Mobius.Tools.MultStructSearch";       // plugin id
            mt.MetaBrokerType = MetaBrokerType.NoSql;

            ColumnSelectionEnum structureColumnSelection = RetrieveStructures ? ColumnSelectionEnum.Selected : ColumnSelectionEnum.Unselected;

            keyMc       = keyMc.Clone();
            keyMc.Name  = "MatchingCid";
            keyMc.Label = "Matching Compound Id";
            mt.AddMetaColumn(keyMc);

            structMc                  = structMc.Clone();
            structMc.Name             = "MatchingStructure";
            structMc.Label            = "Matching Structure";
            structMc.InitialSelection = structureColumnSelection;
            mt.AddMetaColumn(structMc);

            dbSetMc      = dbSetMc.Clone();
            dbSetMc.Name = "Database";
            mt.AddMetaColumn(dbSetMc);
            //if (DatabasesToSearch.Text.Contains(","))
            dbSetMc.InitialSelection = ColumnSelectionEnum.Selected;

            mc = mt.AddMetaColumn("Molsimilarity", "Similarity Search Score", MetaColumnType.Number, ColumnSelectionEnum.Unselected, 10);
            if (Psc.SearchType == StructureSearchType.MolSim)
            {
                mc.InitialSelection = ColumnSelectionEnum.Selected;
            }

            mc = mt.AddMetaColumn("QueryNo", "Query Number", MetaColumnType.Integer);
            //mc = mt.AddMetaColumn("QueryMatchNo", "Query Match Number", MetaColumnType.Integer);

            mc = mt.AddMetaColumn("QueryId", "Query Id", MetaColumnType.String);
            mc = mt.AddMetaColumn("QueryStructure", "Query Structure", MetaColumnType.Structure);
            mc.InitialSelection = structureColumnSelection;

            q  = ToolHelper.InitEmbeddedDataToolQuery(mt);
            dt = q.ResultsDataTable as DataTableMx;

            for (int mi = 0; mi < matchData.Count; mi++)
            {
                MatchData md = matchData[mi];
                dr = dt.NewRow();
                dr[qt.Alias + ".MatchingCid"] = new CompoundId(md.Mid);
                if (RetrieveStructures)
                {
                    dr[qt.Alias + ".MatchingStructure"] = new MoleculeMx(MoleculeFormat.Chime, md.Mstr);
                }
                dr[qt.Alias + ".Database"] = new StringMx(md.Db);
                if (Psc.SearchType == StructureSearchType.MolSim)
                {
                    dr[qt.Alias + ".Molsimilarity"] = new NumberMx(md.Score);
                }
                dr[qt.Alias + ".QueryNo"] = new NumberMx(md.Qno);
                dr[qt.Alias + ".QueryId"] = new StringMx(md.Qid);
                if (RetrieveStructures)
                {
                    dr[qt.Alias + ".QueryStructure"] = new MoleculeMx(MoleculeFormat.Chime, md.Qstr);
                }

                dt.Rows.Add(dr);
            }

            ToolHelper.DisplayData(q, dt, true);

            Progress.Hide();
            return(DialogResult.OK);
        }
Beispiel #10
0
/// <summary>
/// Save/SaveAs the list
/// </summary>
/// <param name="saveAs">SaveAs under another list name</param>
/// <param name="saveAsTempList">Save as a temp list</param>
/// <param name="tempListName">Temp list name to save under, prompt if null</param>
/// <returns></returns>

        bool Save(
            bool saveAs,
            bool saveAsTempList,
            string tempListName)
        {
            if (!ValidateList())
            {
                return(false);                             // Validate the list if requested
            }
// Get list name if needed & check that user can modify it

            if (saveAs || CidList.UserObject.Id == 0)
            {
                CidList.UserObject.Id = 0;                 // assign new id
                if (saveAsTempList)
                {
                    if (tempListName == null)                     // prompt for name
                    {
                        tempListName = CidListCommand.PromptForNewTempListName();
                        if (tempListName == null)
                        {
                            return(false);
                        }
                    }
                    CidList.UserObject = new UserObject(UserObjectType.CnList);
                    CidList.UserObject.ParentFolder = UserObject.TempFolderName;
                    CidList.UserObject.Name         = tempListName;
                    CidList.UserObject.Owner        = SS.I.UserName;
                }

                else                 // save as permanent list
                {
                    UserObject existingUo = CidList.UserObject;
                    if (CidList.UserObject.Id == 0)
                    {
                        existingUo = new UserObject(UserObjectType.CnList);
                    }
                    UserObject listUo = UserObjectSaveDialog.Show("Save As", existingUo);
                    if (listUo == null)
                    {
                        return(false);
                    }
                    CidList.UserObject = listUo;
                }
            }

            if (!UserObjectUtil.UserHasWriteAccess(CidList.UserObject))
            {             // is the user authorized to save this list?
                MessageBoxMx.ShowError("You are not authorized to save this list");
                return(false);
            }

// Write out the list

            DisplayStatusMsg("Saving list...");

            if (CidList.UserObject.HasDefinedParentFolder)
            {
                MetaTreeNode targetFolder = UserObjectTree.GetValidUserObjectTypeFolder(CidList.UserObject);
                if (targetFolder == null)
                {                 // shouldn't happen
                    MessageBoxMx.ShowError("The list could not be saved because the folder it was in no longer exists.  Please try SaveAs instead.");
                    return(false);
                }
            }

            GetNormalizedListFromControl(CidList);

            if (!CidList.UserObject.IsCurrentObject)             // normal list?
            {
                CidListCommand.Write(CidList);
            }

            else                                       // special processing for current list
            {
                SessionManager.LockResultsKeys = true; // avoid possible overwrite of ResultsKeys if in single step query
                int           rc            = CidListCommand.Write(CidList);
                List <string> curListString = CidListCommand.ReadCurrentListLocal().ToStringList();
                SessionManager.CurrentResultKeys = curListString;
                SessionManager.DisplayCurrentCount();
                SessionManager.LockResultsKeys = false;
            }

            //string cFile = SS.I.ClientDefaultDir + @"\Previous.lst"
            //if (UIMisc.CanWriteFileToDefaultDir(cFile))
            //{
            //  StreamWriter sw = new StreamWriter(cFile); // save copy to disk
            //  sw.Write(CidList.UserObject.Content);
            //  sw.Close();
            //}

            int cncnt = CidList.Count;

            DisplayStatusMsg("List saved");

            Before = CidListCtl.Text;
            string tok = UserObjectUtil.GetName(ListName);

            Text = "Edit List - [" + CidList.UserObject.Name + "]";
            return(true);
        }