示例#1
0
        void SetupGrid(List <UserObject> alerts)
        {
            string txt, tok;

            DataTable dt = CreateDataTable();

            foreach (UserObject uo in alerts)             // fill the grid
            {
                UserObject uo2   = uo;
                Alert      alert = Alert.GetAlertFromUserObject(uo2, false);

                UserObject quo = UserObjectDao.ReadHeader(alert.QueryObjId);                 // get query header for name
                if (quo == null)
                {
                    continue;                              // associated query missing?
                }
                alert.QueryName       = quo.Name;
                alert.LastQueryUpdate = quo.UpdateDateTime;

                DataRow dr = dt.NewRow();
                SetDataRow(dr, alert);
                dt.Rows.Add(dr);
            }

            Grid.DataSource = dt;
            Grid.Refresh();

            if (ServicesIniFile.Read("AlertHelpUrl") != "")
            {
                Help.Enabled = true;
            }

            return;
        }
示例#2
0
        /// <summary>
        /// Get security parms
        /// </summary>
        /// <returns></returns>

        public static void ReadSecurityParms()
        {
            if (_readSecurityParms)
            {
                return;
            }
            if (ServicesIniFile.IniFile == null)
            {
                return;
            }

            _useActiveDirectory                  = ServicesIniFile.ReadBool("UseActiveDirectory", true);
            _approvedMobiusUsersGroupName        = ServicesIniFile.Read("ApprovedMobiusUsers", @"<domain>Approved_Mobius_Users");
            _approvedMobiusChemViewGroupName     = ServicesIniFile.Read("ApprovedMobiusChemView", @"<domain>Approved_Mobius_Chemview");
            _approvedMobiusSequenceViewGroupName = ServicesIniFile.Read("ApprovedMobiusSequenceView", @"<domain>Lg_Mol_Search_Incl_Seq");
            string txt = ServicesIniFile.Read("SpecialMobiusSystemAccounts", "MOBIUS");

            _specialMobiusSystemAccounts = new HashSet <string>();
            string[] sa = txt.Split(',');
            foreach (string s in sa)
            {
                if (Lex.IsDefined(s))
                {
                    _specialMobiusSystemAccounts.Add(s.Trim().ToUpper());
                }
            }

            _readSecurityParms = true;
        }
示例#3
0
        /// <summary>
        /// Initialize the UAL
        /// </summary>

        public static void Initialize(string iniFileName)
        {
            ServicesDirs.ExecutablePath   = Application.ExecutablePath;
            ServicesDirs.ServerStartupDir = Application.StartupPath;

            //DebugLog.Message("UalUtil.Initialize iniFileName: " + iniFileName);

            ServicesIniFile.Initialize(iniFileName);
            CommonConfigInfo.MiscConfigDir = ServicesIniFile.Read("MiscConfigDirectory");

            ServicesDirs.MetaDataDir = ServicesIniFile.Read("MetaDataDirectory");
            //DebugLog.Message("MetaDataDir: " + MetaDataDir);

            ServicesDirs.TargetMapsDir = ServicesDirs.MetaDataDir + @"\TargetMaps";             // target maps relative to MetaDataDir

            ServicesDirs.DocDir   = ServicesIniFile.Read("DocumentDirectory");
            ServicesDirs.LogDir   = ServicesIniFile.Read("LogDirectory");
            ServicesDirs.CacheDir = ServicesIniFile.Read("CacheDirectory");
            ServicesDirs.TempDir  = TempFile.TempDir = ServicesIniFile.Read("TempDirectory");
            ServicesDirs.QueryResultsDataSetDir = ServicesIniFile.Read("QueryResultsDataSetDirectory");
            ServicesDirs.BackgroundExportDir    = ServicesIniFile.Read("BackgroundExportDirectory");
            ServicesDirs.BinaryDataDir          = ServicesIniFile.Read("BinaryDataDirectory");

            ServicesDirs.ModelQueriesDir = ServicesIniFile.Read("ModelQueriesDirectory");
            ServicesDirs.ModelQueriesDir = ServicesIniFile.Read("ModelQueriesDirectory");
            ServicesDirs.ImageDir        = ServicesIniFile.Read("ImageDirectory");
            ServicesDirs.ImageDirUNC     = ServicesIniFile.Read("ImageDirectoryUNC");

            LogExecutionTimes = ServicesIniFile.ReadBool("LogUalExecutionTimes", false);

            DbCommandMx.LogDatabaseCalls = ServicesIniFile.ReadBool("LogDatabaseCalls", DbCommandMx.LogDatabaseCalls);

            return;
        }
示例#4
0
        internal void ShowRunQueryUrl()
        {
            if (Query == null || Query.UserObject == null || Query.UserObject.Id <= 0)
            {
                MessageBoxMx.ShowError("The query must first be saved.");
                return;
            }

            string folder   = ServicesIniFile.Read("QueryLinksNetworkFolder"); // get unc form of folder
            string fileName = "Run_Query_" + Query.UserObject.Id + ".bat";     // file name
            string uncPath  = folder + '\\' + fileName;                        // unc file to write now and read later

            string       tempFile = TempFile.GetTempFileName();
            StreamWriter sw       = new StreamWriter(tempFile);
            string       cmd      =                                                            // batch command to start the Mobius client and run the specified query
                                    Lex.AddDoubleQuotes(ClientDirs.ExecutablePath) +           // path to executable in quotes
                                    " Mobius:Command='Run Query " + Query.UserObject.Id + "'"; // the mobius command to run

            sw.WriteLine(cmd);
            sw.Close();

            ServerFile.CopyToServer(tempFile, uncPath);
            FileUtil.DeleteFile(tempFile);

            string url = "file:///" + folder.Replace('\\', '/') + "/" + fileName;             // put in "file:" schema & switch slashes to get URL from UNC name

            InputBoxMx.Show(
                "The following URL can be used from a web page " +
                "to start Mobius and run the current query:",
                "Run Query URL",
                url);
            //"Mobius:Command='Run Query " + Query.UserObject.Id + "'"); // this is better but isn't accepted by SharePoint

            return;
        }
示例#5
0
        /// <summary>
        /// Main tool entry point
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>

        public string Run(
            string args)
        {
            QbUtil.SetMode(QueryMode.Build);             // be sure in build mode

            //List<StructureDbInfo> dbInfo = StructureDbInfo.GetList(); // get list of root structure tables
            //MetaTable mt = MetaTableCollection.Get(dbInfo[0].StructureTable); // use first structure table

            if (DatabasesToSearch.Text == "")
            {                                                  // default to first structure table
                List <RootTable> dbInfo = RootTable.GetList(); // get list of root structure tables
                if (dbInfo != null && dbInfo.Count > 0)
                {
                    DatabasesToSearch.Text = dbInfo[0].Label;
                }
            }

            if (ServicesIniFile.Read("MultStructSearchHelpUrl") != "")
            {
                Help.Enabled = true;
            }

            DialogResult dr = ShowDialog(SessionManager.ActiveForm);

            return("");
        }
