Ejemplo n.º 1
0
        /// <summary>
        /// Assign any new label for metatable
        /// </summary>
        /// <param name="mt"></param>

        public static void SetAnyNewMetaTableLabel(
            MetaTable mt)
        {
            DictionaryMx newDict = DictionaryMx.Get("NewNameDict");

            if (newDict == null)
            {
                return;
            }
            string newLabel = newDict.LookupDefinition(mt.Name);

            if (newLabel == null)
            {
                return;
            }

            DictionaryMx originalDict = DictionaryMx.Get("OriginalNameDict");

            if (originalDict == null)
            {
                return;
            }
            originalDict.Add(mt.Name, mt.Label);             // save original label
            mt.Label = newLabel;
        }
Ejemplo n.º 2
0
        static DictionaryMx ReadDictionary(
            DictionaryMx dict)
        {
            if (!dict.Cache)
            {
                return(ReadDictionaryFromOracle(dict));                         // normal read from Oracle
            }
            string fileName = ServicesDirs.CacheDir + "\\CachedDictionary." + dict.Name + ".txt";

            if (FileUtil.Exists(fileName))
            {
                DateTime updateTime = FileUtil.GetFileLastWriteTime(fileName);
                if (DateTime.Now.Subtract(updateTime).TotalDays < 1)
                {
                    ReadDictionaryFromCacheFile(fileName, dict);
                    if (dict.Words != null && dict.Words.Count > 0)
                    {
                        return(dict);
                    }
                }
            }

            ReadDictionaryFromOracle(dict);
            WriteDictionaryToCacheFile(fileName, dict);
            return(dict);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Convert an external user or group name to an internal name
        /// </summary>
        /// <param name="extName"></param>
        /// <returns></returns>
        string ExternalToInternalName(string extName)
        {
            if (Lex.IsNullOrEmpty(extName))
            {
                return("");
            }
            UserGroup g = LookupGroupItem(extName);             // see if group name first

            if (g != null)
            {
                return(g.InternalName);
            }

            DictionaryMx userDict = DictionaryMx.Get("UserName");

            if (userDict == null)
            {
                return(extName);
            }
            foreach (string userName in userDict.Words)
            {
                string   userInfoString = userDict.LookupDefinition(userName);
                UserInfo userInfo       = UserInfo.Deserialize(userInfoString);
                if (userInfo == null || Lex.IsNullOrEmpty(userInfo.FullName))
                {
                    continue;
                }
                if (Lex.Eq(userInfo.FullNameReversed, extName))
                {
                    return(userInfo.UserName);
                }
            }

            return(extName);            // shouldn't happen
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Set any new label for a metacolumn
        /// </summary>
        /// <param name="mc"></param>

        public static void SetAnyNewMetaColumnLabel(
            MetaColumn mc)
        {
            string       name    = mc.MetaTable.Name + "." + mc.Name;
            DictionaryMx newDict = DictionaryMx.Get("NewNameDict");

            if (newDict == null)
            {
                return;
            }
            string newLabel = newDict.LookupDefinition(name);

            if (newLabel == null)
            {
                return;
            }

            DictionaryMx originalDict = DictionaryMx.Get("OriginalNameDict");

            if (originalDict == null)
            {
                return;
            }
            originalDict.Add(mc.MetaTable.Name + "." + mc.Name, mc.Label);             // save original label

            mc.Label = newLabel;
            mc.Units = "";             // prevent addition of units
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Setup a dropdown control from a dictionary
        /// </summary>
        /// <param name="ctl">Control to set up</param>
        /// <param name="dictName">dictionary name, null to reset control</param>
        /// <param name="reload">reload the list even if previously loaded</param>
        /// <returns></returns>

        public static bool SetListControlItemsFromDictionary(
            object ctlObj,
            string dictName,
            bool reload)
        {
            List <string> dict;
            int           begRow, rowSel, i1;

            if (dictName == null || dictName == "")
            {             // no dictionary, clear dropdown
                UIMisc.SetListControlItems(ctlObj, "");
                return(true);
            }

            dict = DictionaryMx.GetWords(dictName, true);
            if (dict == null)
            {
                return(false);
            }

            StringBuilder buf = new StringBuilder();

            foreach (string s in dict)
            {
                if (buf.Length > 0)
                {
                    buf.Append("\n");
                }
                buf.Append(s);
            }

            UIMisc.SetListControlItems(ctlObj, buf.ToString());

            return(true);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Get words and definitions for dictionary, usually from an Oracle database
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>

        public DictionaryMx GetDefinitions(string dictName)
        {
            dictName = dictName.ToLower();

            if (Dictionaries == null)
            {
                throw new Exception("Dictionary XML not loaded");
            }
            if (!Dictionaries.ContainsKey(dictName))
            {
                throw new Exception("Unknown dictionary: " + dictName);
            }

            DictionaryMx dict = Dictionaries[dictName.ToLower()];

            if (dict.Words != null)
            {
                return(dict);                                // just return if already have
            }
            if (dict.Sql == null || dict.Sql == "")
            {
                return(dict);                                                // empty dictionary
            }
            ReadDictionary(dict);
            return(dict);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Get the path to the MoeExecutable and any default args
        /// </summary>
        /// <param name="moeExecutable"></param>
        /// <param name="moeArgs"></param>

        bool GetMoeExecutable(
            out string mxp,
            out string moeArgs)
        {
            string dmxp = "";

            while (true)
            {
                mxp = moeArgs = "";

                string cl = Preferences.Get("MoeCommandLine");                 // try personal preference first

                if (Lex.IsDefined(cl))
                {
                    ParseMoeCommandLine(cl, out mxp, out moeArgs);
                    dmxp = mxp;
                    if (File.Exists(mxp))
                    {
                        return(true);
                    }
                }

                // If no personal preference then cycle on MOE command lines until we find one that works
                // Example: "C:\Users\[userName]\AppData\Roaming\moe2018\bin\moe.exe  -setenv 'MOE=C:\Users\[userName]\AppData\Roaming\moe2018'"

                DictionaryMx md = DictionaryMx.Get("MoeCommandLines");
                if (md != null)
                {
                    for (int i1 = 0; i1 < md.Words.Count; i1++)
                    {
                        cl = md.Words[i1];
                        if (Lex.IsUndefined(cl))
                        {
                            continue;
                        }
                        cl = cl.Replace("'", "\"");
                        cl = Lex.Replace(cl, "[userName]", SS.I.UserName);
                        ParseMoeCommandLine(cl, out mxp, out moeArgs);
                        if (Lex.IsUndefined(dmxp))
                        {
                            dmxp = mxp;
                        }
                        if (File.Exists(mxp))
                        {
                            return(true);
                        }
                    }
                }

                if (!GetPersonalMoeExecutableLocation(dmxp))
                {
                    return(false);
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Read dictionary from Oracle table
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>

        static DictionaryMx ReadDictionaryFromOracle(
            DictionaryMx dict)
        {
            DbCommandMx drd = null;
            int         t0, t1, i1;

            try
            {
                //if (Lex.Eq(dict.Name, "DIT_PERSON")) dict = dict; // debug
                DbDataReader dr = null;

                drd = new DbCommandMx();
                drd.Prepare(dict.Sql);
                dr = drd.ExecuteReader();

                t0 = TimeOfDay.Milliseconds();
                while (drd.Read())
                {
                    if (!dr.IsDBNull(0))
                    {
                        string word = dr.GetValue(0).ToString();
                        if (Lex.IsNullOrEmpty(word))
                        {
                            continue;
                        }
                        string definition = null;
                        if (!dr.IsDBNull(1))
                        {
                            definition = dr.GetValue(1).ToString();
                        }
                        dict.Add(word, definition);
                        t1 = TimeOfDay.Milliseconds();
                        //						if (t1-t0 > 2000) break; // limit time for development
                    }
                }
                drd.CloseReader();
                drd.Dispose();

                t1 = TimeOfDay.Milliseconds() - t0;

                //				DebugLog.Message("ReadDictionaryFromOracle " + dict.Name + " Time: " + t1.ToString());
                return(dict);
            }
            catch (Exception ex)
            {
                if (drd != null)
                {
                    drd.Dispose();
                }
                return(null);
            }
        }
Ejemplo n.º 9
0
        static bool ReadDictionaryFromCacheFile(
            string fileName,
            DictionaryMx dict)
        {
            StreamReader sr = null;
            string       rec, word, definition;

            string[] sa;

            try
            {
                sr = new StreamReader(fileName);
                while (true)
                {
                    rec = sr.ReadLine();
                    if (rec == null)
                    {
                        break;
                    }
                    sa = rec.Split('\t');
                    if (sa.Length != 2)
                    {
                        continue;
                    }

                    word = sa[0];
                    if (Lex.IsNullOrEmpty(word))
                    {
                        continue;
                    }

                    definition = sa[1];
                    dict.Add(word, definition);
                }

                sr.Close();

                return(true);
            }

            catch (Exception ex)
            {
                try { sr.Close(); } catch { }
                DebugLog.Message(ex.Message);
                return(false);
            }
        }
Ejemplo n.º 10
0
/// <summary>
/// Get user information string
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>

        static string GetUserInfo(string userName)
        {
            if (UserNames == null)
            {
                DictionaryFactory df = new DictionaryFactory();

                UserNames = DictionaryMx.Get("UserName");
                if (UserNames == null)
                {
                    UserNames = new DictionaryMx();
                }
            }

            userName = UserInfo.NormalizeUserName(userName);
            string userInfo = UserNames.LookupDefinition(userName);

            return(userInfo);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Setup a dropdown control from a dictionary
        /// </summary>
        /// <param name="items">Control item collection to fill</param>
        /// <param name="dictName">Dictionary name, null to reset control</param>

        public static void SetListControlItemsFromDictionary(
            ComboBoxItemCollection items,
            string dictName,
            bool removeDuplicates)
        {
            items.Clear();
            if (String.IsNullOrEmpty(dictName))
            {
                return;
            }

            List <string> words = DictionaryMx.GetWords(dictName, removeDuplicates);

            if (words == null)
            {
                return;
            }
            items.AddRange(words);
            return;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Get user information for a user
        /// Note: Will not get email address (avoids slowdown)
        /// </summary>
        /// <param name="?"></param>
        /// <returns></returns>

        public static UserInfo GetUserInfo(
            string userName)
        {
            UserInfo ui;

            if (UserInfo != null && Lex.Eq(userName, UserInfo.UserName))
            {             // if current user then return complete information including privileges
                ui = UserInfo.Clone();
                return(ui);
            }

            string uInf = DictionaryMx.LookupDefinition("UserName", userName);             // lookup serialized user info in "UserName" dictionary

            if (uInf == null)
            {
                return(null);                          // just return null if not found
            }
            UserInfo sui = UserInfo.Deserialize(uInf);

            return(sui);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Get the set of dictionaries and those definitions contained in the base XML
        /// </summary>
        /// <returns></returns>

        public Dictionary <string, DictionaryMx> LoadDictionaries()
        {
            Dictionary <string, DictionaryMx> dicts = null;

            if (ServiceFacade.UseRemoteServices)
            {
                Native.INativeSession nativeClient = ServiceFacade.CreateNativeSessionProxy();
                Services.Native.NativeMethodTransportObject resultObject = ServiceFacade.InvokeNativeMethod(nativeClient,
                                                                                                            (int)Native.ServiceCodes.MobiusDictionaryService,
                                                                                                            (int)Native.ServiceOpCodes.MobiusDictionaryService.GetBaseDictionaries,
                                                                                                            new Services.Native.NativeMethodTransportObject(new object[] { false }));
                ((System.ServiceModel.IClientChannel)nativeClient).Close();
                if (resultObject == null)
                {
                    return(null);
                }
                Dictionary <string, ServiceTypes.DictionaryMx> serviceDictionaryMxs =
                    (Dictionary <string, ServiceTypes.DictionaryMx>)resultObject.Value;
                dicts = ServiceFacade.TypeConversionHelper.Convert <
                    Dictionary <string, ServiceTypes.DictionaryMx>,
                    Dictionary <string, DictionaryMx> >(serviceDictionaryMxs);
                return(dicts);
            }

            else
            {
                dicts = DictionaryFactoryInstance.LoadDictionaries();
                DictionaryMx.Dictionaries = dicts;

                DictionaryMx secondaryMessages =                 // see if secondary debug error messages defined
                                                 DictionaryMx.Get("SecondaryErrorMessages");

                if (secondaryMessages != null)
                {
                    DebugLog.SecondaryErrorMessages = secondaryMessages.WordLookup;
                }

                return(dicts);
            }
        }
Ejemplo n.º 14
0
/// <summary>
/// Get an internal user name from an external name
/// </summary>
/// <param name="externalUserName"></param>
/// <returns></returns>

        public static string GetInternalUserName(
            string externalUserName)
        {
            DictionaryMx users = DictionaryMx.Get("UserName");

            if (users == null)
            {
                users = new DictionaryMx();
            }

            for (int i1 = 0; i1 < users.Words.Count; i1++)
            {
                string userId = users.Words[i1];
                string name   = SecurityUtil.GetPersonNameReversed(userId);
                if (Lex.Eq(userId, externalUserName) || Lex.Eq(name, externalUserName))
                {
                    return(userId);
                }
            }

            return(null);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Get words and definitions for dictionary, usually from an Oracle database
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>

        public void GetDefinitions(DictionaryMx dict)
        {
            if (ServiceFacade.UseRemoteServices)
            {
                //Mobius.Data.DictionaryMx expects to be used to maintain the local cache
                // -- and I expect the static member that holds that cache is not null
                if (DictionaryMx.Dictionaries == null)
                {
                    throw new Exception("Dictionary XML not loaded");
                }

                if (dict != null && !String.IsNullOrEmpty(dict.Name))
                {
                    Native.INativeSession nativeClient = ServiceFacade.CreateNativeSessionProxy();
                    Services.Native.NativeMethodTransportObject resultObject = ServiceFacade.InvokeNativeMethod(nativeClient,
                                                                                                                (int)Native.ServiceCodes.MobiusDictionaryService,
                                                                                                                (int)Native.ServiceOpCodes.MobiusDictionaryService.GetDictionaryByName,
                                                                                                                new Services.Native.NativeMethodTransportObject(new object[] { dict.Name }));
                    ((System.ServiceModel.IClientChannel)nativeClient).Close();

                    if (resultObject == null || resultObject.Value == null)
                    {
                        return;
                    }

                    string txt = resultObject.Value.ToString();
                    DictionaryMx.Deserialize(txt, dict);

                    return;
                }
            }

            else
            {
                DictionaryFactoryInstance.GetDefinitions(dict);
                string txt = dict.Serialize();
                DictionaryMx.Deserialize(txt, dict);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Get words and definitions for dictionary, usually from an Oracle database
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>

        public void GetDefinitions(DictionaryMx dict)
        {
            if (Dictionaries == null)
            {
                throw new Exception("Dictionary XML not loaded");
            }

            string dictName = dict.Name.ToLower();

            if (dict.Words != null)
            {
                return;                                 // just return if already have
            }
            dict.Initialize();

            if (dict.Sql == null || dict.Sql == "")
            {
                return;                                                 // empty dictionary
            }
            ReadDictionary(dict);
            return;
        }
Ejemplo n.º 17
0
/// <summary>
/// Get a sorted list of all user names
/// </summary>
/// <returns></returns>

        public static List <string> GetAllUsers()
        {
            DictionaryMx users = DictionaryMx.Get("UserName");

            if (users == null)
            {
                users = new DictionaryMx();
            }

            List <string> names = new List <string>();

            for (int i1 = 0; i1 < users.Words.Count; i1++)
            {
                string name = SecurityUtil.GetPersonNameReversed(users.Words[i1]);
                if (!Lex.IsNullOrEmpty(name))
                {
                    names.Add(name);
                }
            }

            names.Sort();
            return(names);
        }
Ejemplo n.º 18
0
        static bool WriteDictionaryToCacheFile(
            string fileName,
            DictionaryMx dict)
        {
            StreamWriter sw = null;
            string       rec, definition;

            try
            {
                if (!Directory.Exists(ServicesDirs.CacheDir))
                {
                    Directory.CreateDirectory(ServicesDirs.CacheDir);
                }

                sw = new StreamWriter(fileName);
                foreach (string word in dict.Words)
                {
                    definition = dict.LookupDefinition(word);
                    if (definition == null)
                    {
                        definition = "";
                    }
                    sw.WriteLine(word + "\t" + definition);
                }

                sw.Close();

                return(true);
            }

            catch (Exception ex)
            {
                try { sw.Close(); } catch { }
                DebugLog.Message(ex.Message);
                return(false);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Setup the options from psc
        /// </summary>
        /// <param name="psc"></param>

        public void Setup(
            SmallWorldPredefinedParameters swpArg)
        {
            try
            {
                InSetup = true;
                bool t = true, f = false;

                Swp = swpArg;                 // save reference to parameters

                if (SwDbDict == null)
                {
                    SwDbDict = DictionaryMx.Get("SmallWorldDatabases");
                    if (SwDbDict != null)
                    {
                        UIMisc.SetListControlItemsFromDictionary(DatabaseComboBox.Properties.Items, SwDbDict.Name, true);
                    }

                    GetDefaultSmallWorldOptions();                     // also get any default options for user
                }

                if (Swp == null)                 // get initial option values
                {
                    SmallWorldPredefinedParameters swp = FindStandardPresetMatchingCustomSettings();

                    if (swp == null)                     // if no match then use my preferred
                    {
                        swp = CustomSettings;
                    }

                    if (swp.MaxHits <= 0)                     // be sure maxhits is defined
                    {
                        swp.MaxHits = SmallWorldPredefinedParameters.DefaultMaxHits;
                    }

                    Swp = swp.Clone();                     // make copy
                }

                List <string> dbList = GetDbSetList();

                string dbs           = "";
                foreach (string dbName in dbList)
                {
                    if (SwDbDict.LookupDefinition(dbName) == null)
                    {
                        continue;
                    }
                    if (dbs != "")
                    {
                        dbs += ", ";
                    }
                    dbs += dbName;
                }

                Swp.Database = dbs;

                if (Lex.IsUndefined(Swp.Database))                 // default to first entry in dict
                {
                    Swp.Database = SwDbDict.Words[0];              // assign first database as default if not defined
                }
                DatabaseComboBox.Text = Swp.Database;

                PresetsComboBox.Text = Swp.PresetName;

                CriteriaStructureRangeCtl.SetRange(DistanceRange, "", DistanceRangeLabel, null, Swp.Distance);
                if (Swp.MaxHits < 0)
                {
                    MaxHits.Text = "";
                }
                else
                {
                    MaxHits.Text = Swp.MaxHits.ToString();
                }

                // Set the Defined and Enabled attributes for each range based on search type

                Swp.TerminalUp.Enabled        = Swp.TerminalDown.Enabled = true;
                Swp.RingUp.Enabled            = Swp.RingDown.Enabled = true;
                Swp.LinkerUp.Enabled          = Swp.LinkerDown.Enabled = true;
                Swp.MutationMinor.Enabled     = Swp.MutationMajor.Enabled = true;
                Swp.SubstitutionRange.Enabled = Swp.HybridisationChange.Enabled = true;

                if (Lex.Eq(Swp.PresetName, SmallWorld.PresetName) ||
                    Lex.Eq(Swp.PresetName, CustomSettings.PresetName))
                {
                    ;
                }

                else if (Lex.Eq(Swp.PresetName, Substructure.PresetName))
                {
                    Swp.TerminalDown.Enabled = false;
                    Swp.RingDown.Enabled     = false;
                    Swp.LinkerDown.Enabled   = false;

                    Swp.MutationMinor.Enabled = Swp.MutationMajor.Enabled = false;
                }

                else if (Lex.Eq(Swp.PresetName, SuperStructure.PresetName))
                {
                    Swp.TerminalUp.Enabled = false;
                    Swp.RingUp.Enabled     = false;
                    Swp.LinkerUp.Enabled   = false;

                    Swp.MutationMinor.Enabled = Swp.MutationMajor.Enabled = false;
                }

                else if (Lex.Eq(Swp.PresetName, BemisMurckoFramework.PresetName))
                {
                    Swp.RingUp.Enabled   = Swp.RingDown.Enabled = false;
                    Swp.LinkerUp.Enabled = Swp.LinkerDown.Enabled = false;
                }

                else if (Lex.Eq(Swp.PresetName, NqMCS.PresetName))
                {
                    Swp.LinkerUp.Enabled      = Swp.LinkerDown.Enabled = false;
                    Swp.MutationMinor.Enabled = Swp.MutationMajor.Enabled = false;
                }

                else if (Lex.Eq(Swp.PresetName, ElementGraph.PresetName))
                {
                    Swp.TerminalUp.Enabled = Swp.TerminalDown.Enabled = false;
                    Swp.RingUp.Enabled     = Swp.RingDown.Enabled = false;
                    Swp.LinkerUp.Enabled   = Swp.LinkerDown.Enabled = false;

                    Swp.MutationMinor.Enabled = Swp.MutationMajor.Enabled = false;
                }

                MatchAtomTypes.Checked = Swp.MatchAtomTypes;
                bool e = Swp.MatchAtomTypes;
                Swp.LinkerUp.Active          = Swp.LinkerDown.Active = !e;
                Swp.MutationMinor.Active     = Swp.MutationMajor.Active = e;
                Swp.SubstitutionRange.Active = Swp.HybridisationChange.Active = e;

                // Set the range controls

                TerminalRangeUp.Set(Swp.TerminalUp);
                TerminalRangeDown.Set(Swp.TerminalDown);
                RingRangeUp.Set(Swp.RingUp);
                RingRangeDown.Set(Swp.RingDown);
                LinkerRangeUp.Set(Swp.LinkerUp);
                LinkerRangeDown.Set(Swp.LinkerDown);

                MutationRangeMinor.Set(Swp.MutationMinor);
                MutationRangeMajor.Set(Swp.MutationMajor);
                SubstitutionRange.Set(Swp.SubstitutionRange);
                HybridizationRange.Set(Swp.HybridisationChange);

                ShowColors.Checked = Swp.Highlight;
                SetControlBackgroundColors(ShowColors.Checked);

                AlignStructs.Checked = Swp.Align;
            }

            finally { InSetup = false; }

            return;
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Parse an operator and value
        /// </summary>
        /// <param name="qc"></param>
        /// <param name="op"></param>
        /// <param name="val"></param>
        /// <returns>Expert form of criteria if form is acceptable</returns>

        static string CheckCriteriaValue(
            QueryColumn qc,
            string val)
        {
            string eval, txt, txt2, txt3;
            int    i1;
            double d1;

            MetaColumn mc = qc.MetaColumn;

            if (val == null)
            {
                return(null);
            }

            val = eval = val.Trim();

            switch (mc.DataType)
            {
            case MetaColumnType.Date:
                eval = DateTimeMx.Normalize(val);
                if (eval == null)
                {
                    MessageBoxMx.Show(val + " is not a valid date", UmlautMobius.String,
                                      MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return(null);
                }
                break;

            case MetaColumnType.Integer:
            case MetaColumnType.Number:
            case MetaColumnType.QualifiedNo:
                try
                { d1 = Convert.ToDouble(val); }
                catch (Exception e)
                {
                    MessageBoxMx.Show(val + " is not a valid number", UmlautMobius.String,
                                      MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return(null);
                }
                break;

            case MetaColumnType.String:                     // quoted form
            case MetaColumnType.MolFormula:
                eval = Lex.AddSingleQuotes(Lex.RemoveSingleQuotes(val));
                break;

            case MetaColumnType.DictionaryId:                             // translate dictionary value back to database value
                eval = DictionaryMx.LookupDefinition(mc.Dictionary, val); // get database value
                if (eval == null || eval == "")
                {
                    MessageBoxMx.Show(Lex.Dq(val) + " is not a valid value.\nYou must select an item from the dropdown box.", UmlautMobius.String,
                                      MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return(null);
                }
                eval = Lex.AddSingleQuotes(Lex.RemoveSingleQuotes(eval)); // quote in case string value
                break;
            }                                                             // end of datatype case

            return(eval);
        }         // end of CheckCriteriaValue
Ejemplo n.º 21
0
/// <summary>
/// Setup the form with existing criteria
/// </summary>
/// <param name="qc"></param>

        void Setup(
            QueryColumn qc)
        {
            string    op, tok, val;
            CheckEdit option    = null;
            CheckEdit subOption = null;
            int       i1;

            MetaColumn mc = qc.MetaColumn;

            string prompt = "Select the search criteria that you want to apply to " + qc.ActiveLabel +
                            " from the list below and enter the limiting value(s).";

            bool removeDuplicates = mc.IgnoreCase;                                                             // remove dups if ignoring case

            UIMisc.SetListControlItemsFromDictionary(Value.Properties.Items, mc.Dictionary, removeDuplicates); // setup dropdown

            switch (mc.DataType)
            {
            case MetaColumnType.Integer:
            case MetaColumnType.Number:
            case MetaColumnType.QualifiedNo:
                Setup(true, true, false, false);
                break;

            case MetaColumnType.String:
                Setup(true, true, true, false);
                break;

            case MetaColumnType.Date:
                prompt += " Dates can be entered in the common standard ways: e.g. 12/31/2004 or 31-Dec-04.";
                Setup(true, true, false, true);
                break;

            case MetaColumnType.DictionaryId:
                Setup(false, false, false, false);
                break;
            }

            // Fill in the form with the current criteria

            Instance.Text        = "Search Criteria for " + qc.ActiveLabel;
            Instance.Prompt.Text = prompt;

            ParsedSingleCriteria psc = MqlUtil.ParseSingleCriteria(qc.Criteria);

            if (psc == null)
            {             // create default values
                psc    = new ParsedSingleCriteria();
                psc.Op = "=";
            }

            if (mc.DataType == MetaColumnType.Date && psc.OpEnum != CompareOp.Within)             // format dates for user if not within clause
            {
                if (psc.Value != "")
                {
                    psc.Value = DateTimeMx.Format(psc.Value);
                }
                if (psc.Value2 != "")
                {
                    psc.Value2 = DateTimeMx.Format(psc.Value2);
                }
                if (psc.ValueList != null)
                {
                    for (i1 = 0; i1 < psc.ValueList.Count; i1++)
                    {
                        tok = (string)psc.ValueList[i1];
                        if (tok != null && tok != "")
                        {
                            psc.ValueList[i1] = DateTimeMx.Format(tok);
                        }
                    }
                }
            }

            else if (mc.DataType == MetaColumnType.DictionaryId && psc.Value != "")
            {             // transform database value to dictionary value
                val = DictionaryMx.LookupWordByDefinition(mc.Dictionary, psc.Value);
                if (val != null && val != "")
                {
                    psc.Value = val;
                }
            }

            op = psc.Op;

            // Fill fields based on criteria types

            if (op == "" || op.IndexOf("=") >= 0 || op.IndexOf("<") >= 0 || op.IndexOf(">") >= 0)
            {
                option = BasicOp;
                if (op == "=" || op == "")
                {
                    BasicOpBut.Text = "Equals";
                }
                else if (op == "<")
                {
                    BasicOpBut.Text = "<";
                }
                else if (op == "<=")
                {
                    BasicOpBut.Text = UnicodeString.LessOrEqual;
                }
                else if (op == "<>")
                {
                    BasicOpBut.Text = UnicodeString.NotEqual;
                }
                else if (op == ">")
                {
                    BasicOpBut.Text = ">";
                }
                else if (op == ">=")
                {
                    BasicOpBut.Text = UnicodeString.GreaterOrEqual;
                }

                Value.Text = psc.Value;                 // put in current value
            }

            else if (Lex.Eq(op, "Between"))
            {
                option      = Between;
                Limit1.Text = psc.Value;
                Limit2.Text = psc.Value2;
            }

            else if (Lex.Eq(op, "In"))
            {
                option = InList;
                StringBuilder sb = new StringBuilder();
                for (i1 = 0; i1 < psc.ValueList.Count; i1++)
                {
                    if (i1 > 0)
                    {
                        sb.Append(", ");
                    }
                    sb.Append((string)psc.ValueList[i1]);
                }
                ValueList.Text = sb.ToString();                 // set value
            }

            else if (Lex.Eq(op, "Like"))
            {
                option         = Like;
                tok            = psc.Value.Replace("%", "");      // remove sql wildcard characters
                Substring.Text = tok;
            }

            else if (Lex.Eq(op, "Within"))
            {
                option           = Within;
                WithinValue.Text = psc.Value;

                string value2 = psc.Value2;

                if (Lex.Contains(value2, "Day"))                 // translate alternative values
                {
                    value2 = "Day(s)";
                }
                else if (Lex.Contains(value2, "Week"))
                {
                    value2 = "Week(s)";
                }
                else if (Lex.Contains(value2, "Month"))
                {
                    value2 = "Month(s)";
                }
                else if (Lex.Contains(value2, "Year"))
                {
                    value2 = "Year(s)";
                }

                WithinUnits.Text = value2;
            }

            else if (Lex.Eq(op, "is not null"))
            {
                option = IsNotNull;
            }

            else if (Lex.Eq(op, "is null"))
            {
                option = IsNull;
            }

            else if (Lex.Eq(op, "is not null or is null"))
            {
                option = All;
            }

            else             // oops
            {
                MessageBoxMx.ShowError("Unrecognized criteria type");
                qc.Criteria = qc.CriteriaDisplay = "";
                return;
            }

            option.Checked = true;

            return;
        }
Ejemplo n.º 22
0
        internal void SetupCheckedListBoxFromDictionary(
            string dictName,
            string criteria)
        {
            List <string> vList       = new List <string>();
            List <string> excludeList = new List <string>();

            List <string> dictWords;
            bool          itemChecked;

            SearchText.Text = "";

            dictWords = DictionaryMx.GetWords(dictName, false);
            if (dictWords == null)
            {
                throw new Exception("Dictionary not found: " + dictName);
            }

            Insetup = true;

            ParsedSingleCriteria psc = MqlUtil.ParseSingleCriteria(criteria);

            if (psc != null)
            {
                if (psc.ValueList != null)
                {
                    vList = psc.ValueList;
                }
                else if (!Lex.IsNullOrEmpty(psc.Value))
                {
                    vList.Add(psc.Value);
                }
            }
            HashSet <string> hashSet = new HashSet <string>(vList);

            CheckList.Items.Clear();
            int si = -1;

            foreach (string key in dictWords)
            {
                if (Lex.Eq(dictName, "STRUCTURE_DATABASES") && Lex.Eq(key, "UserDatabase"))
                {
                    continue;                     // special-case fix - generalize later
                }
                CheckedListBoxItem clbi = new CheckedListBoxItem();
                clbi.Description = key;
                if (hashSet.Contains(key))
                {
                    clbi.CheckState = CheckState.Checked;
                    if (si < 0)
                    {
                        si = CheckList.Items.Count;
                    }
                }
                else
                {
                    clbi.CheckState = CheckState.Unchecked;
                }
                CheckList.Items.Add(clbi);
            }

            if (si >= 0)
            {
                CheckList.SelectedIndex = si;
                CheckedListBoxItem clbi = CheckList.Items[si];
                SearchText.Text = clbi.Description;
            }

            SelectedItemText.Text        =
                SelectedItemText.ToolTip = GetCheckedListItems();

            Insetup = false;
            return;
        }
Ejemplo n.º 23
0
        /// <summary>
        /// See if a ClickFunction command & process if so
        /// </summary>
        /// <param name="command"></param>
        /// <param name="qm"></param>
        /// <param name="cInf"></param>

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

            int ai;

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

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

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

                    args.Add(arg);
                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        _query = QbUtil.ReadQuery(qId);

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

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

                        mt = null;
                        mc = null;

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

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

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

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

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

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

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

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

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

                    return;
                }

                // Open a URL, normally substituting parameter value

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

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

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

                    SystemUtil.StartProcess(url);
                    return;
                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        UIMisc.SaveAndOpenBinaryDocument(typeName, ba);
                    }

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

                    return;
                }

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

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

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

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

                    return;
                }

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

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

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

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

                ServicesLog.Message(msg);
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Load metadata describing dictionaries
        /// </summary>
        /// <param name="dictFileName"></param>
        /// <returns></returns>

        public Dictionary <string, DictionaryMx> LoadDictionaries()
        {
            XmlAttributeCollection atts;

            Dictionaries = new Dictionary <string, DictionaryMx>();

            //UalUtil is assumed to have been initialized
            // and UalUtil.MetaDataDir set
            string       dictFileName = ServicesDirs.MetaDataDir + @"\" + "Dictionaries.xml";
            StreamReader sr           = new StreamReader(dictFileName);
            XmlDocument  doc          = new XmlDocument();

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

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

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

            XmlNode dictNode = dictsNode.FirstChild;

            while (dictNode != null)             // loop through dictionaries
            {
                if (dictNode.NodeType != XmlNodeType.Element)
                {
                    ;                                                         // ignore non-elements
                }
                else if (Lex.Eq(dictNode.Name, "Dictionary"))                 // dictionary element
                {
                    DictionaryMx dict = new DictionaryMx();

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

                        if (Lex.Eq(att.Name, "Name"))
                        {
                            dict.Name = att.Value.ToLower();
                        }

                        else if (Lex.Eq(att.Name, "Sql"))
                        {
                            dict.Sql = att.Value;
                        }

                        else if (Lex.Eq(att.Name, "Cache"))
                        {
                            bool.TryParse(att.Value, out dict.Cache);
                        }

                        else
                        {
                            DebugLog.Message("Unexpected Dictionary (" + dict.Name + ") attribute: " + att.Name);
                        }
                    }

                    if (dict.Name == "")
                    {
                        throw new Exception("Connection is missing name");
                    }
                    if (Lex.EndsWith(dict.Name, "_cache"))
                    {
                        dict.Cache = true;                                                        // alternate way to indicate cached dictionary (avoid unexpected attribute exception in older clients)
                    }
                    Dictionaries[dict.Name] = dict;

                    XmlNode entryNode = dictNode.FirstChild;
                    while (entryNode != null)                     // loop through dict entries
                    {
                        if (entryNode.NodeType != XmlNodeType.Element)
                        {
                            ;                                                             // ignore non-elements
                        }
                        else if (Lex.Eq(entryNode.Name, "Entry"))                         // word entry
                        {
                            string word = "";
                            string def  = "";
                            atts = entryNode.Attributes;
                            for (int i = 0; i < atts.Count; i++)
                            {
                                XmlNode att = atts.Item(i);

                                if (Lex.Eq(att.Name, "Word"))
                                {
                                    word = att.Value.Trim();
                                }

                                else if (Lex.Eq(att.Name, "Def") ||
                                         Lex.Eq(att.Name, "Definition"))
                                {
                                    def = att.Value.Trim();
                                }

                                else
                                {
                                    DebugLog.Message("Unexpected Dictionary (" + dict.Name + ") entry attribute: " + att.Name);
                                }
                            }

                            if (word == "")
                            {
                                throw new Exception("Dictionary entry is missing Word attribute");
                            }
                            dict.Add(word, def);
                        }

                        else
                        {
                            throw new Exception("Expected Entry element but saw " +
                                                dictNode.Name);
                        }

                        entryNode = entryNode.NextSibling;
                    }                     // end of entry loop
                }

                else
                {
                    throw new Exception("Expected Dictionary element but saw " +
                                        dictNode.Name);
                }

                dictNode = dictNode.NextSibling;
            }             // end of dictionary loop

            sr.Close();

            return(Dictionaries);
        }