Contains() public method

public Contains ( Object key ) : bool
key Object
return bool
示例#1
0
 protected override void CreateChildControls()
 {
     Hashtable hs = new Hashtable();
     int result = LoginEntity.LoadConfiguration(SPContext.Current.Web.CurrentUser.LoginName, ref hs);
     if (result == 1)
     {
         PlayerUserControl control = (PlayerUserControl)Page.LoadControl(_ascxPath);
         if (hs != null)
         {
             if (hs.Contains("APIKey"))
                 control.APIKey = hs["APIKey"].ToString();
             if (hs.Contains("SecretKey"))
                 control.SecretKey = hs["SecretKey"].ToString();
         }
         Controls.Add(control);
     }
     else
     {
         string _ascxPathAPI = @"~/_CONTROLTEMPLATES/OoyalaPlugin.WP_API_Settings/APISettings/APISettingsUserControl.ascx";
         APISettingsUserControl control = (APISettingsUserControl)Page.LoadControl(_ascxPathAPI);
         if (hs != null)
         {
             if (hs.Contains("APIKey"))
                 control.APIKey = hs["APIKey"].ToString();
             if (hs.Contains("SecretKey"))
                 control.SecretKey = hs["SecretKey"].ToString();
             if (hs.Contains("PartnerCode"))
                 control.PartnerCode = hs["PartnerCode"].ToString();
         }
         control.APIErrorMessage = "API Settings are not configured properly";
         Controls.Add(control);
         return;
     }
 }
示例#2
0
        /// <summary>
        /// 创建数字签名
        /// </summary>
        /// <param name="htValidationParams">存放数字签名参数的Hashtable</param>
        /// <returns>DigitalSign</returns>
        public static string CreateDigitalSign(Hashtable htValidationParams)
        {
            if (!htValidationParams.Contains("AccountKey")
                || String.IsNullOrWhiteSpace(htValidationParams["AccountKey"].ToString()))
            {
                throw new ApplicationException("缺少API帐户密钥");
            }

            string accountKey = htValidationParams["AccountKey"].ToString().Trim();   //API帐户密钥

            List<string> stringList = new List<string>();
            //if (htValidationParams.Contains("service_version"))
            //    stringList.Add(string.Format("service_version={0}", htValidationParams["service_version"].ToString()));
            if (htValidationParams.Contains("partner"))
                stringList.Add(string.Format("partner={0}", htValidationParams["partner"].ToString()));
            if (htValidationParams.Contains("user_ip"))
                stringList.Add(string.Format("user_ip={0}", htValidationParams["user_ip"].ToString()));
            if (htValidationParams.Contains("sign"))
                stringList.Add(string.Format("sign={0}", htValidationParams["sign"].ToString()));

            //if (htValidationParams.Contains("ReqTime")
            //    && htValidationParams["ReqTime"] != null)
            //    stringList.Add(string.Format("ReqTime={0}", ((DateTime)htValidationParams["ReqTime"]).ToString("yyyy-MM-dd HH:mm:ss.fff")));

            string[] originalArray = stringList.ToArray();
            string[] sortedArray = BubbleSort(originalArray);
            string digitalSing = GetMD5ByArray(sortedArray, accountKey, "utf-8");
            return digitalSing;
        }
示例#3
0
文件: Example.cs 项目: langeds/aima
		public Example numerize(Hashtable attrValueToNumber) 
		{
			Hashtable numerizedExampleData = new Hashtable();
			foreach (string key in attributes.Keys)
			{
				Attribute attribute = (Attribute)attributes[key];
				if ( attribute is StringAttribute)
				{
					int correspondingNumber = int.Parse(((Hashtable)(attrValueToNumber[key]))[attribute.valueAsString()].ToString());
					NumericAttributeSpecification spec = new NumericAttributeSpecification(key);
					if (numerizedExampleData.Contains(key))
						numerizedExampleData[key] = new NumericAttribute((double)correspondingNumber,spec);
					else
						numerizedExampleData.Add(key,new NumericAttribute((double)correspondingNumber,spec));
					
				}
				else 
				{//Numeric Attribute
					if (numerizedExampleData.Contains(key))
						numerizedExampleData[key] = attribute;
					else
						numerizedExampleData.Add(key,attribute);
				}
			}
			return new Example(numerizedExampleData,(Attribute)numerizedExampleData[targetAttribute.name()]);
		}
示例#4
0
        public void WriteParameters()
        {
            MethodInformation mi = Procedures[current_method];

            if (mi.arg_names != null && mi.arg_names.Length > 0)
            {
                indent_level += 3;
                for (int i = 0; i < mi.arg_names.Length; i++)
                {
                    Indent();
                    if (variables.Contains(mi.arg_names[i].ToLower()))
                    {
                        stream.Write(" ??_Variable");
                        variables.Remove(mi.arg_names[i]);
                    }
                    else if (arrays.Contains(current_method.ToLower()))
                    {
                        stream.Write(" ??_Array");
                        arrays.Remove(mi.arg_names[i]);
                    }
                    else if (arrays_2d.Contains(current_method.ToLower()))
                    {
                        stream.Write(" ??_Array_2D");
                        arrays_2d.Remove(mi.arg_names[i]);
                    }
                    else
                    {
                        stream.Write(" ??");
                    }
                    if (mi.args_are_output[i])
                    {
                        stream.Write(" *");
                    }
                    else
                    {
                        stream.Write(" ");
                    }
                    stream.Write(mi.arg_names[i]);

                    if (i < mi.arg_names.Length - 1)
                    {
                        stream.WriteLine(";");
                    }
                    else
                    {
                        stream.WriteLine(")");
                    }
                }
                indent_level -= 3;

                indent_level -= 3;
                Indent();
                stream.WriteLine("{");
                indent_level += 3;
            }
            else
            {
                stream.WriteLine(" {");
            }
        }
示例#5
0
        /// <summary>
        /// Constructor for Read dialog
        /// </summary>
        public ReadDialog(Epi.Windows.MakeView.Forms.MakeViewMainForm frm)
            : base(frm)
        {
            InitializeComponent();
            Construct();
            SourceProjectNames = new Hashtable();

            if (frm.projectExplorer != null)
            {
                if (frm.projectExplorer.currentPage != null)
                {
                    this.sourceProject = frm.projectExplorer.currentPage.view.Project;
                    this.selectedProject = this.sourceProject;
                    this.selectedDataSource = this.selectedProject;

                    foreach (string s in this.sourceProject.GetNonViewTableNames())
                    {
                        string key = s.ToUpper().Trim();
                        if (!SourceProjectNames.Contains(key))
                        {
                            SourceProjectNames.Add(key, true);
                        }
                    }
                    foreach (string s in this.sourceProject.GetViewNames())
                    {
                        string key = s.ToUpper().Trim();
                        if (!SourceProjectNames.Contains(key))
                        {
                            SourceProjectNames.Add(key, true);
                        }
                    }

                }
            }
        }
        public static bool isAnagram(string[] test)
        {
            Hashtable tmp = new Hashtable();

            int count = 0;
            foreach (string s in test)
            {
                if (count == 0)
                {
                    foreach (char c in s)
                    {
                        string key = c.ToString();
                        if (tmp.Contains(key))
                        {
                            int value = (int)tmp[key];
                            tmp[key] = value + 1;
                        }
                        else
                        {
                            tmp.Add(key, 1);
                        }
                    }
                }

                if (count == 1)
                {
                    foreach (char c in s)
                    {
                        string key = c.ToString();

                        if (!tmp.Contains(key)) return false;
                        else
                        {
                            int value = (int)tmp[key];

                            if (value - 1 < 0) return false;
                            tmp[key] = value - 1;
                        }
                    }

                    // at the end, check tmp each value ==0

                    foreach (DictionaryEntry entry in tmp)
                    {
                        int value = (int)entry.Value;

                        if (value > 0) return false;
                        // redundant check
                        if (value < 0)
                        {
                            return false; // unreachable code
                        }
                    }
                    return true;
                }

                count++;
            }
            return false;
        }