示例#6
0
/// <summary>
/// Write out the data and return the html/js to open the template .dxp file with the exported data file
/// </summary>
/// <param name="q"></param>
/// <param name="trvp"></param>
/// <returns></returns>

        public static string CreateSpotfireAnalysisDocument(
            Query q,
            TargetSummaryOptions trvp)
        {
            ExportParms ep = new ExportParms();

            ep.OutputDestination = OutputDest.TextFile;
            ep.ExportFileFormat  = ExportFileFormat.Csv;
            ep.OutputFileName    = TempFile.GetTempFileName(".csv");          // temp .csv file to export to
            ep.IncludeDataTypes  = true;

            string result = UalUtil.IQueryExec.RunQuery(q, ep);             // do the export

            if (result == null)
            {
                return(null);                      // just return if cancelled
            }
            string templateLibFolder =             // unc name of the lib folder (not currently used)
                                       ServicesIniFile.Read("SpotfireLibraryFolder");

            string templateLibUrl =             // url of the library containing the Mobius templates
                                    ServicesIniFile.Read("SpotfireLibraryUrl");

            templateLibUrl = @"http://[server]/SpotfireWeb/Library.aspx?folder=DCRT%20(chemistry)%20users/Mobius/Templates";

            string templateUrl = templateLibUrl + "/MultiDbView";

            string html = templateUrl;             // todo, build html/js to open the template with the specified file

            return(html);
        }
示例#7
0
        /// <summary>
        /// Build & return the full MetaTree
        /// </summary>
        ///
        public Dictionary <string, MetaTreeNode> GetMetaTree2()
        {
            if (ServiceFacade.UseRemoteServices)
            {
                NativeMethodTransportObject resultObject = ServiceFacade.CallServiceMethod(
                    ServiceCodes.MobiusMetaDataService,
                    MobiusMetaDataService.Build,
                    new object[] { false });

                // Get the cache from the server if newer than the client cache

                string cacheFile       = ServicesIniFile.Read("CachedTreeFile", DefaultCachedTreeFile);
                string serverCacheFile = @"<MetaDataDir>\MetaTrees\" + cacheFile;

                string clientCacheFile = ClientDirs.CacheDir + @"\" + cacheFile;
                //ServerFile.Get(serverCacheFile, clientCacheFile); // debug, always get
                bool changed = ServerFile.GetIfChanged(serverCacheFile, clientCacheFile);                 // just get if changed

                // Build the tree from the local copy of the cache

                MetaFactoryNamespace.MetaTreeFactory.BuildFromCache(ClientDirs.CacheDir, false);

                return(Mfn.MetaTreeFactory.Nodes);
            }

            else
            {
                Mfn.MetaTreeFactory.Build();
                return(Mfn.MetaTreeFactory.Nodes);
            }
        }
示例#8
0
        /// <summary>
        /// Initialize the UAL and load the MetaData
        /// </summary>

        //public void Initialize()
        //{
        //  InitializeUAL();
        //  LoadMetaData();
        //  return;
        //}

        /// <summary>
        /// Initialize the UAL so basic Oracle operations can be performed
        /// </summary>

        public void InitializeUAL()
        {
            lock (_lockObject)
            {
                // Set the ini file

                if (ServicesIniFile.IniFile == null)
                {
                    string iniFilePath = GetMobiusServicesIniFileLocation();
                    Mobius.UAL.UalUtil.Initialize(iniFilePath);
                    if (!System.IO.File.Exists(iniFilePath))
                    {
                        throw new Exception("IniFile doesn't exist: " + iniFilePath);
                    }
                }

                if (ServicesDirs.MetaDataDir == "")
                {
                    ServicesDirs.MetaDataDir = ServicesIniFile.Read("MetaData");
                }

                string logFile = ServicesDirs.LogDir + @"\" + Mobius.ComOps.CommonConfigInfo.ServicesLogFileName; // log file name
                Mobius.Services.Util.ServicesLog.Initialize(logFile);                                             // initialize for logging

                // Get list of valid privileges

                Mobius.ComOps.PrivilegesMx.SetValidPrivilegeListFromInifile(ServicesIniFile.IniFile);

                // Load data source meta info

                if (Mobius.UAL.DataSourceMx.DataSources == null ||
                    Mobius.UAL.DataSourceMx.DataSources.Count == 0 ||
                    Mobius.UAL.DataSourceMx.Schemas == null ||
                    Mobius.UAL.DataSourceMx.Schemas.Count == 0)
                {
                    Mobius.UAL.DataSourceMx.LoadMetadata();
                }

                // Foundation dependency injections

                // Dependency injections for client components
                //Mobius.Data.Query.IDataTableManager = new DataTableManager();
                //Mobius.Data.ChemicalStructure.IChemicalStructureUtil = new Mobius.ClientComponents.ChemicalStructureUtil();
                //Mobius.Data.RootTable.IServerFile = new ServerFile();
                //Mobius.ServServiceFacade.ServiceFacade.IDebugLog = new DebugLogMediator();

                Mobius.Data.ResultsViewProps.ResultsViewFactory = new Mobius.ClientComponents.ViewFactory();
                Mobius.Data.Query.IDataTableManager             = new Mobius.ClientComponents.DataTableManager();
                Mobius.Data.CidList.ICidListDao        = new Mobius.UAL.CidListDao();
                Mobius.Data.MoleculeMx.IMoleculeMxUtil = new Mobius.QueryEngineLibrary.MoleculeUtil();
                Mobius.Data.RootTable.IServerFile      = new Mobius.UAL.ServerFile();

                Mobius.Data.InterfaceRefs.IUserObjectDao  = new Mobius.UAL.IUserObjectDaoMethods();
                Mobius.Data.InterfaceRefs.IUserObjectIUD  = new Mobius.ClientComponents.IUserObjectIUDMethods();
                Mobius.Data.InterfaceRefs.IUserObjectTree = new Mobius.ClientComponents.IUserObjectTreeMethods();

                Mobius.MolLib1.StructureConverter.ICdkUtil = new Mobius.CdkMx.CdkUtil();
            }
        }
示例#9
0
        /// <summary>
        /// GetDefaultWebPlayerUrl
        /// </summary>
        /// <returns></returns>

        static string GetDefaultWebPlayerUrl()
        {
            if (_defaultWebplayerUrl == null)
            {
                _defaultWebplayerUrl = ServicesIniFile.Read("SpotfireWebplayer", "https://[server]/spotfire/wp");
            }

            return(_defaultWebplayerUrl);
        }
示例#10
0
/// <summary>
/// Get server file name to export to
/// </summary>
/// <param name="rf"></param>
/// <param name="objId"></param>
/// <returns></returns>

        static string GetServerFileName(ResultsFormat rf, int objId)
        {
            string clientFile   = rf.OutputFileName;           // file name on client
            string ext          = Path.GetExtension(clientFile);
            string serverExpDir = ServicesIniFile.Read("BackgroundExportDirectory");
            string serverFile   = serverExpDir + @"\" + objId + ext;           // use background export userobject id & client file extension

            return(serverFile);
        }
示例#11
0
        /// <summary>
        /// Send mail object
        /// </summary>
        /// <param name="mail"></param>

        public static void SendEmail(
            MailMessage mail)
        {
            SmtpClient mailClient     = new SmtpClient();
            string     mailServerName = ServicesIniFile.Read("SmtpServer");

            mailClient.Host = mailServerName;
            mailClient.UseDefaultCredentials = true;
            //						mailClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
            mailClient.Send(mail);
        }
示例#12
0
        /// <summary>
        /// Main tool entry point
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>

        public string Run(
            string args)
        {
            QbUtil.SetMode(QueryMode.Build);             // be sure in build mode

            if (ServicesIniFile.Read("RgroupDecompositionHelpUrl") != "")
            {
                Help.Enabled = true;
            }

            this.ShowDialog();
            return("");
        }
示例#13
0
        /// <summary>
        /// Show NCBI Entre Gene web page for supplied geneId and/or symbol
        /// </summary>
        /// <param name="geneIdSymbol"></param>

        public static string GetTargetDescriptionUrl(
            string targetIdSymbol)
        {
            int    targetId;
            string targetSymbol;

            if (String.IsNullOrEmpty(targetIdSymbol))
            {
                return(null);
            }

            else if (Lex.IsInteger(targetIdSymbol))             // numeric gene id
            {
                targetId = int.Parse(targetIdSymbol);
            }

            else if (targetIdSymbol.Contains("-"))             // 1234-Symbol form
            {
                string[] sa = targetIdSymbol.Split('-');
                targetSymbol = sa[1].ToUpper();
                try { targetId = TargetSymbolToId(targetSymbol); }
                catch { return(null); }
            }

            else             // must be symbol
            {
                targetSymbol = targetIdSymbol.ToUpper();
                try { targetId = TargetSymbolToId(targetSymbol); }
                catch { return(null); }
            }

            if (targetId <= 0)
            {
                return(null);
            }

            string url = ServicesIniFile.Read("NcbiGeneIdUrlTemplate");

            if (String.IsNullOrEmpty(url))
            {
                return(null);
            }
            url = url.Replace("<GENE_ID>", targetId.ToString());
            return(url);
        }
示例#14
0
        /// <summary>
        /// Display any new news if requested
        /// </summary>

        public static bool ShowNewNews()
        {
            try
            {
                string lastNews = Preferences.Get("ShowNews");
                if (lastNews == "false")
                {
                    return(false);                                     // user doesn't want to see news
                }
                if (ClientState.IsDeveloper)
                {
                    return(false);                                         // debug
                }
                string fileName = ServicesIniFile.Read("NewsFile");
                if (fileName == "")
                {
                    throw new Exception("NewsFile not defined");
                }
                DateTime dt = File.GetLastWriteTime(fileName);

                string fileDate = String.Format("{0,4:0000}{1,2:00}{2,2:00}", dt.Year, dt.Month, dt.Day);

                if (String.Compare(fileDate, lastNews) > 0 || lastNews == "")
                {
                    ShowNews();                     // show the news
                    UserObjectDao.SetUserParameter(SS.I.UserName, "ShowNews", fileDate);
                    return(true);
                }

                else
                {
                    return(false);
                }
            }

            catch (Exception ex)
            {
                //if (ClientState.IsDeveloper)
                // MessageBoxMx.ShowError(ex.Message);
                return(false);
            }
        }
示例#15
0
        /// <summary>
        /// Some methods in the AlertQueue class are static.  Therefore the _alertQueueFileName will not be set in those cases.
        /// This method will ensure we have a valid file name in all cases.
        /// </summary>
        /// <returns></returns>
        private static string GetAlertQueueFileName()
        {
            if (_alertQueueFileName != null)
            {
                return(_alertQueueFileName);
            }

            if (_serverLogDir == null)
            {
                _serverLogDir = ServicesIniFile.Read("LogDirectory");
            }
            if (String.IsNullOrEmpty(_serverLogDir))
            {
                throw new Exception("Server LogDirectory not defined in config file");
            }

            if (_alertQueueFileName == null)
            {
                _alertQueueFileName = _serverLogDir + @"\AlertQueue.txt";
            }
            return(_alertQueueFileName);
        }