示例#7
0
        public static Settings Load(Hashtable settings)
        {
            var result = new Settings();

            if (settings == null)
                return result;

            if (settings.Contains("RepoOwner"))
                result.RepoOwner = settings["RepoOwner"].ToString();

            if (settings.Contains("RepoName"))
                result.RepoName = settings["RepoName"].ToString();

            ReleaseTypes releaseType;

            result.ReleaseType = settings.Contains("Releases") && Enum.TryParse(settings["Releases"].ToString(), out releaseType)
                                ? releaseType
                                : ReleaseTypes.Latest;

            result.PreReleaseType = settings.Contains("PreReleases") && Enum.TryParse(settings["PreReleases"].ToString(), out releaseType)
                                ? releaseType
                                : ReleaseTypes.Latest;

            bool boolVal;

            result.EnableDownloadCounts = !settings.Contains("EnableDownloadCount") || !bool.TryParse(settings["EnableDownloadCount"].ToString(), out boolVal) || boolVal;

            return result;
        }
示例#8
0
        /*
         * Given an array of integers and a target value, find a pair of integers that
         * sum to the target value. Time complexity should be O(n).
         */
        public static int[] Two(int[] arr, int target)
        {
            Hashtable hash = new Hashtable();

            int iterations = 0;

            for (int i = 0; i < arr.Length; i++)
            {
                if (!hash.Contains(arr[i]))
                {
                    hash.Add(arr[i], arr[i]);
                }

                int diff = target - arr[i];

                if (hash.Contains(diff))
                {
                    return new int[] { arr[i], diff };
                }

                iterations++;
            }

            return new int[] { };
        }
        private static Hashtable GetSumPairs0(int[] input, int sum)
        {
            Hashtable result = new Hashtable();
            foreach (int val in input)
            {
                if (!result.Contains(val))
                {
                    result.Add(val, sum - val);
                }
            }

            for (int i = 0; i < input.Length - 1; i++)
            {
                int numb1 = input[i]; //how to remove dup key?
                int numb2 = sum - numb1;
                if (result.Contains(numb1) && result.Contains(numb2))
                {
                    result.Remove(numb2);
                    result[numb1] = numb2;
                }
                else if (result.Contains(numb1) && !result.Contains(numb2))
                {
                    result.Remove(numb1);
                }
            }

            return result;
        }
示例#10
0
        private void AddToView(string[] files, System.Collections.ArrayList al)
        {
            FileInfo     fi           = null;
            string       ParentPath   = string.Empty;
            string       ExePath      = string.Empty;
            Icon         icon         = null;
            int          index        = imglMenu.Images.Count;
            ListViewItem item         = null;
            int          j            = 0;
            string       groupKeyName = string.Empty;

            foreach (String srcFileName in files)
            {
                fi = new FileInfo(srcFileName);
                if (fi.Extension.ToLower() == ".lnk")
                {
                    ParentPath = ShortCutHelper.GetParentPathOfShortcut(srcFileName);
                    if (PubData.GV_CreateShowcutWithDel == true)
                    {
                        System.IO.File.Delete(srcFileName);
                    }
                }
                else
                {
                    ParentPath = srcFileName;
                }
                //if (ExistExePath(ParentPath) == false)
                //{
                SaveExePathToDB(al, ParentPath);

                ExePath      = ParentPath;
                fi           = new FileInfo(ExePath);
                groupKeyName = fi.Extension;
                if (!htListGroups.Contains(groupKeyName))
                {
                    ListViewGroup group = new ListViewGroup();
                    group.Header = groupKeyName;
                    group.Name   = groupKeyName;
                    lvStartMenu.Groups.Add(group);
                    htListGroups.Add(groupKeyName, group);
                }

                icon = FileIcon.ExtractAssociatedIcon(ExePath);

                imglMenu.Images.Add(icon);
                imglMenu.Images.SetKeyName(index + j, fi.Name);


                item = new ListViewItem();

                item.Text       = fi.Name;
                item.Group      = (ListViewGroup)htListGroups[groupKeyName];
                item.Tag        = fi.FullName;
                item.ImageIndex = index + j;
                lvStartMenu.Items.Add(item);
                j++;
                //}
            }
        }
示例#11
0
 public bool GetRequired(Control ctl)
 {
     if (Props.Contains(ctl))
     {
         return((bool)Props[ctl]);
     }
     else
     {
         return(false);
     }
 }
示例#12
0
        public override void CustomiseResponse(ref System.Collections.Hashtable response, UserProfile theUser)
        {
            Int32 circode = (Int32)response["circuit_code"];

            theUser.AddSimCircuit((uint)circode, LLUUID.Random());
            response["home"]     = "{'region_handle':[r" + (997 * 256).ToString() + ",r" + (996 * 256).ToString() + "], 'position':[r" + theUser.homepos.X.ToString() + ",r" + theUser.homepos.Y.ToString() + ",r" + theUser.homepos.Z.ToString() + "], 'look_at':[r" + theUser.homelookat.X.ToString() + ",r" + theUser.homelookat.Y.ToString() + ",r" + theUser.homelookat.Z.ToString() + "]}";
            response["sim_port"] = m_port;
            response["sim_ip"]   = m_ipAddr;
            response["region_y"] = (Int32)regionY * 256;
            response["region_x"] = (Int32)regionX * 256;

            string first;
            string last;

            if (response.Contains("first_name"))
            {
                first = (string)response["first_name"];
            }
            else
            {
                first = "test";
            }

            if (response.Contains("last_name"))
            {
                last = (string)response["last_name"];
            }
            else
            {
                last = "User";
            }

            ArrayList InventoryList = (ArrayList)response["inventory-skeleton"];
            Hashtable Inventory1    = (Hashtable)InventoryList[0];

            Login _login = new Login();

            //copy data to login object
            _login.First           = first;
            _login.Last            = last;
            _login.Agent           = new LLUUID((string)response["agent_id"]);
            _login.Session         = new LLUUID((string)response["session_id"]);
            _login.SecureSession   = new LLUUID((string)response["secure_session_id"]);
            _login.BaseFolder      = null;
            _login.InventoryFolder = new LLUUID((string)Inventory1["folder_id"]);

            //working on local computer if so lets add to the gridserver's list of sessions?
            if (m_gridServer.GetName() == "Local")
            {
                Console.WriteLine("adding login data to gridserver");
                ((LocalGridBase)this.m_gridServer).AddNewSession(_login);
            }
        }
 public object GetValue(string propertyName, object defaultValue)
 {
     if (Properties == null)
     {
         return(defaultValue);
     }
     if (!Properties.Contains(propertyName))
     {
         return(defaultValue);
     }
     return(Properties[propertyName]);
 }