示例#16
0
        public static void Initialize()
        {
            MetaTableXmlFolder = ServicesDirs.MetaDataDir + @"\MetaTables";
            string rootFile = ServicesIniFile.Read("MetaTableRootFile", "Metatables.xml");             // root to start at

            if (rootFile.IndexOf(@"\") < 0)
            {
                rootFile = MetaTableXmlFolder + @"\" + rootFile;
            }

            IncludeQualifiedNumberDetailColumnsInMetaTables =             // get flag for including hidden Qualified Number detail cols in metatables
                                                              ServicesIniFile.ReadBool("IncludeQualifiedNumberDetailColumnsInMetaTables", true);

            BuildFromXmlFile(rootFile);             // get initial metatables

            RegisterFactory("CalcField", new CalcFieldMetaFactory());
            RegisterFactory("Annotation", new AnnotationMetaFactory());
            RegisterFactory("MultiTable", new MultiTableMetaFactory());
            RegisterFactory("Oracle", new OracleMetaFactory());
            RegisterFactory("PubChem", new PubChemMetaFactory());
            RegisterFactory("UnpivotedAssay", new UnpivotedAssayMetaFactory());
            RegisterFactory("SpotfireLink", new SpotfireLinkMetafactory());
        }
示例#17
0
        /// <summary>
        /// Display the news file
        /// </summary>

        public static void ShowNews()
        {
            try
            {
                string fileName = ServicesIniFile.Read("NewsFile");
                if (fileName == "")
                {
                    return;
                }

                if (Instance == null)
                {
                    Instance = new NewsDialog();
                }

                Instance.ShowNewsCheckBox.Checked = Preferences.GetBool("ShowNews");
                Instance.Show();
                Application.DoEvents();                 // allow form to draw before doing navigate
                Instance.WebBrowser.Navigate(fileName);
            }


            catch (Exception ex) { return; }
        }
示例#18
0
        public bool CanCreateTempTables = false;                            // true if the associated account can create temp tables

        /// <summary>
        /// Load metadata describing connections and associated schemas
        /// </summary>
        /// <param name="dsFileName"></param>
        /// <returns></returns>

        public static int LoadMetadata()
        {
            XmlAttributeCollection atts;

            // Get some inifile parameters first

            if (ServicesIniFile.IniFile == null)
            {
                throw new Exception("ServicesIniFile.IniFile is null");
            }

            SessionConnection.Pooling            = ServicesIniFile.ReadBool("Pooling", true);
            SessionConnection.MinPoolSize        = ServicesIniFile.ReadInt("MinPoolSize", 1);
            SessionConnection.IncrPoolSize       = ServicesIniFile.ReadInt("IncrPoolSize", 5);
            SessionConnection.MaxPoolSize        = ServicesIniFile.ReadInt("MaxPoolSize", 100);
            SessionConnection.DecrPoolSize       = ServicesIniFile.ReadInt("DecrPoolSize", 1);
            SessionConnection.ConnectionLifetime = ServicesIniFile.ReadInt("ConnectionLifetime", 0);

            string tok     = ServicesIniFile.Read("KeyListPredType", "Parameterized");
            int    enumInt = EnumUtil.Parse(typeof(KeyListPredTypeEnum), tok);

            if (enumInt >= 0)
            {
                DbCommandMx.DefaultKeyListPredType = (KeyListPredTypeEnum)enumInt;
            }

            DbCommandMx.DbFetchRowCount = ServicesIniFile.ReadInt("DbFetchRowCount", DbCommandMx.DbFetchRowCount);
            DbCommandMx.DbFetchSizeMax  = ServicesIniFile.ReadInt("DbFetchSizeMax", DbCommandMx.DbFetchSizeMax);

            DataSources = new Dictionary <string, DataSourceMx>(StringComparer.OrdinalIgnoreCase);
            Schemas     = new Dictionary <string, DbSchemaMx>(StringComparer.OrdinalIgnoreCase);

            string dsFileName = ServicesDirs.MetaDataDir + @"\" + "DataSources.xml";

            StreamReader sr  = new StreamReader(dsFileName);
            XmlDocument  doc = new XmlDocument();

            doc.Load(sr);
            XmlNode node = doc.FirstChild;

            while (node != null)
            {
                if (node.NodeType == XmlNodeType.Element)
                {
                    break;
                }
                node = node.NextSibling;
                if (node == null)
                {
                    throw new Exception("No initial element found");
                }
            }

            if (!Lex.Eq(node.Name, "DataSources"))
            {
                throw new Exception("Expected DataSources node: " + node.Name);
            }

            atts = node.Attributes;             // datasources attributes
            for (int i = 0; i < atts.Count; i++)
            {
                XmlNode att = atts.Item(i);

                if (Lex.Eq(att.Name, "DblinkConnName"))
                {
                }                                                           // obsolete key word

                else
                {
                    throw new Exception
                              ("Unexpected DataSources attribute: " + att.Name);
                }
            }

            node = node.FirstChild;
            while (node != null)
            {
                if (node.NodeType != XmlNodeType.Element)
                {
                    ;                                                       // ignore non-elements
                }
                else if (Lex.Eq(node.Name, "DataSource") ||                 // connection element
                         Lex.Eq(node.Name, "Connection"))
                {
                    DataSourceMx cd = new DataSourceMx();

                    atts = node.Attributes;
                    for (int i = 0; i < atts.Count; i++)
                    {
                        XmlNode att = atts.Item(i);

                        if (Lex.Eq(att.Name, "DatabaseType") || Lex.Eq(att.Name, "DbType"))
                        {
                            if (!Enum.TryParse <DatabaseType>(att.Value, true, out cd.DbType))
                            {
                                throw new Exception("Invalid Database type: " + att.Value);
                            }
                        }

                        else if (Lex.Eq(att.Name, "Name"))
                        {
                            cd.DataSourceName = att.Value.ToUpper().Trim();
                        }

                        else if (Lex.Eq(att.Name, "DatabaseName") || Lex.Eq(att.Name, "OracleName"))
                        {
                            cd.DatabaseLocator = att.Value.ToUpper().Trim();
                        }

                        else if (Lex.Eq(att.Name, "ConnectionString"))                         // keep case if connection string
                        {
                            cd.DatabaseLocator = att.Value.Trim();
                        }

                        else if (Lex.Eq(att.Name, "UserName"))
                        {
                            cd.UserName = att.Value.Trim();                             // keep case as is (Oracle 11g)
                        }
                        else if (Lex.Eq(att.Name, "Password"))
                        {
                            cd.Password = att.Value.Trim();                           // keep case as is (Oracle 11g)
                        }
                        else if (Lex.Eq(att.Name, "MdlInit"))                         // mdl initialization
                        {
                            cd.InitCommand = "select cdcaux.ctenvinit('" + att.Value.Trim() + "') from dual";
                        }

                        else if (Lex.Eq(att.Name, "InitCommand"))
                        {
                            cd.InitCommand = att.Value.Trim();
                        }

                        else if (Lex.Eq(att.Name, "KeyDataSource"))
                        {
                            bool.TryParse(att.Value.Trim(), out cd.IsKeyDataSource);
                        }

                        else if (Lex.Eq(att.Name, "CanCreateTempTables"))
                        {
                            bool.TryParse(att.Value.Trim(), out cd.CanCreateTempTables);
                        }

                        else if (Lex.Eq(att.Name, "AlwaysUseDbLink"))
                        {
                        }                                                                         // obsolete

                        else
                        {
                            throw new Exception
                                      ("Unexpected Connection attribute: " + att.Name);
                        }
                    }

                    if (cd.DataSourceName == "")
                    {
                        DebugLog.Message("Connection is missing name: " + cd.DatabaseLocator);
                    }
                    else if (DataSourceMx.DataSources.ContainsKey(cd.DataSourceName))
                    {
                        DebugLog.Message("Data source defined twice: " + cd.DataSourceName);
                    }
                    else
                    {
                        DataSourceMx.DataSources.Add(cd.DataSourceName, cd);
                    }
                }

                else if (Lex.Eq(node.Name, "SchemaToDataSource") ||                 // schema map element
                         Lex.Eq(node.Name, "SchemaToConnection"))
                {
                    DbSchemaMx schema = new DbSchemaMx();
                    atts = node.Attributes;
                    for (int i = 0; i < atts.Count; i++)
                    {
                        XmlNode att = atts.Item(i);

                        if (Lex.Eq(att.Name, "Schema"))
                        {
                            schema.Name = att.Value.ToUpper().Trim();
                        }

                        else if (Lex.Eq(att.Name, "AliasFor"))
                        {
                            schema.AliasFor = att.Value.ToUpper().Trim();
                        }

                        else if (Lex.Eq(att.Name, "Connection"))
                        {
                            schema.DataSourceName = att.Value.ToUpper().Trim();
                        }

                        else if (Lex.Eq(att.Name, "Label") || Lex.Eq(att.Name, "L"))
                        {
                            schema.Label = att.Value.Trim();
                        }

                        else
                        {
                            throw new Exception
                                      ("Unexpected Connection attribute: " + att.Name);
                        }
                    }

                    if (schema.Name == "")
                    {
                        throw new Exception("Missing schema name");
                    }
                    if (schema.DataSourceName == "")
                    {
                        throw new Exception("Missing data source/connection name");
                    }
                    Schemas[schema.Name] = schema;
                }

                else
                {
                    throw new Exception("Expected Connection or SchemaToDataSource element but saw " +
                                        node.Name);
                }

                node = node.NextSibling;
            }
            sr.Close();

            return(DataSources.Count);
        }
示例#19
0
        /// <summary>
        /// Thread to check to see if any imports need to started
        /// </summary>

        public void CheckForImportFileUpdatesThreadMethod(Object CheckAll)
        {
            // Check each ImportState user object for the user to see if any imports need to be started.
            // If any are found then start a new hidden Mobius client & server to upload the file(s)
            // and start an import user data process for each one.

            UserDataImportState udis;

            List <UserObject> imps = new List <UserObject>();
            UserCmpndDbDao    udbs = new UserCmpndDbDao();

            int t0 = TimeOfDay.Milliseconds();

            bool checkAllImportFiles = (bool)CheckAll;

            if (checkAllImportFiles)
            {
                imps = UserObjectDao.ReadMultiple(UserObjectType.ImportState, false);
            }
            else
            {
                imps = UserObjectDao.ReadMultiple(UserObjectType.ImportState, SS.I.UserName, false, false);
            }

            int t1 = TimeOfDay.Milliseconds() - t0;

            if (imps.Count == 0)
            {
                return;
            }
            //			return ""; // debug

            int i1 = 0;

            while (i1 < imps.Count)
            {             // pare list down do those needing updating
                UserObject uo = imps[i1];

                try { udis = UserDataImportState.Deserialize(uo); }
                catch (Exception ex)
                {
                    imps.RemoveAt(i1);
                    continue;
                }

                if (udis.CheckForFileUpdates && ((checkAllImportFiles == true && udis.ClientFile.Substring(0, 1) == "\\" && FileUtil.Exists(udis.ClientFile)) || checkAllImportFiles == false))
                {
                    DateTime clientFileModDt = FileUtil.GetFileLastWriteTime(udis.ClientFile); // get client file mod date

                    if (clientFileModDt == DateTime.MinValue ||                                // skip if client file not found or
                        udis.ImportIsRunning ||                                                // import is already running
                        ((clientFileModDt - udis.ClientFileModified).TotalSeconds < 1 &&       // no change in client file mod date and
                         !udis.ImportHasFailed))                                               // prev load attempt hasn't failed
                    {
                        imps.RemoveAt(i1);
                        continue;
                    }

                    udis.ClientFileModified = clientFileModDt;                     // write the updated file date
                    uo.Description          = udis.Serialize();
                    UserObjectDao.Write(uo);
                }

                else                          // running or failed manual background import
                {
                    if (udis.ImportHasFailed) // delete if failed
                    {
                        bool deleted = UserObjectDao.Delete(udis.Id);
                        udbs.LogMessage("Deleted ImportState object for failed manual background import on " + uo.Name);
                    }

                    imps.RemoveAt(i1);                     // don't consider further here
                    continue;
                }

                i1++;
            }

            //write a debug message and return
            udbs.LogMessage(string.Format("Found {0} annotation files that could be updated by the {1} account", imps.Count, SS.I.UserName));

            int t2 = TimeOfDay.Milliseconds() - t0;

            if (imps.Count == 0)
            {
                return;
            }

            // Upload the file to the server and start a background process to update the annotation table

            foreach (UserObject uo2 in imps)
            {
                try
                {
                    udis = UserDataImportState.Deserialize(uo2);
                    string internalUoName = "Annotation_" + uo2.Id;
                    string exportDir      = ServicesIniFile.Read("BackgroundExportDirectory");
                    string serverFileName =                     // location for file on server
                                            exportDir + @"\" + internalUoName + Path.GetExtension(udis.FileName);
                    ServerFile.CopyToServer(udis.FileName, serverFileName);
                    string command = "ImportUserData " + serverFileName + ", " + internalUoName;
                    CommandLine.StartBackgroundSession("ImportUserData " + serverFileName + ", " + uo2.Name);
                    udbs.LogMessage("Auto-upload for ImportState ObjId = " + ", " + uo2.Id + ", Name = " + uo2.Name + ", Desc = " + uo2.Description);
                }

                catch (Exception ex)
                {
                    try
                    {
                        udbs.LogMessage("Auto-upload exception ImportState ObjId = " + uo2.Id + ", Name = " + uo2.Name +
                                        ", Desc = " + uo2.Description +
                                        "\n" + DebugLog.FormatExceptionMessage(ex));
                    }

                    catch (Exception ex2) { ex2 = ex2; }

                    continue;
                }
            }

            Progress.Hide();

            int t3 = TimeOfDay.Milliseconds() - t0;

            return;
        }
示例#20
0
/// <summary>
/// Method to run query in background and save the results for later retrieval
/// </summary>
/// <param name="q"></param>
/// <param name="emailSubject">Send email if defined</param>
/// <param name="templateName"></param>
/// <returns></returns>

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

            bool notifyUserByEmail = !Lex.IsNullOrEmpty(emailSubject);

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

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

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

                return(msg);
            }

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

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

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

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

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

            return(msg);
        }
示例#21
0
/// <summary>
/// Get image & coordinates file from KEGG FTP
/// </summary>
/// <param name="pathwayId"></param>
/// <returns></returns>

        public static TargetMap GetKeggPathway(
            string pathwayId)
        {
            String ftpPath, rec;

            if (TargetMapDict == null)
            {
                ReadTargetMapDict();
            }

            TargetMap tm = new TargetMap();

            tm.Name   = pathwayId;
            tm.Label  = pathwayId;            // default label
            tm.Source = "KEGG";
            tm.Type   = "Pathway";

// Build basic paths

            string ftpFolder = ServicesIniFile.Read("KeggPathWayFtpDirectory");             // get from here

            if (String.IsNullOrEmpty(ftpFolder))
            {
                throw new Exception("KeggPathWayFtpDirectory not defined");
            }
            if (!ftpFolder.EndsWith(@"/"))
            {
                ftpFolder += @"/";
            }

// Get map_title file and read title for pathway

            string filePath      = TargetMapDir + @"\map_title.tab";
            string pathwayPrefix = pathwayId.Substring(0, 3);
            string pathwayNbr    = pathwayId.Substring(3);          //
            bool   download      = false;

            if (!File.Exists(filePath))
            {
                download = true;
            }

            while (true)
            {
                if (download)
                {
                    ftpPath = ftpFolder + "map_title.tab";
                    Download(ftpPath, filePath);
                }

                StreamReader sr = new StreamReader(filePath);
                while (true)
                {
                    rec = sr.ReadLine();
                    if (rec == null)
                    {
                        break;
                    }
                    if (!rec.StartsWith(pathwayNbr))
                    {
                        continue;
                    }
                    string[] sa = rec.Split('\t');
                    tm.Label = sa[1].Trim() + " (KEGG: " + pathwayId + ")";
                    break;
                }
                sr.Close();

                if (!String.IsNullOrEmpty(tm.Label))
                {
                    break;                         // have it
                }
                else if (download)                 // already downloaded but not found
                {
                    tm.Label = pathwayId;
                    break;
                }

                else
                {                 // download again if not done yet
                    download = true;
                    continue;
                }
            }

// Get gif file

            if (Lex.Ne(pathwayPrefix, "map"))             // if not a base level map then in organisms
            {
                ftpFolder += @"organisms/";
            }
            ftpFolder += pathwayPrefix + @"/";

            ftpPath  = ftpFolder + pathwayId + ".gif";
            filePath = TargetMapDir + @"\" + pathwayId + ".gif";
            Download(ftpPath, filePath);

            Image img = Image.FromFile(filePath);

            tm.Bounds     = new Rectangle(0, 0, img.Width, img.Height);
            tm.MarkBounds = true;

            filePath = TargetMapDir + @"\" + pathwayId + ".png";             // save as .png file that Spotfire can read
            img.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
            tm.ImageType = "png";
            tm.ImageFile = Path.GetFileName(filePath);             // store just file name

// Get coordinates file

            if (Lex.Eq(pathwayPrefix, "map"))
            {
                ftpPath  = ftpFolder + pathwayId + "_ec.coord";
                filePath = TargetMapDir + @"\" + pathwayId + "_ec.coord";
            }
            else
            {
                ftpPath  = ftpFolder + pathwayId + "_gene.coord";
                filePath = TargetMapDir + @"\" + pathwayId + "_gene.coord";
            }
            Download(ftpPath, filePath);
            tm.CoordsFile = Path.GetFileName(filePath);

            TargetMapDict[tm.Name.ToUpper()]         = tm;     // add to list of maps
            TargetMapDictByLabel[tm.Label.ToUpper()] = tm;

            GetMapWithCoords(pathwayId);             // read in coords to validate file format

// Write out the map file containing basic map data

            filePath = TargetMapDir + @"\" + pathwayId + ".map";
            StreamWriter sw = new StreamWriter(filePath);

            rec =
                tm.Name + "\t" +
                tm.Label + "\t" +
                tm.Source + "\t" +
                tm.Type + "\t" +
                tm.ImageType + "\t" +
                tm.ImageFile + "\t" +
                tm.Bounds.Left + "\t" +
                tm.Bounds.Top + "\t" +
                tm.Bounds.Right + "\t" +
                tm.Bounds.Bottom + "\t" +
                tm.MarkBounds + "\t" +
                tm.CoordsFile;

            sw.WriteLine(rec);
            sw.Close();

            return(tm);
        }