示例#14
0
        public void TestContainsBasic()
        {
            StringBuilder sblMsg = new StringBuilder(99);

            Hashtable ht1 = null;

            string s1 = null;
            string s2 = null;

            int i = 0;

            ht1 = new Hashtable(); //default constructor
            Assert.False(ht1.Contains("No_Such_Key"));

            /// []  Testcase: add few key-val pairs
            ht1 = new Hashtable();
            for (i = 0; i < 100; i++)
            {

                sblMsg = new StringBuilder(99);
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg = new StringBuilder(99);
                sblMsg.Append("val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                ht1.Add(s1, s2);
            }

            for (i = 0; i < ht1.Count; i++)
            {
                sblMsg = new StringBuilder(99);
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                Assert.True(ht1.Contains(s1));
            }

            //
            // Remove a key and then check
            //
            sblMsg = new StringBuilder(99);
            sblMsg.Append("key_50");
            s1 = sblMsg.ToString();

            ht1.Remove(s1); //removes "Key_50"
            Assert.False(ht1.Contains(s1));
        }
示例#15
0
 public bool GetRequired(Control ctl)
 {
     if (CustomProps.Contains(ctl))
     {
         Props p = (Props)CustomProps[ctl];
         SetToolTip(ctl);
         return(p.Required);
     }
     else
     {
         return(false);
     }
 }
        protected override void SetOptions(Hashtable options)
        {
            // get the package code - generate if not specified
            _packageCode = options.Contains("packagecode")
                ? new Guid(options["packagecode"].ToString())
                : Guid.NewGuid();

            // get the product code - set to package code if not specified
            _productCode = options.Contains("productcode") ? new Guid(options["productcode"].ToString()) : _packageCode;

            // get the upgrade code - leave empty if not specified
            if (options.Contains("upgradecode"))
                _upgradeCode = new Guid(options["upgradecode"].ToString());
        }
示例#17
0
        private void LoadSettings()
        {
            moduleId = WebUtils.ParseInt32FromQueryString("mid", -1);
            itemId = WebUtils.ParseInt32FromQueryString("ItemID", -1);

            moduleSettings = ModuleSettings.GetModuleSettings(moduleId);
            GmapApiKey = SiteUtils.GetGmapApiKey();

            if (moduleSettings.Contains("GoogleMapInitialMapTypeSetting"))
            {
                string gmType = moduleSettings["GoogleMapInitialMapTypeSetting"].ToString();
                try
                {
                    mapType = (MapType)Enum.Parse(typeof(MapType), gmType);
                }
                catch (ArgumentException) { }

            }

            GoogleMapHeightSetting = WebUtils.ParseInt32FromHashtable(
                moduleSettings, "GoogleMapHeightSetting", GoogleMapHeightSetting);

            //GoogleMapWidthSetting = WebUtils.ParseInt32FromHashtable(
            //    moduleSettings, "GoogleMapWidthSetting", GoogleMapWidthSetting);
            if (moduleSettings.Contains("GoogleMapWidthSetting"))
            {
                GoogleMapWidthSetting = moduleSettings["GoogleMapWidthSetting"].ToString();
            }

            GoogleMapInitialZoomSetting = WebUtils.ParseInt32FromHashtable(
                moduleSettings, "GoogleMapInitialZoomSetting", GoogleMapInitialZoomSetting);

            GoogleMapEnableMapTypeSetting = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "GoogleMapEnableMapTypeSetting", false);

            GoogleMapEnableZoomSetting = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "GoogleMapEnableZoomSetting", false);

            GoogleMapShowInfoWindowSetting = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "GoogleMapShowInfoWindowSetting", false);

            GoogleMapEnableLocalSearchSetting = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "GoogleMapEnableLocalSearchSetting", false);

            GoogleMapEnableDirectionsSetting = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "GoogleMapEnableDirectionsSetting", false);

            AddClassToBody("eventcaldetail");
        }
示例#18
0
        public Hashtable SelectExecuteQuery(string cultureName)
        {
            Hashtable hashTable = new Hashtable();
            using (IDbConnection dbConnection = this.dataProvider.GetConnection)
            {
                dbConnection.Open();

                string resourceCmdText = "Select ResourceKey, ResourceValue from tStringResource where Language = @cultureName";

                List<KeyValuePair<string, object>> resourceParameters = new List<KeyValuePair<string, object>>();
                resourceParameters.Add(new KeyValuePair<string, object>("@cultureName", cultureName));
                IDbCommand command = this.GetCommand(resourceCmdText, dbConnection, this.dataProvider.GetParameter(resourceParameters), null);
                DataTable resourceDataTable = this.dataProvider.SelectQuery(command);


                string errorCmdText = "Select ErrorKey, ErrorMessage from tErrorResource where Language = @cultureName";

                List<KeyValuePair<string, object>> parameters = new List<KeyValuePair<string, object>>();
                parameters.Add(new KeyValuePair<string, object>("@cultureName", cultureName));
                IDbCommand Errorcommand = this.GetCommand(errorCmdText, dbConnection, this.dataProvider.GetParameter(parameters), null);
                DataTable ErrorDataTable = this.dataProvider.SelectQuery(Errorcommand);


                if (resourceDataTable != null && resourceDataTable.Rows.Count > 0)
                {
                    foreach (DataRow row in resourceDataTable.Rows)
                    {
                        if (hashTable.Contains(row["ResourceKey"].ToString()) == false)
                        {
                            hashTable.Add(row["ResourceKey"].ToString(), row["ResourceValue"].ToString());
                        }
                    }
                }

                if (ErrorDataTable != null && ErrorDataTable.Rows.Count > 0)
                {
                    foreach (DataRow row in ErrorDataTable.Rows)
                    {
                        if (hashTable.Contains(row["ErrorKey"].ToString()) == false)
                        {
                            hashTable.Add(row["ErrorKey"].ToString(), row["ErrorMessage"].ToString());
                        }
                    }
                }
            }

            return hashTable;
        }