示例#22
0
        /// <summary>
        /// Return description for table.
        /// May be html or simple text
        /// </summary>
        /// <param name="mt"></param>
        /// <returns></returns>

        public static TableDescription GetTableDescription(
            MetaTable mt)
        {
            DateTime dt;
            bool     firstRow;
            double   d1;
            int      assayId, i1;
            string   geneSymbol, geneId, geneLinkUrl = "", html = "", url, txt;

            TableDescription td = new TableDescription();

            try
            {
                string       templateFile = CommonConfigInfo.MiscConfigDir + @"<templateName>";
                StreamReader sr           = new StreamReader(templateFile);
                html = sr.ReadToEnd();
                sr.Close();
            }
            catch (Exception ex)
            {
                td.TextDescription = "Error: " + ex.Message;
                return(td);
            }

            try
            { geneLinkUrl = ServicesIniFile.Read("LsgEntrezGeneUrlTemplate"); }
            catch (Exception ex) { }

            try { assayId = Convert.ToInt32(mt.Code); }
            catch (Exception ex) { return(null); }

            AssayDbMetadata assay = AssayMetadataDao.GetAssayTargetGeneData(assayId);             // get biological target(s) & gene(s) for assay

            string btStr = "";
            string gsStr = "";

            List <AssayDbTarget> targets = assay.Targets;

            foreach (AssayDbTarget target in assay.Targets)
            {
                string bt = target.TargetName;
                if (bt == "")
                {
                    continue;
                }

                bt += "<Target_Link>";
                if (target.TargetDesc != "")
                {
                    bt += " - " + target.TargetDesc;
                }

                if (btStr.IndexOf(bt) < 0)                 // new bio target
                {
                    if (gsStr != "")
                    {
                        gsStr = " (" + gsStr + ")";
                    }
                    btStr  = btStr.Replace("<Target_Link>", gsStr);
                    gsStr  = "";
                    btStr += "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                             bt;
                }

                if (target.Genes != null && target.Genes.Count > 0)
                {                                       // add link to gene if appropriate
                    AssayDbGene gene = target.Genes[0]; // just first gene for now
                    geneSymbol = gene.GeneSymbol;
                    geneId     = gene.GeneId;

                    geneLinkUrl =
                        "http:////Mobius/command?ShowContextMenu:TargetContextMenu(<Gene_Link>)";

                    if (!String.IsNullOrEmpty(geneLinkUrl))
                    {                     // include link to gene description
                        if (Lex.IsDefined(geneId))
                        {
                            url = geneLinkUrl.Replace("<Gene_Link>", geneId);                             // link on gene id
                        }
                        else
                        {
                            url = geneLinkUrl.Replace("<Gene_Link>", gene.GeneSymbol); // link on symbol
                        }
                        geneSymbol =                                                   // define tag to open in new window
                                     "<a href=\"" + url + "\">" + geneSymbol + "</a>";
                    }

                    if (gsStr != "")
                    {
                        gsStr += ", ";                                  // same bt additional gene
                    }
                    gsStr += geneSymbol;
                }
            }

            if (gsStr != "")
            {
                gsStr = " (" + gsStr + ")";
            }
            btStr = btStr.Replace("<Target_Link>", gsStr);             // plug in last gene symbol

            html = html.Replace("blgcl_trgt_text", btStr);

            // Method type & descriptors

            string methodDescrSql = @"
				SELECT <columns>
        FROM <tables>  
        WHERE <criteria>
        ORDER BY LOWER(<orderCols>)";

            DbCommandMx drd = new DbCommandMx();

            drd.PrepareParameterized(methodDescrSql, DbType.Int32);

            assayId = Convert.ToInt32(mt.Code);
            drd.ExecuteReader(assayId);

            string mdStr = "";

            firstRow = true;
            while (true)
            {
                if (!drd.Read())
                {
                    break;
                }
                if (firstRow)                 // get single assay parameters
                {
                    firstRow = false;
                }

                string mdtn = "<methodTypeName>";
                if (mdtn == "")
                {
                    continue;
                }
                string bmdn  = drd.GetStringByName("<methodDescriptionColumn>");
                string bmddt = drd.GetStringByName("<methodDescriptionColumn2>");
                mdtn = "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                       mdtn + ": " + bmdn;
                if (bmddt != "" && bmdn.ToLower().IndexOf(bmddt.ToLower()) < 0)                 // include any description if don't already have
                {
                    mdtn += " - " + bmddt;
                }
                mdStr += mdtn;
            }

            html = html.Replace("<methodDescriptionPlaceHolder>", mdStr);

            // Get Minimum Significant Results information

            string msrSql = @"
			SELECT <columns>
				FROM <tables>
				WHERE <conditions>"                ;

            // RDM MSR Sql (obsolete)

            string msrSqlRdm = @"<todo>";

            drd.PrepareParameterized(msrSql, DbType.Int32);

            assayId = Convert.ToInt32(mt.Code);
            drd.ExecuteReader(assayId);

            while (true)
            {
                if (!drd.Read())
                {
                    break;                              // should always get at least one row even if no MSR data
                }
            }

            // Pharmacological action

            // <todo>

            // Research effort & therapeutic target

            // <todo>

            // Biological Conditions

            // <todo>
            // All done

            drd.Dispose();

            td.TextDescription = html;
            return(td);
        }
示例#23
0
        TextReader GetAssayXml(
            string aid)
        {
            TextReader  rdr = null;
            DbCommandMx dao = null;
            string      xml;

// Try to get from file first

            if (PubChemAssayDirectory == null)
            {
                PubChemAssayDirectory = ServicesIniFile.Read("PubChemAssayDirectory");
            }
            if (PubChemAssayDirectory != "")
            {
                try
                {
                    string       fileName = PubChemAssayDirectory + @"\CSV\Description\" + aid + ".descr.xml";
                    StreamReader sr       = new StreamReader(fileName);
                    xml = sr.ReadToEnd();
                    sr.Close();
                    if (String.IsNullOrEmpty(xml))
                    {
                        return(null);
                    }
                    return(new StringReader(xml));
                }
                catch (Exception ex) { }
            }

// Try to get from table (new method)

            string sql =
                "select xml " +
                "from mbs_owner.mbs_pbchm_assy_xml " +
                "where aid = :0";

            try
            {
                dao = new DbCommandMx();
                dao.PrepareParameterized(sql, DbType.String);
                dao.ExecuteReader(aid);
                if (!dao.Read())
                {
                    throw new Exception("Not found");
                }
                xml = dao.GetString(0);
                dao.Dispose();
            }
            catch (Exception ex)
            {
                dao.Dispose();
                return(null);
            }

            if (String.IsNullOrEmpty(xml))
            {
                return(null);
            }
            return(new StringReader(xml));
        }