示例#19
0
        public static ArrayList GetEmpMultiFilterParams(ref string sqlStr, Hashtable hashTable, DBUtil dbUtil)
        {
            ArrayList listParms = new ArrayList();
            UtilService utilService = new UtilService();

            if (hashTable.Contains("@EmpName"))
            {
                sqlStr = utilService.validSearchFilter(sqlStr, "@EmpName");
                listParms.Add(new SqlParameter("@EmpName", SqlDbType.NVarChar, 40));
            }

            if (hashTable.Contains("@IdCard"))
            {
                sqlStr = utilService.validSearchFilter(sqlStr, "@IdCard");
                listParms.Add(new SqlParameter("@IdCard", SqlDbType.VarChar, 20));
            }

            if (hashTable.Contains("@DeptID"))
            {
                sqlStr = utilService.validSearchFilter(sqlStr, "@DeptID");
                listParms.Add(new SqlParameter("@DeptID", SqlDbType.VarChar, 800));
            }

            if (hashTable.Contains("@EmpTypeID"))
            {
                sqlStr = utilService.validSearchFilter(sqlStr, "@EmpTypeID");
                listParms.Add(new SqlParameter("@EmpTypeID", SqlDbType.VarChar, 800));
            }

            if (hashTable.Contains("@StatusKBN"))
            {
                sqlStr = utilService.validSearchFilter(sqlStr, "@StatusKBN");
                listParms.Add(new SqlParameter("@StatusKBN", SqlDbType.VarChar, 800));
            }

            if (hashTable.Contains("@EntryTimeStart"))
            {
                sqlStr = utilService.validSearchFilter(sqlStr, "@EntryTimeStart");
                listParms.Add(new SqlParameter("@EntryTimeStart", SqlDbType.DateTime));
            }
            if (hashTable.Contains("@EntryTimeEnd"))
            {
                sqlStr = utilService.validSearchFilter(sqlStr, "@EntryTimeEnd");
                listParms.Add(new SqlParameter("@EntryTimeEnd", SqlDbType.DateTime));
            }
            if (hashTable.Contains("@LeaveTimeStart"))
            {
                sqlStr = utilService.validSearchFilter(sqlStr, "@LeaveTimeStart");
                listParms.Add(new SqlParameter("@LeaveTimeStart", SqlDbType.DateTime));
            }
            if (hashTable.Contains("@LeaveTimeEnd"))
            {
                sqlStr = utilService.validSearchFilter(sqlStr, "@LeaveTimeEnd");
                listParms.Add(new SqlParameter("@LeaveTimeEnd", SqlDbType.DateTime));
            }

            return listParms;
        }
        public void fun2()
        {
            List<int> li = new List<int>();
            Hashtable ht = new Hashtable();
            ht.Add(1, 'a');
            ht.Add(5, 'f');
            ht.Add(7, 'h');
            ht.Add(9, 'y');

            ICollection ic = ht.Keys;
            foreach (object o in ic)
            {
                Console.WriteLine(o.ToString());
            }

            Console.WriteLine(ht.Contains(1));
            char c = (char)ht[9];
            Console.WriteLine(c);

            ht[9] = 'x';
            //Console.WriteLine(c);
            foreach (DictionaryEntry de in ht)
            {
                Console.WriteLine("key ={0} value ={1}", de.Key, de.Value);
            }
        }
示例#21
0
 public void Declare_As_Variable(string name)
 {
     if (!classes.Contains(name))
     {
         variables.Add(name, null);
     }
 }
示例#22
0
        private Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
        {
            if (args == null || string.IsNullOrEmpty(args.Name))
            {
                return(null);
            }
            try
            {
                //First check if it's one of the already loaded assemblies.
                string shortname = (args.Name.Split(','))[0];
                if (mAssemblies.Contains(shortname))
                {
                    return(mAssemblies[shortname] as Assembly);
                }

                //load from search path, if file exists
                string filepath = ProtoCore.Utils.FileUtils.GetDSFullPathName(shortname + ".dll");
                if (File.Exists(filepath))
                {
                    return(Assembly.LoadFrom(filepath));
                }
            }
            catch (Exception)
            {
            }

            return(null);
        }
示例#23
0
        public void                 ApplyFilter(TestItem testItem, Hashtable found)
        {
			// Remove all test items not found in the list.
			for(int i=0; i<testItem.Children.Count; i++)
			{
				//If the entire test item was selected as part of the filter, we are done.
				//(as all children are implicitly included if the parent is selected)
                TestItem child = (TestItem)testItem.Children[i];
                if (!found.Contains(child))
                {
                    //If this is a leaf, then remove
                    if (child.Children.Count <= 0)
                    {
                        testItem.Children.Remove(child);
                        i--;
                    }
                    else
                    {
                        //Otherwise, check its children
                        ApplyFilter(child, found);

                        //If no test item children are left, (and since the test item wasn't on the list),
                        //then the test item shouldn't be removed as well
                        if (child.Children.Count <= 0)
                        {
                            testItem.Children.Remove(child);
                            i--;
                        }
                    }
                }
            }
        }
示例#24
0
        private static void Main(string[] args)
        {
            Hashtable storage = new Hashtable();

            XmlDocument doc = new XmlDocument();
            doc.Load("../../../catalogue.xml");

            XmlNodeList artists = doc.GetElementsByTagName("artist");

            foreach (XmlNode artist in artists)
            {
                if (!storage.Contains(artist.InnerText))
                {
                    storage.Add(artist.InnerText, 1);
                }
                else
                {
                    storage[artist.InnerText] = (int)storage[artist.InnerText] + 1;
                }

            }
            foreach (DictionaryEntry entry in storage)
            {
                Console.WriteLine("Artist: {0} has {1} albums", entry.Key, entry.Value);
            }
        }
示例#25
0
        static void Main(string[] args)
        {
            Hashtable openWith = new Hashtable();

            String key = " ";
            while (key != "")
            {

                int value = 1;

                key = Console.ReadLine();
                if (openWith.Contains(key))
                {
                    int value1 = (int)openWith[key];
                    openWith[key] = ++value1;
                }
                else
                    openWith.Add(key, value);
            }

            openWith.Remove("");

            PrintValues(openWith);

            Console.ReadKey();
        }
示例#26
0
 public override bool Contains(string key)
 {
     lock (Cache.SyncRoot)
     {
         return(Cache.Contains(this.QualifiedKey(key)));
     }
 }
示例#27
0
        // Creates a Hashtable object with one entry for each unique
        // subitem value (or initial letter for the parent item)
        // in the specified column.
        private Hashtable CreateGroupsTable(int column)
        {
            // Create a Hashtable object.
            Hashtable h_groups = new Hashtable();

            // Iterate through the items in listView_HoverTree.
            foreach (ListViewItem item in listView_HoverTree.Items)
            {
                // Retrieve the text value for the column.
                string h_subItemText = item.SubItems[column].Text;

                // Use the initial letter instead if it is the first column.
                if (column == 0)
                {
                    h_subItemText = h_subItemText.Substring(0, 1);
                }

                // If the groups table does not already contain a group
                // for the subItemText value, add a new group using the
                // subItemText value for the group header and Hashtable key.
                if (!h_groups.Contains(h_subItemText))
                {
                    h_groups.Add(h_subItemText, new ListViewGroup(h_subItemText,
                        HorizontalAlignment.Left));
                }
            }

            // Return the Hashtable object.
            return h_groups;
        }