示例#24
0
        /// <summary>
        /// Get a SharePoint open or save file name
        /// </summary>
        /// <param name="action">1=open, 2=save</param>
        /// <param name="title">Dialog title</param>
        /// <param name="initialFile">Initial file name.
        /// If no filename is supplied upon entry then the "SharePointSiteUrl"
        /// parameter is used as the initial folder. If this is not defined then
        /// "DefaultSharePointSiteUrl" .ini file setting is used. Examples:
        /// </param>
        /// <param name="filter">Filter string, e.g. "Lists (*.lst)|*.lst" </param>
        /// <param name="defaultExt">Default file extension</param>
        /// <returns></returns>

        private static string GetFilename(
            int action,
            string title,
            string initialFile,
            string filter,
            string defaultExt)
        {
            string dir = "", fileName = "", lastSite = "";
            object gfo = null;

            try
            {
                if (!Lex.IsNullOrEmpty(defaultExt) && !defaultExt.StartsWith("."))
                {
                    defaultExt = '.' + defaultExt;
                }

                try { dir = IO.Path.GetDirectoryName(initialFile); } catch { } // get any directory name
                if (Lex.IsNullOrEmpty(dir))                                    // if no directory specified get user's preferred SharePoint folder
                {
                    lastSite = Preferences.Get("SharePointSiteUrl");
                    if (lastSite == "")
                    {
                        lastSite = ServicesIniFile.Read("DefaultSharePointSiteUrl");
                        lastSite = Lex.Replace(lastSite, "<UserName>", SS.I.UserName);
                    }

                    if (Lex.StartsWith(lastSite, "http://spotfire"))                     // convert incorrect URL to proper UNC
                    {
                        lastSite = Lex.Replace(lastSite, "http://spotfire", @"\\spotfire");
                        lastSite = Lex.Replace(lastSite, "/", @"\");
                    }

                    if (lastSite != "")                     // plug into initial file
                    {
                        initialFile = lastSite;
                        if (Lex.StartsWith(initialFile, "http") && !initialFile.EndsWith(@"\") && !initialFile.EndsWith("/"))
                        {
                            initialFile += "/";                             // be sure we have final slash if URL
                        }
                        else if (Lex.StartsWith(initialFile, @"\\"))
                        {
                            if (!initialFile.EndsWith(@"\") && !initialFile.EndsWith("/"))
                            {
                                initialFile += @"\";                         // be sure we have final slash if URL
                            }
                            initialFile += "*" + defaultExt;                 // need extension to get files listed for a UNC
                        }
                    }
                }

                if (Lex.StartsWith(initialFile, "http"))                 // replace any back slashes with forward slashes if http
                {
                    initialFile = initialFile.Replace(@"\", @"/");
                }

                filter = filter.Replace("|", ","); // use proper filter delimiter for Office dialogs

                if (action == 1)                   // Open dialog
                {
                    fileName = ShowOfficeOpenFileDialog(initialFile, filter, defaultExt, title);
                }

                else                 // SaveAs Dialog
                {
                    fileName = ShowOfficeSaveAsFileDialog(initialFile, filter, defaultExt, title);
                }

                if (Lex.StartsWith(fileName, "http") || Lex.StartsWith(fileName, @"\\"))                 // if filename is a URL or UNC update default SharePoint folder
                {
                    try
                    {
                        string dirPath = IO.Path.GetDirectoryName(fileName);
                        if (dirPath != "" && Lex.Ne(dirPath, lastSite))
                        {
                            Preferences.Set("SharePointSiteUrl", dirPath);
                            lastSite = dirPath;
                        }
                    }
                    catch { }
                }

                return(fileName);
            }

            catch (Exception ex)
            {
                return("");
            }
        }
示例#25
0
        /// <summary>
        /// Setup the form
        /// </summary>
        /// <param name="alert"></param>

        void Setup(
            Alert alert,
            UserObject quo)
        {
            Alert          = alert;
            QueryUo        = quo;
            QueryName.Text = alert.QueryName;

            if (alert.Id == 0)             // if new alert default to Daily Control
            {
                radioButtonDaily.Checked = true;
            }
            dateTimePicker1.Text = alert.StartTime.ToShortTimeString();

            SetControlData(alert);

            var txt = alert.MailTo;

            if (txt == "")
            {
                txt = SS.I.UserInfo.EmailAddress;
            }
            Recipients.Text = txt;

            if (alert.CheckTablesWithCriteriaOnly)
            {
                CheckTablesWithCriteriaOnly.Checked = true;
            }
            else
            {
                CheckAllTables.Checked = true;
            }

            ExportParms = Alert.ExportParms;             // store ref for later access
            string exportFileFormat = "None";

            if (alert.ExportParms != null)
            {
                if (alert.ExportParms.TextFile)
                {
                    exportFileFormat = "CSV / Text File";
                }
                else if (alert.ExportParms.Excel)
                {
                    exportFileFormat = "Excel Worksheet";
                }
                else if (alert.ExportParms.Word)
                {
                    exportFileFormat = "MS Word Table";
                }
                else if (alert.ExportParms.SdFile)
                {
                    exportFileFormat = "SDFile";
                }
                else if (alert.ExportParms.Grid)
                {
                    exportFileFormat = "Mobius - Results displayed when query is opened";
                }
            }
            ExportFileFormat.Text = exportFileFormat;

            HighlightChangedCompounds.Checked = alert.HighlightChangedCompounds;

            if (!alert.CheckTablesWithCriteriaOnly ||             // show expanded window if expanded option selected
                alert.ExportParms != null)
            {
                ExpandWindow();
            }

            RunNow.Checked = false;

            if (ServicesIniFile.Read("AlertHelpUrl") != "")
            {
                Help.Enabled = true;
            }
        }
示例#26
0
        /// <summary>
        /// Edit a new or existing calculated field
        /// </summary>
        /// <param name="cf"></param>
        /// <param name="uoIn"></param>
        /// <returns></returns>

        public static UserObject Edit(
            CalcField cf,
            UserObject uoIn)
        {
            QueryTable qt;
            MetaTable  mt = null;
            MetaColumn mc, field;
            UserObject uo2;
            CalcField  cf2 = null;
            string     msg;
            int        i1;

            CalcFieldEditor lastInstance = Instance;

            CalcFieldEditor i = Instance = new CalcFieldEditor();

            i.AdvancedPanel.BorderStyle = BorderStyle.None;
            i.AdvancedPanel.Visible     = false;
            i.AdvancedPanel.Dock        = DockStyle.Fill;

            i.BasicPanel.BorderStyle = BorderStyle.None;
            i.BasicPanel.Visible     = true;
            i.BasicPanel.Dock        = DockStyle.Fill;
            i.SetupStandardCalculatedFields();
            if (ServicesIniFile.Read("CalcFieldHelpUrl") != "")
            {
                i.Help.Enabled = true;
            }

            if (lastInstance != null)
            {
                i.StartPosition = FormStartPosition.Manual;
                i.Location      = lastInstance.Location;
                i.Size          = lastInstance.Size;
                lastInstance    = null;
            }

            if (uoIn == null)
            {
                uoIn = new UserObject(UserObjectType.CalcField);
            }

            else if (uoIn.Id > 0)             // get existing metatable for calc field for exclusion in BuildQuickSelectTableMenu
            {
                string tName = "CALCFIELD_" + uoIn.Id.ToString();
                mt = MetaTableCollection.GetExisting(tName);
                if (MainMenuControl != null)
                {
                    MainMenuControl.UpdateMruList(tName);
                }
            }

            Instance.UoIn = uoIn;

            string title = "Edit Calculated Field";

            if (!String.IsNullOrEmpty(uoIn.Name))
            {
                title += " - " + uoIn.Name;
            }
            Instance.Text = title;

            Instance.CalcField = cf;          // what we're editing
            Instance.SetupForm();             // set up the form

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

            if (dr == DialogResult.Cancel)
            {
                return(null);
            }

            return(Instance.UoIn);            // return saved object
        }
示例#27
0
/// <summary>
/// Setup the form
/// </summary>
/// <param name="query"></param>
/// <param name="optionPage"></param>
/// <param name="ti"></param>

        void Setup(
            Query query,
            string optionPage,
            ref int ti)
        {
            QueryTable  qt;
            QueryColumn qc;
            MetaTable   mt;
            string      txt;
            int         i1, i2;

            Query = query;

            string formCaption = "Query Options";

            if (Security.IsAdministrator(Security.UserName) && query.UserObject.Id > 0)
            {
                formCaption += " (Query Id: " + query.UserObject.Id + ")";
            }
            Text = formCaption;

            int tpi = -1;

            if (optionPage == "SumPos")
            {
                tpi = 0;
            }
            else if (optionPage == "Alert")
            {
                tpi = 1;
            }
            else if (optionPage == "Misc")
            {
                tpi = 1;
            }
            else if (optionPage == "Advanced")
            {
                tpi = 2;
            }

            if (tpi >= 0)
            {
                Tabs.SelectedTabPageIndex = tpi;                       // goto any specified page, otherwise stay where we were last time
            }
            // Setup general tab

            txt = SS.I.DefaultNumberFormat.ToString() + " (" + SS.I.DefaultDecimals.ToString() + ")";
            DefaultNumberFormat.Text = txt;

            txt = QbUtil.ConvertStatDisplayFormat(query.StatDisplayFormat);
            QnfStatsTextEdit.Text = txt;

            SetAlertText(query);

            TableColumnZoom.ZoomPct    = SS.I.TableColumnZoom;                  // Setup zoom controls
            GraphicsColumnZoom.ZoomPct = SS.I.GraphicsColumnZoom;

// Advanced options - query specific

            DuplicateKeyValues.Checked   = query.DuplicateKeyValues;
            FilterNullRows.Checked       = query.FilterNullRows;
            ShowCondFormatLabels.Checked = query.ShowCondFormatLabels;
            //BrowseExistingResultsWhenOpened.Checked = query.BrowseExistingResultsWhenOpened;
            RunQueryWhenOpened.Checked = query.RunQueryWhenOpened;
            //UseCachedData.Checked = query.UseCachedData;
            CombineSearchAndRetrieval.Checked = query.SingleStepExecution;
            Multitable.Checked  = query.Multitable;            // (not visible)
            MobileQuery.Checked = query.Mobile;


// Advanced options - applies to all queries

            RepeatReport.Checked               = SS.I.RepeatReport;
            ShowStereoComments.Checked         = SS.I.ShowStereoComments;
            BreakHtmlPopupsAtPageWidth.Checked = SS.I.BreakHtmlPopupsAtPageWidth;
            RestoreWindowsAtStartup.Checked    = SS.I.RestoreWindowsAtStartup;

            HilightCorpIdChanges.Checked       = SS.I.HilightCidChanges;
            RemoveLeadingZerosFromCids.Checked = SS.I.RemoveLeadingZerosFromCids;
            MarkCheckBoxesInitially.Checked    = SS.I.GridMarkCheckBoxesInitially;

            EvenRowBackgroundColor.Color = SS.I.EvenRowBackgroundColor;
            OddRowBackgroundColor.Color  = SS.I.OddRowBackgroundColor;

            DnfMc            = new MetaColumn();  // setup to get new number format info
            DnfMc.DataType   = MetaColumnType.QualifiedNo;
            DnfMc.Format     = SS.I.DefaultNumberFormat;
            DnfMc.Decimals   = SS.I.DefaultDecimals;
            DnfQc            = new QueryColumn();
            DnfQc.MetaColumn = DnfMc;

            DefaultToSingleStepQueryExecution.Checked = MqlUtil.DefaultToSingleStepQueryExecution;

            // Setup summarization / table position tab

            CustomSummarization.Visible = Aggregator.IsAvailableForUser;

            DataTable dt = CreateDataTable();

            OriginalQueryTables = new Dictionary <string, QueryTable>();            // keep set of original tables
            for (i1 = 0; i1 < query.Tables.Count; i1++)
            {
                qt = query.Tables[i1];
                mt = qt.MetaTable;

                object cs;
                if (mt.SummarizedExists)
                {
                    if (qt.MetaTable.UseSummarizedData)
                    {
                        cs = true;
                    }
                    else
                    {
                        cs = false;
                    }
                }
                else
                {
                    cs = DBNull.Value;
                }

                string tableLabel = qt.ActiveLabel;
                while (OriginalQueryTables.ContainsKey(tableLabel))
                {
                    tableLabel += ".";                                   // avoid unlikely but possible dup name
                }
                OriginalQueryTables.Add(tableLabel, qt);                 // accumulate original labels

                int selectCount = 0, criteriaCount = 0;
                for (i2 = 0; i2 < qt.QueryColumns.Count; i2++)
                {
                    qc = qt.QueryColumns[i2];
                    if (qc.Selected)
                    {
                        selectCount++;
                    }
                    if (qc.Criteria != "")
                    {
                        criteriaCount++;
                    }
                }
                txt = selectCount.ToString() + "/" +
                      qt.QueryColumns.Count.ToString() + ", " + criteriaCount.ToString();

                DataRow dr = DataTable.NewRow();
                dr["SummarizedCol"] = cs;
                dr["TableNameCol"]  = tableLabel;
                dr["SelectedFieldsAndCriteriaCountsCol"] = txt;
                DataTable.Rows.Add(dr);
            }

            TableGrid.DataSource = DataTable;

            if (ti >= 0 && ti < query.Tables.Count)
            {
                SelectRow(ti);
            }

            if (ServicesIniFile.Read("QueryOptionsHelpUrl") != "")
            {
                Help.Enabled = true;
            }

            EditAlertOnOpen = Lex.Eq(optionPage, "Alert");

            return;
        }