示例#28
0
        public static DataSet GetSubtotalsPerCurrency(int fileid)
        {
            IDalSession session = NHSessionFactory.CreateSession();

            IList orders = OrderMapper.GetOrdersPerExportFile(session, fileid);

            Hashtable currencySubtotals = new Hashtable();
            foreach (IOrder order in orders)
                if (!currencySubtotals.Contains(order.OrderCurrency.Key))
                    currencySubtotals[order.OrderCurrency.Key] = new CurrencySubtotalRowView(order.OrderCurrency);

            foreach (IOrder order in orders)
            {
                CurrencySubtotalRowView currencySubtotalRowView = (CurrencySubtotalRowView)currencySubtotals[order.OrderCurrency.Key];
                currencySubtotalRowView.OrderCount++;
                currencySubtotalRowView.Value += order.EstimatedAmount;
            }

            session.Close();

            CurrencySubtotalRowView[] currencySubtotalRowViews = new CurrencySubtotalRowView[currencySubtotals.Values.Count];
            currencySubtotals.Values.CopyTo(currencySubtotalRowViews, 0);

            return DataSetBuilder.CreateDataSetFromBusinessObjectList(currencySubtotalRowViews, "CurrencyName, OrderCount, Value");
        }
        public static bool GetDisplayName(ref PackageInfo info, string packageName)
        {
            if (dic == null)
            {
                dic = new Hashtable();
                var files = DirectoryUtils.GetFiles($"{Environment.CurrentDirectory}/Library/PackageCache", "package.json", System.IO.SearchOption.AllDirectories);
                foreach (var f in files)
                {
                    var pj = PackageJson.Load(f);

                    dic.Add(pj.name, pj);
                }
            }
            if (dic.Contains(packageName))
            {
                info.displayName = ((PackageJson)dic[packageName]).displayName;
                info.version     = ((PackageJson)dic[packageName]).version;
                if (info.version.StartsWith("http"))
                {
                    info.version = "URL";
                }
                return(true);
            }
            info.displayName = string.Empty;
            info.version     = string.Empty;
            return(false);
        }
示例#30
0
 public static void AddIfNotContains(System.Collections.Hashtable hashtable, System.Object item)
 {
     if (hashtable.Contains(item) == false)
     {
         hashtable.Add(item, item);
     }
 }
示例#31
0
 public void Add(string key, ResourceCacheEntry newEntry)
 {
     if (!m_ResourceHash.Contains(key))
     {
         m_ResourceHash.Add(key, newEntry);
     }
 }
示例#32
0
        public void Visit(Ast.DictNode dict)
        {
            IDictionary obj = new Hashtable(dict.Elements.Count);
            foreach(Ast.KeyValueNode kv in dict.Elements)
            {
                kv.Key.Accept(this);
                object key = generated.Pop();
                kv.Value.Accept(this);
                object value = generated.Pop();
                obj[key] = value;
            }

            if(dictToInstance==null || !obj.Contains("__class__"))
            {
                generated.Push(obj);
            }
            else
            {
                object result = dictToInstance(obj);
                if(result==null)
                    generated.Push(obj);
                else
                    generated.Push(result);
            }
        }
        public void CheckResultIgnoreAllowDBNull(DataSet dataSource)
        {
            Hashtable visited = new Hashtable();
            topo.IgnoreAllowDBNull = true;
            topo.Compute();
            DisplayResults();

            foreach (DataTable table in topo.GetSortedTables())
            {
                Console.WriteLine("Checking table {0}", table.TableName);
                DataTableVertex v = this.graph.GetVertex(table);
                foreach (DataRelationEdge edge in this.graph.InEdges(v))
                {
                    if (edge.Source == v)
                        continue;
                    if (!topo.IgnoreAllowDBNull && !topo.NonNullableRelationEdgePredicate.Test(edge))
                        continue;

                    Assert.IsTrue(visited.Contains(edge.Source),
                        "Table {0} should be before {1}",
                        edge.Source.Table.TableName,
                        v.Table.TableName
                        );
                }
                visited.Add(v, v);
            }
        }
		protected override void Reload () 
		{
			System.Collections.Hashtable ht = new System.Collections.Hashtable ();
			Photo [] photos = query.Store.Query ((Tag [])null, null, null, null);
			
			foreach (Photo p in photos) {
				if (ht.Contains (p.DirectoryPath)) {
					DirectoryAdaptor.Group group = (DirectoryAdaptor.Group) ht [p.DirectoryPath];
					group.Count += 1;
				} else 
					ht [p.DirectoryPath] = new DirectoryAdaptor.Group ();
			}
			
			Console.WriteLine ("Count = {0}", ht.Count);
			dirs = new System.Collections.DictionaryEntry [ht.Count];
			ht.CopyTo (dirs, 0);
			
			Array.Sort (dirs, new DirectoryAdaptor.Group ());
			Array.Sort (query.Photos, new Photo.CompareDirectory ());
			
			if (!order_ascending) {
				Array.Reverse (dirs);
				Array.Reverse (query.Photos);
			}
			
			if (Changed != null)
				Changed (this);
		}
示例#35
0
		static void ExploreSWF(string swfname)
		{
			Stream stream = File.OpenRead(swfname);
			SwfExportTagReader reader = new SwfExportTagReader(new BufferedStream(stream)); 
			Swf swf = reader.ReadSwf(); 
			
			Hashtable tagsSeen = new Hashtable();

			// list tags
			ExportTag export;
			foreach(BaseTag tag in swf)
			{
				export = tag as ExportTag;
				if (export != null)
				{
					foreach(string name in export.Names)
					{
						if (!tagsSeen.Contains(name))
						{
							Console.WriteLine(name);
							tagsSeen.Add(name,true);
						}
					}
				}
			}
		}
 public void ExportFlat()
 {
     Hashtable h = new Hashtable();
  
     h.Add("FirstName", "John");
     h.Add("LastName", "Doe");
     h.Add("MiddleName", null);
     
     JsonReader reader = Export(h);
     
     //
     // We need a complex assertions loop here because the order in 
     // which members are written cannot be guaranteed to follow
     // the order of insertion.
     //
     
     reader.ReadToken(JsonTokenClass.Object);
     while (reader.TokenClass != JsonTokenClass.EndObject)
     {
         string member = reader.ReadMember();
         Assert.IsTrue(h.Contains(member));
     
         object expected = h[member];
         
         if (expected == null)
             reader.ReadNull();
         else
             Assert.AreEqual(expected, reader.ReadString());
     }
 }
        private void CheckForComparisonDelegateLoops(String delegateName)
        {
            String nextDelegateName = delegateName;
            Hashtable alreadyReferencedDelegates = new Hashtable();

            while(true)
            {
                ComparisonEvaluator nextComparisonEvaluator =
                    (ComparisonEvaluator)_comparisonEvaluators[nextDelegateName];
                if(nextComparisonEvaluator == null)
                {
                    break;
                }

                if(alreadyReferencedDelegates.Contains(nextDelegateName))
                {
                    String msg = SR.GetString(SR.DevFiltDict_FoundLoop,
                                              nextComparisonEvaluator.capabilityName,
                                              delegateName);
                    throw new Exception(msg);
                }

                alreadyReferencedDelegates[nextDelegateName] = null;
                nextDelegateName = nextComparisonEvaluator.capabilityName;
            }
        }
 private static void FillCorrelationAliasAttrs(MemberInfo memberInfo, Hashtable correlationAliasAttrs, ValidationErrorCollection validationErrors)
 {
     foreach (object obj2 in memberInfo.GetCustomAttributes(typeof(CorrelationAliasAttribute), false))
     {
         CorrelationAliasAttribute attributeFromObject = Helpers.GetAttributeFromObject<CorrelationAliasAttribute>(obj2);
         if (string.IsNullOrEmpty(attributeFromObject.Name) || (attributeFromObject.Name.Trim().Length == 0))
         {
             ValidationError item = new ValidationError(SR.GetString(CultureInfo.CurrentCulture, "Error_CorrelationAttributeInvalid", new object[] { typeof(CorrelationAliasAttribute).Name, "Name", memberInfo.Name }), 0x150);
             item.UserData.Add(typeof(CorrelationAliasAttribute), memberInfo.Name);
             validationErrors.Add(item);
         }
         else if (string.IsNullOrEmpty(attributeFromObject.Path) || (attributeFromObject.Path.Trim().Length == 0))
         {
             ValidationError error2 = new ValidationError(SR.GetString(CultureInfo.CurrentCulture, "Error_CorrelationAttributeInvalid", new object[] { typeof(CorrelationAliasAttribute).Name, "Path", memberInfo.Name }), 0x150);
             error2.UserData.Add(typeof(CorrelationAliasAttribute), memberInfo.Name);
             validationErrors.Add(error2);
         }
         else if (correlationAliasAttrs.Contains(attributeFromObject.Name))
         {
             ValidationError error3 = new ValidationError(SR.GetString(CultureInfo.CurrentCulture, "Error_DuplicateCorrelationAttribute", new object[] { typeof(CorrelationAliasAttribute).Name, attributeFromObject.Name, memberInfo.Name }), 0x151);
             error3.UserData.Add(typeof(CorrelationAliasAttribute), memberInfo.Name);
             validationErrors.Add(error3);
         }
         else
         {
             correlationAliasAttrs.Add(attributeFromObject.Name, attributeFromObject);
         }
     }
 }
		public void UpdateFromSelection (Photo [] sel)
		{
			Hashtable taghash = new Hashtable ();
	
			for (int i = 0; i < sel.Length; i++) {
				foreach (Tag tag in sel [i].Tags) {
					int count = 1;
	
					if (taghash.Contains (tag))
						count = ((int) taghash [tag]) + 1;
	
					if (count <= i)
						taghash.Remove (tag);
					else 
						taghash [tag] = count;
				}
				
				if (taghash.Count == 0)
					break;
			}
	
			selected_photos_tagnames = new ArrayList ();
			foreach (Tag tag in taghash.Keys)
				if ((int) (taghash [tag]) == sel.Length)
					selected_photos_tagnames.Add (tag.Name);
	
			Update ();
		}
 public void TestClosestEditDistanceMatchComesFirst()
 {
     FuzzyLikeThisQuery flt = new FuzzyLikeThisQuery(10, analyzer);
     flt.AddTerms("smith", "name", 0.3f, 1);
     Query q = flt.Rewrite(searcher.GetIndexReader());
     Hashtable queryTerms = new Hashtable();
     q.ExtractTerms(queryTerms);
     Assert.IsTrue(queryTerms.Contains(new Term("name", "smythe")),"Should have variant smythe");
     Assert.IsTrue(queryTerms.Contains(new Term("name", "smith")), "Should have variant smith");
     Assert.IsTrue(queryTerms.Contains(new Term("name", "smyth")), "Should have variant smyth");
     TopDocs topDocs = searcher.Search(flt, 1);
     ScoreDoc[] sd = topDocs.scoreDocs;
     Assert.IsTrue((sd != null) && (sd.Length > 0), "score docs must match 1 doc");
     Document doc = searcher.Doc(sd[0].doc);
     Assert.AreEqual("2", doc.Get("id"), "Should match most similar not most rare variant");
 }
示例#41
0
        internal static void CheckArrayParameter(ref string[] param, bool checkForNull, bool checkIfEmpty, bool checkForCommas, int maxSize, string paramName)
        {
            if (param == null)
            {
                throw new ArgumentNullException(paramName);
            }

            if (param.Length < 1)
            {
                throw new ArgumentException("Parameter_array_empty, paramName, " + paramName);
            }

            Hashtable values = new Hashtable(param.Length);
            for (int i = param.Length - 1; i >= 0; i--)
            {
                SecUtility.CheckParameter(ref param[i], checkForNull, checkIfEmpty, checkForCommas, maxSize,
                    paramName + "[ " + i.ToString(CultureInfo.InvariantCulture) + " ]");
                if (values.Contains(param[i]))
                {
                    throw new ArgumentException("Parameter_duplicate_array_element, " + paramName + ", " + paramName);
                }
                else
                {
                    values.Add(param[i], param[i]);
                }
            }
        }
示例#42
0
        private static string MaxSubStringWithUniqueChars(string str)
        {
            char[] cArr = str.ToCharArray();
            Hashtable h = new Hashtable();
            h.Clear();
            int n = cArr.Length;
            int begin = 0;
            int j = 0;
            string maxSub = "";
            for (int i = 0; i < n; ++i)
            {
                if (!h.Contains(cArr[i]))
                {
                    h.Add(cArr[i], true);
                    j++;

                }
                else
                {
                    int newSublen = j - begin;
                    if (maxSub.Length < newSublen)
                    {
                        maxSub = str.Substring(begin, j);

                    }
                    begin = i;
                    j = begin + 1;
                    h.Clear();
                }
            }
            return maxSub;
        }
示例#43
0
 /// <summary>
 /// 判断某列是否存在并且有无数据
 /// </summary>
 /// <param name="table"></param>
 /// <param name="reader"></param>
 /// <param name="columnName"></param>
 /// <returns></returns>
 public static bool ReaderExists(System.Collections.Hashtable table, IDataReader reader, string columnName)
 {
     if (table.Contains(columnName.ToLower()) && !Convert.IsDBNull(reader[columnName]))
     {
         return(true);
     }
     return(false);
 }
示例#44
0
 public void Emit_Is_Array(string name)
 {
     if (arrays.Contains(name.ToLower()))
     {
         stream.Write("true");
     }
     else
     {
         stream.Write("false");
     }
 }
示例#45
0
 public static void AddAllIfNotContains(System.Collections.Hashtable hashtable, System.Collections.IList items)
 {
     System.Object item;
     for (int i = 0; i < items.Count; i++)
     {
         item = items[i];
         if (hashtable.Contains(item) == false)
         {
             hashtable.Add(item, item);
         }
     }
 }
示例#46
0
        private void OpenStartupWorld()
        {
            string startupWorldName = null;

            if (Global.worldWindUri != null)
            {
                foreach (string curWorld in availableWorldList.Keys)
                {
                    if (string.Compare(Global.worldWindUri.World, curWorld, true, CultureInfo.InvariantCulture) == 0)
                    {
                        startupWorldName = curWorld;
                        break;
                    }
                }
                if (startupWorldName == null)
                {
                    //	Log.Write(startupWorldName + " - 1");
                    //	MessageBox.Show(this,
                    //		String.Format("Unable to find data for planet '{0}', loading first available planet.", worldWindUri.World));
                    //	throw new UriFormatException(string.Format(CultureInfo.CurrentCulture, "Unable to find data for planet '{0}'.", worldWindUri.World ) );
                }
            }

            if (startupWorldName == null && availableWorldList.Contains(Global.Settings.DefaultWorld))
            {
                startupWorldName = Global.Settings.DefaultWorld;
            }

            if (startupWorldName == null)
            {
                // Pick the first planet found in config
                foreach (string curWorld in availableWorldList.Keys)
                {
                    startupWorldName = curWorld;
                    break;
                }
            }

            if (startupWorldName != null)
            {
                //WorldXmlDescriptor.WorldType worldDescriptor = (WorldXmlDescriptor.WorldType)this.availableWorldList[startupWorldName];
                string curWorldFile = availableWorldList[startupWorldName] as string;
                if (curWorldFile == null)
                {
                    throw new ApplicationException(
                              string.Format(CultureInfo.CurrentCulture, "Unable to load planet {0} configuration file from '{1}'.",
                                            startupWorldName,
                                            Global.Settings.ConfigPath));
                }

                OpenWorld(curWorldFile);
            }
        }
示例#47
0
 //Get method for range required
 public bool GetRangeValueRequired(Control ctl)
 {
     //This makes best use of a hashtable for quick retrieval
     if (CustomProps.Contains(ctl))
     {
         Props p = (Props)CustomProps[ctl];
         SetToolTip(ctl);
         return(p.RangeRequired);
     }
     else
     {
         return(false);
     }
 }
示例#48
0
 void AddFile(string key, string filename)
 {
     if (dmp.Contains(key))
     {
         ((ArrayList)dmp[key]).Add(filename);
     }
     else
     {
         System.Collections.ArrayList al = new ArrayList();
         al.Add(filename);
         dmp.Add(key, al);
     }
 }
示例#49
0
 public static void AddAllIfNotContains(System.Collections.Hashtable hashtable, System.Collections.ICollection items)
 {
     System.Collections.IEnumerator iter = items.GetEnumerator();
     System.Object item;
     while (iter.MoveNext())
     {
         item = iter.Current;
         if (hashtable.Contains(item) == false)
         {
             hashtable.Add(item, item);
         }
     }
 }
示例#50
0
        // Returns a new list of Assembly names consisting of names that
        // haven't already been visited (i.e., they aren't present in the
        // database).
        private IList _minimize(IList l)
        {
            IList r = new ArrayList();

            foreach (AssemblyName an in l)
            {
                if (!m_map.Contains(an.FullName))
                {
                    r.Add(an);
                }
            }
            return(r);
        }
示例#51
0
 public void RemoveFilesFromDownloadQueue(string[] remotefilename)
 {
     foreach (string s in remotefilename)
     {
         if (queue.Contains(s))
         {
             queue.Remove(s);
         }
         else
         {
             throw new Exception("File does not exist: " + s);
         }
     }
 }
示例#52
0
 public static void AddIfNotContains(System.Collections.Hashtable hashtable, System.Object item)
 {
     // Added lock around check.  Even though the collection should already have
     // a synchronized wrapper around it, it doesn't prevent this test from having
     // race conditions.  Two threads can (and have in TestIndexReaderReopen) call
     // hashtable.Contains(item) == false at the same time, then both try to add to
     // the hashtable, causing an ArgumentException.  locking on the collection
     // prevents this. -- cc
     lock (hashtable)
     {
         if (hashtable.Contains(item) == false)
         {
             hashtable.Add(item, item);
         }
     }
 }
示例#53
0
        private object GetTabValue(System.Collections.Hashtable hs, string tabName, string fieldName)
        {
            object result;

            if (hs.Contains(tabName))
            {
                if (!(hs[tabName] is System.Data.DataTable))
                {
                    result = hs[tabName];
                    return(result);
                }
                System.Data.DataTable dataTable = hs[tabName] as System.Data.DataTable;
                if (dataTable.Columns.Contains(fieldName.ToUpper()) && dataTable.Rows.Count > 0)
                {
                    result = dataTable.Rows[0][fieldName.ToUpper()];
                    return(result);
                }
            }
            result = null;
            return(result);
        }
        public static bool GetDisplayName(ref PackageInfo info, string packageName)
        {
            if (dic == null)
            {
                dic = new Hashtable();
                var files = DirectoryUtils.GetFiles($"{EditorApplication.applicationContentsPath}/Resources/PackageManager/BuiltInPackages", "package.json", System.IO.SearchOption.AllDirectories);
                foreach (var f in files)
                {
                    var pj = PackageJson.Load(f);

                    dic.Add(pj.name, pj);
                }
            }
            if (dic.Contains(packageName))
            {
                info.displayName = ((PackageJson)dic[packageName]).displayName;
                info.version     = ((PackageJson)dic[packageName]).version;
                return(true);
            }
            info.displayName = string.Empty;
            info.version     = string.Empty;
            return(false);
        }
示例#55
0
        static Mime()
        {
            ht = new Hashtable(StringComparer.InvariantCultureIgnoreCase);
            string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, MimeFileName);
            Stream s        = null;

            if (File.Exists(fileName))
            {
                s = File.OpenRead(fileName);
            }
            else
            {
                System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
                s = a.GetManifestResourceStream(a.GetName().Name + ".Services.Web.Handlers.MIME.config");
            }

            if (s == null)
            {
                throw new Exception("Can't find MIME mapping!");
            }

            System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
            xd.Load(s);

            System.Xml.XmlNodeList xnl = xd.SelectNodes("mimes/mime");

            string tempExt = null;

            foreach (System.Xml.XmlNode xn in xnl)
            {
                tempExt = xn.Attributes["ext"].InnerText.ToLower();
                if (!ht.Contains(tempExt))
                {
                    ht.Add(tempExt, xn.Attributes["type"].InnerText);
                }
            }
        }
        public static bool GetDisplayName(ref PackageInfo info, string packageName)
        {
            if (dic == null)
            {
                dic = new Hashtable();

                E.Load();
                foreach (var path in E.i.m_dirList)
                {
                    if (path.IsEmpty())
                    {
                        continue;
                    }
                    var files = DirectoryUtils.GetFiles(path, "package.json", System.IO.SearchOption.AllDirectories);
                    foreach (var fname in files)
                    {
                        var pj = PackageJson.Load(fname);
                        if (dic.Contains(pj.name))
                        {
                            Debug.LogWarning($"Duplicate: {pj.name}: {fname}");
                            continue;
                        }

                        dic.Add(pj.name, pj);
                    }
                }
            }
            if (dic.Contains(packageName))
            {
                info.displayName = ((PackageJson)dic[packageName]).displayName;
                info.version     = ((PackageJson)dic[packageName]).version;
                return(true);
            }
            info.displayName = string.Empty;
            info.version     = string.Empty;
            return(false);
        }
示例#57
0
        /// <summary>
        /// Add segment to HL7 message
        /// </summary>
        /// <param name="segment"></param>
        public void AddSegment(Hl7Segment segment)
        {
            ICollection segments           = _segments.Values;
            int         nextSequenceNumber = segments.Count;

            // check if the segment is already present
            if (_segments.Contains(segment.SegmentId.Id) == true)
            {
                // remove the segment
                Hl7Segment tempSegment = (Hl7Segment)_segments[segment.SegmentId.Id];
                _segments.Remove(segment.SegmentId.Id);

                // use the current sequence number
                segment.SequenceNumber = tempSegment.SequenceNumber;
            }
            else
            {
                // check to see if a segment already exists of the same type
                int existingSequenceNumber = 0;
                int nextSegmentIndex       = 0;
                if (GetNextSegmentIndex(segment.SegmentId.SegmentName, out existingSequenceNumber, out nextSegmentIndex) == true)
                {
                    // segment exists - this new one must get the existing sequence number and next segment index
                    segment.SequenceNumber         = existingSequenceNumber;
                    segment.SegmentId.SegmentIndex = nextSegmentIndex;
                }
                else
                {
                    // segment does not exist - simply give it the next sequence number and start the segment index at 1.
                    segment.SequenceNumber         = nextSequenceNumber;
                    segment.SegmentId.SegmentIndex = 1;
                }
            }

            // add the new segment
            _segments.Add(segment.SegmentId.Id, segment);
        }
示例#58
0
        protected override void Reload()
        {
            System.Collections.Hashtable ht = new System.Collections.Hashtable();
            Photo [] photos = query.Store.Query((Tag [])null, null, null, null);

            foreach (Photo p in photos)
            {
                if (ht.Contains(p.DirectoryPath))
                {
                    DirectoryAdaptor.Group group = (DirectoryAdaptor.Group)ht [p.DirectoryPath];
                    group.Count += 1;
                }
                else
                {
                    ht [p.DirectoryPath] = new DirectoryAdaptor.Group();
                }
            }

            Console.WriteLine("Count = {0}", ht.Count);
            dirs = new System.Collections.DictionaryEntry [ht.Count];
            ht.CopyTo(dirs, 0);

            Array.Sort(dirs, new DirectoryAdaptor.Group());
            Array.Sort(query.Photos, new Photo.CompareDirectory());

            if (!order_ascending)
            {
                Array.Reverse(dirs);
                Array.Reverse(query.Photos);
            }

            if (Changed != null)
            {
                Changed(this);
            }
        }
示例#59
0
        /// <summary>
        ///  Gets the properties for a given Com2 Object.  The returned Com2Properties
        ///  Object contains the properties and relevant data about them.
        /// </summary>
        public static Com2Properties GetProperties(object obj)
        {
            Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Com2TypeInfoProcessor.GetProperties");

            if (obj == null || !Marshal.IsComObject(obj))
            {
                Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Com2TypeInfoProcessor.GetProperties returning null: Object is not a com Object");
                return(null);
            }

            UnsafeNativeMethods.ITypeInfo[] typeInfos = FindTypeInfos(obj, false);

            // oops, looks like this guy doesn't surface any type info
            // this is okay, so we just say it has no props
            if (typeInfos == null || typeInfos.Length == 0)
            {
                Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Com2TypeInfoProcessor.GetProperties :: Didn't get typeinfo");
                return(null);
            }

            int       defaultProp = -1;
            int       temp        = -1;
            ArrayList propList    = new ArrayList();

            Guid[] typeGuids = new Guid[typeInfos.Length];

            for (int i = 0; i < typeInfos.Length; i++)
            {
                UnsafeNativeMethods.ITypeInfo ti = typeInfos[i];

                if (ti == null)
                {
                    continue;
                }

                int[] versions             = new int[2];
                Guid  typeGuid             = GetGuidForTypeInfo(ti, versions);
                PropertyDescriptor[] props = null;
                bool dontProcess           = typeGuid != Guid.Empty && processedLibraries != null && processedLibraries.Contains(typeGuid);

                if (dontProcess)
                {
                    CachedProperties cp = (CachedProperties)processedLibraries[typeGuid];

                    if (versions[0] == cp.MajorVersion && versions[1] == cp.MinorVersion)
                    {
                        props = cp.Properties;
                        if (i == 0 && cp.DefaultIndex != -1)
                        {
                            defaultProp = cp.DefaultIndex;
                        }
                    }
                    else
                    {
                        dontProcess = false;
                    }
                }

                if (!dontProcess)
                {
                    props = InternalGetProperties(obj, ti, Ole32.DispatchID.MEMBERID_NIL, ref temp);

                    // only save the default property from the first type Info
                    if (i == 0 && temp != -1)
                    {
                        defaultProp = temp;
                    }

                    if (processedLibraries == null)
                    {
                        processedLibraries = new Hashtable();
                    }

                    if (typeGuid != Guid.Empty)
                    {
                        processedLibraries[typeGuid] = new CachedProperties(props, i == 0 ? defaultProp : -1, versions[0], versions[1]);
                    }
                }

                if (props != null)
                {
                    propList.AddRange(props);
                }
            }

            Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Com2TypeInfoProcessor.GetProperties : returning " + propList.Count.ToString(CultureInfo.InvariantCulture) + " properties");

            // done!
            Com2PropertyDescriptor[] temp2 = new Com2PropertyDescriptor[propList.Count];
            propList.CopyTo(temp2, 0);

            return(new Com2Properties(obj, temp2, defaultProp));
        }
示例#60
0
        private void m_UpdateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                System.DateTime updateStart = System.DateTime.Now;

                for (int i = 0; i < m_WorldWindow.CurrentWorld.RenderableObjects.Count; i++)
                {
                    WorldWind.Renderable.RenderableObject curRo = (WorldWind.Renderable.RenderableObject)m_WorldWindow.CurrentWorld.RenderableObjects.ChildObjects[i];
                    if (i >= this.treeView1.Nodes.Count)
                    {
                        // Add a node
                        TreeNode             correctNode = new TreeNode(curRo.Name);
                        RenderableObjectInfo curRoi      = new RenderableObjectInfo();
                        curRoi.Renderable = curRo;
                        correctNode.Tag   = curRoi;

                        m_NodeHash.Add(correctNode.Text, correctNode);
                        this.treeView1.BeginInvoke(new AddTableTreeDelegate(this.AddTableTree), new object[] { correctNode });
                        updateNode(correctNode);
                    }
                    else
                    {
                        //compare nodes
                        TreeNode curTn = this.treeView1.Nodes[i];

                        RenderableObjectInfo curRoi = (RenderableObjectInfo)curTn.Tag;
                        if (curRoi.Renderable != null && curRoi.Renderable.Name == curRo.Name)
                        {
                            updateNode(curTn);
                            continue;
                        }
                        else
                        {
                            if (!m_NodeHash.Contains(curRo.Name))
                            {
                                //add it
                                curRoi            = new RenderableObjectInfo();
                                curRoi.Renderable = curRo;
                                curTn             = new TreeNode(curRo.Name);
                                curTn.Tag         = curRoi;

                                m_NodeHash.Add(curTn.Text, curTn);
                                this.treeView1.BeginInvoke(new InsertTableTreeDelegate(this.InsertTableTree), new object[] { i, curTn });
                            }
                            else
                            {
                                curTn = (TreeNode)m_NodeHash[curRo.Name];
                                try
                                {
                                    treeView1.BeginInvoke(new RemoveTableTreeDelegate(this.RemoveTableTree), new object[] { curTn });
                                }
                                catch
                                {}

                                treeView1.BeginInvoke(new InsertTableTreeDelegate(this.InsertTableTree), new object[] { i, curTn });
                            }
                        }

                        updateNode(curTn);
                    }
                }

                for (int i = m_WorldWindow.CurrentWorld.RenderableObjects.Count; i < this.treeView1.Nodes.Count; i++)
                {
                    this.treeView1.BeginInvoke(new RemoveAtTableTreeDelegate(this.RemoveAtTableTree), new object[] { i });
                }

                System.Collections.ArrayList deletionList = new ArrayList();
                foreach (TreeNode tn in m_NodeHash.Values)
                {
                    RenderableObjectInfo roi = (RenderableObjectInfo)tn.Tag;
                    if (roi == null || roi.Renderable == null || roi.LastSpotted < updateStart)
                    {
                        deletionList.Add(GetAbsoluteRenderableObjectPath(roi.Renderable));
                    }
                }

                foreach (string key in deletionList)
                {
                    m_NodeHash.Remove(key);
                }
            }
            catch
            {}
        }