Clear() public méthode

public Clear ( ) : void
Résultat void
		private static void ReadMap(StringDictionary map, TextReader reader, string mapName)
		{
			map.Clear();

			var mappings = reader.ReadLine().Replace(string.Format("{0}:", mapName), string.Empty).Split(new[] {';'},
			                                                                                             StringSplitOptions.
			                                                                                             	RemoveEmptyEntries);

			foreach (string mapping in mappings)
			{
				string[] parts = mapping.Split(new[] {':'}, StringSplitOptions.RemoveEmptyEntries);
				map.Add(parts[0], parts[1]);
			}
		}
        public static void Main()
        {
            // Creates and initializes a new StringDictionary.
            StringDictionary myCol = new StringDictionary();
            myCol.Add("red", "rojo");
            myCol.Add("green", "verde");
            myCol.Add("blue", "azul");
            Console.WriteLine("Count:    {0}", myCol.Count);

            // Display the contents of the collection using foreach. This is the preferred method.
            Console.WriteLine("Displays the elements using foreach:");
            PrintKeysAndValues1(myCol);

            // Display the contents of the collection using the enumerator.
            Console.WriteLine("Displays the elements using the IEnumerator:");
            PrintKeysAndValues2(myCol);

            // Display the contents of the collection using the Keys, Values, Count, and Item properties.
            Console.WriteLine("Displays the elements using the Keys, Values, Count, and Item properties:");
            PrintKeysAndValues3(myCol);

            // Copies the StringDictionary to an array with DictionaryEntry elements.
            DictionaryEntry[] myArr = new DictionaryEntry[myCol.Count];
            myCol.CopyTo(myArr, 0);

            // Displays the values in the array.
            Console.WriteLine("Displays the elements in the array:");
            Console.WriteLine("   KEY        VALUE");
            for (int i = 0; i < myArr.Length; i++)
                Console.WriteLine("   {0,-10} {1}", myArr[i].Key, myArr[i].Value);
            Console.WriteLine();

            // Searches for a value.
            if (myCol.ContainsValue("amarillo"))
                Console.WriteLine("The collection contains the value \"amarillo\".");
            else
                Console.WriteLine("The collection does not contain the value \"amarillo\".");
            Console.WriteLine();

            // Searches for a key and deletes it.
            if (myCol.ContainsKey("green"))
                myCol.Remove("green");
            Console.WriteLine("The collection contains the following elements after removing \"green\":");
            PrintKeysAndValues1(myCol);

            // Clears the entire collection.
            myCol.Clear();
            Console.WriteLine("The collection contains the following elements after it is cleared:");
            PrintKeysAndValues1(myCol);
        }
		public void Empty ()
		{
			StringDictionary sd = new StringDictionary ();
			Assert.AreEqual (0, sd.Count, "Count");
			Assert.IsFalse (sd.IsSynchronized, "IsSynchronized");
			Assert.AreEqual (0, sd.Keys.Count, "Keys");
			Assert.AreEqual (0, sd.Values.Count, "Values");
			Assert.IsNotNull (sd.SyncRoot, "SyncRoot");
			Assert.IsFalse (sd.ContainsKey ("a"), "ContainsKey");
			Assert.IsFalse (sd.ContainsValue ("1"), "ContainsValue");
			sd.CopyTo (new DictionaryEntry[0], 0);
			Assert.IsNotNull (sd.GetEnumerator (), "GetEnumerator");
			sd.Remove ("a"); // doesn't exists
			sd.Clear ();
		}
Exemple #4
0
        /// <summary>
        /// Copy elements from a Python mapping of dict environment variables to a StringDictionary.
        /// </summary>
        private static void SetEnvironment(StringDictionary currentEnvironment, object newEnvironment)
        {
            Dict env = newEnvironment as Dict;
            if (env == null) {
                throw Ops.TypeError("env argument must be a dict");
            }

            currentEnvironment.Clear();

            string strKey, strValue;
            foreach (object key in env.Keys) {
                if (!Converter.TryConvertToString(key, out strKey)) {
                    throw Ops.TypeError("env dict contains a non-string key");
                }
                if (!Converter.TryConvertToString(env[key], out strValue)) {
                    throw Ops.TypeError("env dict contains a non-string value");
                }
                currentEnvironment[strKey] = strValue;
            }
        }
Exemple #5
0
        public void Test01()
        {
            IntlStrings intl;
            StringDictionary sd;
            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aa",
                "text",
                "     spaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "one",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            int cnt = 0;
            // initialize IntStrings
            intl = new IntlStrings();


            // [] StringDictionary is constructed as expected
            //-----------------------------------------------------------------

            sd = new StringDictionary();

            // [] Remove() from empty dictionary
            //
            if (sd.Count > 0)
                sd.Clear();

            for (int i = 0; i < keys.Length; i++)
            {
                sd.Remove(keys[0]);
            }

            // [] Remove() from filled dictionary
            //
            int len = values.Length;
            sd.Clear();
            for (int i = 0; i < len; i++)
            {
                sd.Add(keys[i], values[i]);
            }
            if (sd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
            }

            for (int i = 0; i < len; i++)
            {
                cnt = sd.Count;
                sd.Remove(keys[i]);

                if (sd.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, didn't remove element with {0} key", i));
                }

                // verify that indeed element with given key was removed
                if (sd.ContainsValue(values[i]))
                {
                    Assert.False(true, string.Format("Error, removed wrong value", i));
                }
                if (sd.ContainsKey(keys[i]))
                {
                    Assert.False(true, string.Format("Error, removed wrong value", i));
                }
            }


            //
            // [] Remove() on dictionary with identical values
            //

            sd.Clear();
            string intlStr = intl.GetRandomString(MAX_LEN);

            sd.Add("keykey1", intlStr);        // 1st duplicate
            for (int i = 0; i < len; i++)
            {
                sd.Add(keys[i], values[i]);
            }
            sd.Add("keykey2", intlStr);        // 2nd duplicate
            if (sd.Count != len + 2)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len + 2));
            }

            // remove
            //
            sd.Remove("keykey2");
            if (!sd.ContainsValue(intlStr))
            {
                Assert.False(true, string.Format("Error, removed both duplicates"));
            }
            // second string should still be present
            if (sd.ContainsKey("keykey2"))
            {
                Assert.False(true, string.Format("Error, removed not given instance"));
            }
            if (!sd.ContainsKey("keykey1"))
            {
                Assert.False(true, string.Format("Error, removed wrong instance"));
            }

            //
            // Intl strings
            // [] Remove() from dictionary filled with Intl strings
            //

            string[] intlValues = new string[len * 2];
            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }

            //
            // will use first half of array as values and second half as keys
            //
            sd.Clear();
            for (int i = 0; i < len; i++)
            {
                sd.Add(intlValues[i + len], intlValues[i]);
            }
            if (sd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
            }

            // remove
            for (int i = 0; i < len; i++)
            {
                cnt = sd.Count;
                sd.Remove(intlValues[i + len]);

                if (sd.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, didn't remove element with {0} key", i + len));
                }

                // verify that indeed element with given key was removed
                if (sd.ContainsValue(intlValues[i]))
                {
                    Assert.False(true, string.Format("Error, removed wrong value", i));
                }
                if (sd.ContainsKey(intlValues[i + len]))
                {
                    Assert.False(true, string.Format("Error, removed wrong key", i));
                }
            }

            //
            // [] Case sensitivity: keys are always lowercased
            //

            sd.Clear();

            string[] intlValuesUpper = new string[len];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                intlValues[i] = intlValues[i].ToLowerInvariant();
            }

            // array of uppercase keys
            for (int i = 0; i < len; i++)
            {
                intlValuesUpper[i] = intlValues[i + len].ToUpperInvariant();
            }

            sd.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                sd.Add(intlValues[i + len], intlValues[i]);     // adding lowercase strings
            }
            if (sd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
            }

            // remove
            for (int i = 0; i < len; i++)
            {
                cnt = sd.Count;
                sd.Remove(intlValuesUpper[i]);

                if (sd.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, didn't remove element with {0} lower key", i + len));
                }

                // verify that indeed element with given key was removed
                if (sd.ContainsValue(intlValues[i]))
                {
                    Assert.False(true, string.Format("Error, removed wrong value", i));
                }
                if (sd.ContainsKey(intlValuesUpper[i]))
                {
                    Assert.False(true, string.Format("Error, removed wrong key", i));
                }
            }

            //
            // [] Invalid parameter
            //
            Assert.Throws<ArgumentNullException>(() => { sd.Remove(null); });
        }
		public void SomeElements ()
		{
			StringDictionary sd = new StringDictionary ();
			for (int i = 0; i < 10; i++)
				sd.Add (i.ToString (), (i * 10).ToString ());
			Assert.AreEqual ("10", sd["1"], "this[1]");
			Assert.AreEqual (10, sd.Count, "Count-10");
			Assert.AreEqual (10, sd.Keys.Count, "Keys");
			Assert.AreEqual (10, sd.Values.Count, "Values");
			Assert.IsTrue (sd.ContainsKey ("2"), "ContainsKey");
			Assert.IsTrue (sd.ContainsValue ("20"), "ContainsValue");
			DictionaryEntry[] array = new DictionaryEntry[10];
			sd.CopyTo (array, 0);
			sd.Remove ("1");
			Assert.AreEqual (9, sd.Count, "Count-9");
			sd.Clear ();
			Assert.AreEqual (0, sd.Count, "Count-0");
		}
        public void Test01()
        {
            IntlStrings intl;
            StringDictionary sd;
            string ind;
            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aa",
                "text",
                "     spaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "one",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            int cnt = 0;            // Count
            // initialize IntStrings
            intl = new IntlStrings();


            // [] StringDictionary is constructed as expected
            //-----------------------------------------------------------------

            sd = new StringDictionary();

            //  [] check for empty dictionary
            //
            for (int i = 0; i < values.Length; i++)
            {
                if (sd.ContainsKey(keys[i]))
                {
                    Assert.False(true, string.Format("Error, returned true for empty dictionary", i));
                }
            }


            // [] add simple strings and verify ContainsKey()
            //

            cnt = values.Length;
            for (int i = 0; i < cnt; i++)
            {
                sd.Add(keys[i], values[i]);
            }
            if (sd.Count != cnt)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, cnt));
            }

            for (int i = 0; i < cnt; i++)
            {
                // verify that collection contains all added items
                //
                if (!sd.ContainsValue(values[i]))
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain value \"{1}\"", i, values[i]));
                }
                if (!sd.ContainsKey(keys[i]))
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain key \"{1}\"", i, keys[i]));
                }
            }

            //
            // Intl strings
            // [] add Intl strings and verify ContainsKey()
            //

            int len = values.Length;
            string[] intlValues = new string[len * 2];
            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }

            Boolean caseInsensitive = false;
            for (int i = 0; i < len * 2; i++)
            {
                if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
                    caseInsensitive = true;
            }


            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                cnt = sd.Count;

                sd.Add(intlValues[i + len], intlValues[i]);
                if (sd.Count != cnt + 1)
                {
                    Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1));
                }

                // verify that collection contains newly added item
                //
                if (!sd.ContainsValue(intlValues[i]))
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i));
                }

                if (!sd.ContainsKey(intlValues[i + len]))
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
                }

                //  access the item
                //
                ind = intlValues[i + len];
                if (String.Compare(sd[ind], intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, sd[ind], intlValues[i]));
                }
            }

            //
            // add null string with non-null key
            // [] add null string with non-null key and verify ContainsKey()
            //
            cnt = sd.Count;
            string k = "keykey";

            sd.Add(k, null);
            if (sd.Count != cnt + 1)
            {
                Assert.False(true, string.Format("Error, count is {1} instead of {2}", sd.Count, cnt + 1));
            }

            // verify that collection contains newly added item
            //
            if (!sd.ContainsKey(k))
            {
                Assert.False(true, string.Format("Error, dictionary doesn't contain new key"));
            }

            //
            // [] Case sensitivity: search should be case-sensitive
            //

            sd.Clear();
            if (sd.Count != 0)
            {
                Assert.False(true, string.Format("Error, count is {1} instead of {2} after Clear()", sd.Count, 0));
            }

            string[] intlValuesLower = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                intlValues[i] = intlValues[i].ToUpperInvariant();
            }

            for (int i = 0; i < len * 2; i++)
            {
                intlValuesLower[i] = intlValues[i].ToLowerInvariant();
            }

            sd.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                cnt = sd.Count;

                sd.Add(intlValues[i + len], intlValues[i]);     // adding uppercase strings
                if (sd.Count != cnt + 1)
                {
                    Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1));
                }

                // verify that collection contains newly added uppercase item
                //
                if (!sd.ContainsValue(intlValues[i]))
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i));
                }

                if (!sd.ContainsKey(intlValues[i + len]))
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
                }

                // verify that collection doesn't contains lowercase item
                //
                if (!caseInsensitive && sd.ContainsValue(intlValuesLower[i]))
                {
                    Assert.False(true, string.Format("Error, collection contains lowercase value of new item", i));
                }

                // key is case insensitive
                if (!sd.ContainsKey(intlValuesLower[i + len]))
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain lowercase key of new item", i));
                }
            }

            //
            // call ContainsKey with null - ArgumentNullException expected
            // [] ContainsKey (null)
            //
            Assert.Throws<ArgumentNullException>(() => { sd.ContainsKey(null); });
        }
 private static void CleanEnvironmentVariables(StringDictionary variables)
 {
     variables.Clear();
     variables[EnvironmentSystemDrive] = System.Environment.GetEnvironmentVariable(EnvironmentSystemDrive);
     variables[EnvironmentSystemRoot] = System.Environment.GetEnvironmentVariable(EnvironmentSystemRoot);
     variables[EnvironmentPath] = System.Environment.SystemDirectory;
     variables[EnvironmentTemp] = System.Environment.GetEnvironmentVariable(EnvironmentTemp);
 }
Exemple #9
0
		public void setSQLTableDefaults(string table, ref StringDictionary sql)
		{
			//sql = new StringDictionary();
			
			sql.Clear();				

			
			if (table == "SCAPersona")
			{
				// Setting SCAPersona defaults
				
				sql.Add("Tipo","2");		
				sql.Add("Referencia", "NULL");
				sql.Add("Apellido1", "NULL");
				sql.Add("Apellido2", "NULL");
				
				// Field fields (not used)
				foreach (string key in field_keys)
				{
					sql.Add(key, "NULL");
				}
				
				// Alta
				sql.Add("Alta", DateTime.Now.ToString ("yyyyMMdd HH:mm"));
			}
			else if (table == "SCAMuestra")
			{
				string data = DateTime.Now.ToString("yyyyMMdd");
				string hora = DateTime.Now.ToShortTimeString();

				// Setting SCAMuestra defaults
				
				sql.Add("IdEspecie", "NULL");
				sql.Add("IdCentro", "1");
				sql.Add("IdDoctor", "1");
				sql.Add("FechaAnalisis", data);
				sql.Add("HoraAnalisis", hora);
				sql.Add("Volumen", "2.5");
				sql.Add("FechaObtencion", data);
				sql.Add("HoraObtencion", hora);
				sql.Add("HoraEntrega", hora);
				sql.Add("IdMetodoObtencion", "1");
				sql.Add("DiasAbstinencia", "3");
				sql.Add("pH", "7.5");
				sql.Add("Temperatura", "37");
				sql.Add("IdColor", "1");
				sql.Add("IdViscosidad", "1");
				sql.Add("IdLicuefaccion", "1");
				sql.Add("IdAspecto", "1");
				sql.Add("IdOlor", "1");
				sql.Add("IdAglutinaciones", "1");
				sql.Add("IdOtrasPropiedades", "1");
				sql.Add("Observaciones", "NULL");
				sql.Add("local", "1");
				sql.Add("Other", "NULL");
				sql.Add("Confirmed", "0");
				sql.Add("IdCollection1", "1");
				sql.Add("IdCollection2", "1");
				
				// Optional fields (not used)
				foreach (string key in optional_keys)
				{
					sql.Add(key, "NULL");
				}
			}
		}
Exemple #10
0
		public bool fromXLStoSQL(string filePath)
		{
			Logger.Debug(filePath);
			FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
		
			IExcelDataReader excelReader = null;
			
			if (filePath.EndsWith("xls"))
			{
				Logger.Debug("Reading from a binary Excel file ('97-2003 format; *.xls)");
				excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
			}
			else if (filePath.EndsWith("xlsx"))
			{
				Logger.Debug("Reading from a OpenXml Excel file (2007 format; *.xlsx)");
				excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
			}
			else
			{
				// wrong file extension (can't happen, but...)
			
				stream.Close();
				return false;
			}
			
			while (excelReader != null && excelReader.Read())
			{
				int numColumns = excelReader.FieldCount;
	
				// Logger.Debug("Found " + numColumns + " columns in excel file");
				
				if (numColumns < 2 || numColumns > 3)
				{
					// file format not supported
					excelReader.Close();
					stream.Close();
					return false;
				}
			
				string [] columns = new string [numColumns];

				try
				{
					for (int i=0; i<numColumns; i++)
					{
						columns[i] = excelReader.GetString(i);
						// Logger.Debug("Column " + i.ToString() + ": " + columns[i]);
					}
				}
				catch(Exception e)
				{
					Logger.Fatal("Can't read xls file: " + e.ToString());
					excelReader.Close();
					stream.Close();
					return false;
				}

				string nom = null;
				string nhc = null;
				string referencia = null;
				
				if (numColumns >= 3)
				{
					referencia = columns[0];
					nhc = columns[1];
					nom = columns[2];
				}
				else
				{
					nhc = columns[0];
					nom = columns[1];
				}
								
				if (nom != null && nhc != null)
				{
					StringDictionary sql = new StringDictionary();
						
					setSQLTableDefaults("SCAPersona", ref sql);

					sql.Add("Nombre", nom);
					sql.Add("Nombre1", nom);
					sql.Add("NHC", nhc);
					
					int lastInsertRowId = -1;
					
					if (storeSQL("SCAPersona", sql, ref lastInsertRowId) == false)
					{
						excelReader.Close();
						stream.Close();
						return false;
					}
					
					if (numColumns >= 3 && referencia != null && lastInsertRowId != -1)
					{
						/*
						Si el xls té tres columnes, a part d’emplenar
						la taula SCAPersona tal i com ja ho fa,
						hauries d’emplenar també la taula SCAMuestra
						on la primera columna seria la referencia de la mostra.
						Tots els altres camps de SCAMuestra els hauries de posar
						amb un valor per defecte
						*/
						
						sql.Clear();
	
						setSQLTableDefaults("SCAMuestra", ref sql);
						
						sql.Add("Referencia", referencia);
						sql.Add("IdPersona", lastInsertRowId.ToString());
						
						if (storeSQL("SCAMuestra", sql)  == false)
						{
							excelReader.Close();
							stream.Close();
							return false;
						}
					}
				}
				else
				{
					Logger.Debug("Empty fields or wrong number of them. Going to next row.");
				}
			}

			excelReader.Close();	
			stream.Close();

			return true;
		}
Exemple #11
0
        public void Test01()
        {
            IntlStrings intl;
            StringDictionary sd;
            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aa",
                "text",
                "     spaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "one",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            int cnt = 0;            // Count
            string ind;            // key
            // initialize IntStrings
            intl = new IntlStrings();


            // [] StringDictionary is constructed as expected
            //-----------------------------------------------------------------

            sd = new StringDictionary();

            // [] Add() simple strings
            //
            for (int i = 0; i < values.Length; i++)
            {
                cnt = sd.Count;
                sd.Add(keys[i], values[i]);
                if (sd.Count != cnt + 1)
                {
                    Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1));
                }

                // verify that collection contains newly added item
                //
                if (!sd.ContainsValue(values[i]))
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i));
                }

                if (!sd.ContainsKey(keys[i]))
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
                }

                //  access the item
                //
                if (String.Compare(sd[keys[i]], values[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, sd[keys[i]], values[i]));
                }
            }

            //
            // Intl strings
            // [] Add() Intl strings
            //
            int len = values.Length;
            string[] intlValues = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }

            Boolean caseInsensitive = false;
            for (int i = 0; i < len * 2; i++)
            {
                if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
                    caseInsensitive = true;
            }

            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                cnt = sd.Count;

                sd.Add(intlValues[i + len], intlValues[i]);
                if (sd.Count != cnt + 1)
                {
                    Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1));
                }

                // verify that collection contains newly added item
                //
                if (!sd.ContainsValue(intlValues[i]))
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i));
                }

                if (!sd.ContainsKey(intlValues[i + len]))
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
                }

                //  access the item
                //
                ind = intlValues[i + len];
                if (String.Compare(sd[ind], intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, sd[ind], intlValues[i]));
                }
            }

            //
            // [] Case sensitivity
            //
            string[] intlValuesLower = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                intlValues[i] = intlValues[i].ToUpperInvariant();
            }

            for (int i = 0; i < len * 2; i++)
            {
                intlValuesLower[i] = intlValues[i].ToLowerInvariant();
            }

            sd.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                cnt = sd.Count;

                sd.Add(intlValues[i + len], intlValues[i]);
                if (sd.Count != cnt + 1)
                {
                    Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1));
                }

                // verify that collection contains newly added uppercase item
                //
                if (!sd.ContainsValue(intlValues[i]))
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i));
                }

                if (!sd.ContainsKey(intlValues[i + len]))
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
                }

                // verify that collection doesn't contains lowercase item
                //
                if (!caseInsensitive && sd.ContainsValue(intlValuesLower[i]))
                {
                    Assert.False(true, string.Format("Error, collection contains lowercase value of new item", i));
                }

                // key is case insensitive
                if (!sd.ContainsKey(intlValuesLower[i + len]))
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain lowercase key of new item", i));
                }
            }

            //
            // [] Add (string, null)
            //

            cnt = sd.Count;
            sd.Add("keykey", null);

            if (sd.Count != cnt + 1)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, cnt + 1));
            }

            // verify that collection contains null
            //
            if (!sd.ContainsValue(null))
            {
                Assert.False(true, string.Format("Error, collection doesn't contain null"));
            }

            // access item-null
            //
            if (sd["keykey"] != null)
            {
                Assert.False(true, string.Format("Error, returned non-null on place of null"));
            }

            //
            // Add item with null key - ArgumentNullException expected
            // [] Add (null, string)
            //
            Assert.Throws<ArgumentNullException>(() => { sd.Add(null, "item"); });

            //
            // Add duplicate key item - ArgumentException expected
            // [] Add duplicate key item
            //

            // generate key
            string k = intl.GetRandomString(MAX_LEN);
            if (!sd.ContainsKey(k))
            {
                sd.Add(k, "newItem");
            }
            if (!sd.ContainsKey(k))
            {
                Assert.False(true, string.Format("Error,failed to add item"));
            }
            else
            {
                Assert.Throws<ArgumentException>(() => { sd.Add(k, "itemitemitem"); });
            }
        }
Exemple #12
0
        public void Test01()
        {
            IntlStrings intl;
            StringDictionary sd;
            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aa",
                "text",
                "     spaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "one",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            int cnt = 0;            // Count
            // initialize IntStrings
            intl = new IntlStrings();


            // [] StringDictionary is constructed as expected
            //-----------------------------------------------------------------

            sd = new StringDictionary();
            cnt = sd.Count;
            if (cnt != 0)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1} after default ctor", sd.Count, 0));
            }

            // [] Clear() empty dictionary
            //
            sd.Clear();
            cnt = sd.Count;
            if (cnt != 0)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1} after Clear()", sd.Count, 0));
            }


            // [] Add simple strings and Clear()
            //
            cnt = sd.Count;
            for (int i = 0; i < values.Length; i++)
            {
                sd.Add(keys[i], values[i]);
            }
            if (sd.Count != values.Length)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, values.Length));
            }

            sd.Clear();
            cnt = sd.Count;
            if (cnt != 0)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1} after Clear()", sd.Count, 0));
            }


            //
            // [] Add Intl strings and Clear()
            //
            int len = values.Length;
            string[] intlValues = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }

            //   Add items
            //
            cnt = sd.Count;
            for (int i = 0; i < len; i++)
            {
                sd.Add(intlValues[i + len], intlValues[i]);
            }
            if (sd.Count != (cnt + len))
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, cnt + len));
            }

            sd.Clear();
            cnt = sd.Count;
            if (cnt != 0)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1} after Clear()", sd.Count, 0));
            }
        }
Exemple #13
0
        /// <summary>         /// 下载         
        /// </summary>        
        //private static bool DownLoadSoft(string DownloadPath, string FullFilePath, string FileName)
        //{
        //    string path = DownloadPath.Remove(DownloadPath.Length - 1);
        //    bool flag = false;           
        //    try
        //    { 
        //        if (!Directory.Exists(path))
        //        {
        //            Directory.CreateDirectory(path);
        //        }
        //        using (FileStream fs = new FileStream(DownloadPath + FileName, FileMode.Create, FileAccess.Write)) 
        //        {
        //            //创建请求                     
        //            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FullFilePath);
        //            //接收响应 
        //            HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
        //            //输出流
        //            Stream responseStream = response.GetResponseStream();
        //            byte[] bufferBytes = new byte[10000];//缓冲字节数组 
        //            int bytesRead = -1;
        //            while ((bytesRead = responseStream.Read(bufferBytes, 0, bufferBytes.Length)) > 0)
        //            {
        //                fs.Write(bufferBytes, 0, bytesRead); 
        //            }       
        //            if (fs.Length>0)      
        //            {                   
        //                flag = true;            
        //            }                    
        //            //关闭写入         
        //            fs.Flush();          
        //            fs.Close();         
        //        }            
        //    }            
        //    catch (Exception exp)   
        //    {                 //返回错误消息  
        //    }            
        //    return flag;       
        //}


        /// <summary>
        /// 人员调动数据更新
        /// </summary>
        /// <param name="AttendDate"></param>
        /// <param name="JobForID"></param>
        /// <param name="ProjectID"></param>
        /// <param name="LineID"></param>
        /// <param name="TeamID"></param>
        /// <param name="UserID"></param>
        /// <param name="pFlag">调动类型</param>
        /// <returns></returns>
        public static int SetTeamChangeSQL(string AttendDate, string JobForID, string ProjectID, string LineID, string TeamID,string UserID,string pFlag)
        {
            int result = 0;
            try
            {
                StringDictionary dicItemName = new StringDictionary();
                StringDictionary dicPrimarName = new StringDictionary();
                string str_sql = string.Empty;
                DataTable dt_temp=new DataTable();

                //删除Attend_Total_Result表中对应UserID的信息
                str_sql = string.Format(@"DELETE t1 FROM Attend_Total_Result t1  WHERE t1.AttendDate=convert(VARCHAR(10),'{0}') 
                                               AND t1.JobForID='{1}' AND t1.ProjectID='{2}' AND t1.LineID='{3}' AND t1.TeamID='{4}' AND t1.UserID='{5}'",
                                               AttendDate, JobForID, ProjectID, LineID, TeamID, UserID);
                dicItemName["AttendDate"]=AttendDate;
                dicItemName["JobForID"]=JobForID;
                dicItemName["ProjectID"]=ProjectID;
                dicItemName["LineID"]=LineID;
                dicItemName["TeamID"]=TeamID;
                dicItemName["UserID"]=UserID;
                dicPrimarName["AttendDate"] = "true";
                dicPrimarName["JobForID"] = "true";
                dicPrimarName["ProjectID"] = "true";
                dicPrimarName["LineID"] = "true";
                dicPrimarName["TeamID"] = "true";
                dicPrimarName["UserID"] = "true";
                result=SysParam.m_daoCommon.SetDeleteDataItem("Attend_Total_Result", dicItemName, dicPrimarName);

                //查询V_Attend_Move_i表的人员调动情况并且在V_Produce_User是在职人员,向别班别线别班别都相同
                str_sql = string.Format(@"select distinct
                                              H2.ID,H2.UserID,H2.UserName,H1.Sex,H2.JobForID,
                                              H2.ProjectID,H2.LineID,H2.TeamID,H2.GuanweiID,H2.GuanweiSite , 
                                              H2.StrDate,H2.EndDate,H2.MoveStatus,
                                              ISNULL(H1.AttendUnit,0) AS AttendUnit,H1.StatusNames AS AttendType,'' AS AttendMemo,H1.StatusIDs,
                                              H1.StatusNames,H2.OperID
                                             FROM V_Attend_Move_i H2
                                              LEFT JOIN V_Produce_User H1  --调动视图
                                              ON H2.UserID=H1.UserID --向别
                                                AND H2.ProjectID=H1.ProjectID AND H2.LineID=H1.LineID AND H2.TeamID=H1.TeamID AND H1.User_Status='在职'
                                             where 1=1
                                                AND H2.PFlag in ('{0}') 
                                                AND CONVERT(VARCHAR(10), H2.EndDate,120) ='4000-01-01'  and H2.UserID='{1}'",
                                             pFlag,UserID);
                dt_temp=SysParam.m_daoCommon.GetTableInfoBySqlNoWhere(str_sql);
                if (dt_temp.Rows.Count > 0)
                {
                    //将查询到的V_Attend_Move_i表中的数据插入到Attend_Total_Result
                    dicItemName.Clear();
                    dicPrimarName.Clear();
                    dicItemName["AttendDate"] = AttendDate;
                    dicItemName["UserID"] = dt_temp.Rows[0]["UserID"].ToString();
                    dicItemName["UserNM"] = dt_temp.Rows[0]["UserNM"].ToString();
                    dicItemName["Sex"] = dt_temp.Rows[0]["Sex"].ToString();
                    dicItemName["JobForID"] = dt_temp.Rows[0]["JobForID"].ToString();
                    dicItemName["ProjectID"] = dt_temp.Rows[0]["ProjectID"].ToString();
                    dicItemName["LineID"] = dt_temp.Rows[0]["LineID"].ToString();
                    dicItemName["TeamID"] = dt_temp.Rows[0]["TeamID"].ToString();
                    dicItemName["GuanweiID"] = dt_temp.Rows[0]["GuanweiID"].ToString();
                    dicItemName["GuanweiSite"] = dt_temp.Rows[0]["GuanweiSite"].ToString();
                    dicItemName["TeamSetID"] = dt_temp.Rows[0]["TeamSetID"].ToString();
                    dicItemName["AttendType"] = dt_temp.Rows[0]["AttendType"].ToString();
                    dicItemName["AttendMemo"] = dt_temp.Rows[0]["AttendMemo"].ToString();
                    dicItemName["CardTime"] = "";
                    dicItemName["LastDate"] = "";
                    dicItemName["AttendWork"] = dt_temp.Rows[0]["AttendWork"].ToString();
                    dicItemName["StatusID"] = dt_temp.Rows[0]["StatusID"].ToString();
                    dicItemName["StatusName"] = dt_temp.Rows[0]["StatusName"].ToString();
                    dicItemName["OperID"] = dt_temp.Rows[0]["OperID"].ToString();
                    result = SysParam.m_daoCommon.SetInsertDataItem("Attend_Total_Result", dicItemName);
                }

            }
            catch (Exception ex)
            {
                return result;
                throw ex;
            }

            return result;
        }
        public void Test01()
        {
            IntlStrings intl;
            StringDictionary sd;
            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aa",
                "text",
                "     spaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "one",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            Array destination;
            int cnt = 0;            // Count
            // initialize IntStrings
            intl = new IntlStrings();


            // [] StringDictionary is constructed as expected
            //-----------------------------------------------------------------

            sd = new StringDictionary();

            // [] Copy empty dictionary into empty array
            //
            destination = Array.CreateInstance(typeof(Object), sd.Count);
            Assert.Throws<ArgumentOutOfRangeException>(() => { sd.CopyTo(destination, -1); });
            sd.CopyTo(destination, 0);
            Assert.Throws<ArgumentException>(() => { sd.CopyTo(destination, 1); });

            // [] Copy empty dictionary into non-empty array
            //
            destination = Array.CreateInstance(typeof(Object), values.Length);
            for (int i = 0; i < values.Length; i++)
            {
                destination.SetValue(values[i], i);
            }
            sd.CopyTo(destination, 0);
            if (destination.Length != values.Length)
            {
                Assert.False(true, string.Format("Error, altered array after copying empty collection"));
            }
            if (destination.Length == values.Length)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    if (String.Compare(destination.GetValue(i).ToString(), values[i]) != 0)
                    {
                        Assert.False(true, string.Format("Error, altered item {0} after copying empty collection", i));
                    }
                }
            }


            // [] add simple strings and CopyTo(Array, 0)
            //

            cnt = sd.Count;
            int len = values.Length;
            for (int i = 0; i < len; i++)
            {
                sd.Add(keys[i], values[i]);
            }
            if (sd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, values.Length));
            }

            destination = Array.CreateInstance(typeof(Object), len);
            sd.CopyTo(destination, 0);

            IEnumerator en = sd.GetEnumerator();
            //
            // order of items is the same as order of enumerator
            //
            for (int i = 0; i < len; i++)
            {
                en.MoveNext();
                // verify that collection is copied correctly
                //
                DictionaryEntry curr = (DictionaryEntry)en.Current;

                if (String.Compare(curr.Value.ToString(), ((DictionaryEntry)destination.GetValue(i)).Value.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, ((DictionaryEntry)destination.GetValue(i)).Value, curr.Value));
                }

                if (String.Compare(curr.Key.ToString(), ((DictionaryEntry)destination.GetValue(i)).Key.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, ((DictionaryEntry)destination.GetValue(i)).Key, curr.Key));
                }
            }

            //
            // [] add simple strings and CopyTo(Array, middle_index)


            sd.Clear();

            for (int i = 0; i < len; i++)
            {
                sd.Add(keys[i], values[i]);
            }
            if (sd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, values.Length));
            }

            destination = Array.CreateInstance(typeof(Object), len * 2);
            sd.CopyTo(destination, len);

            en = sd.GetEnumerator();
            //
            // order of items is the same as order of enumerator
            //
            for (int i = 0; i < len; i++)
            {
                en.MoveNext();
                // verify that collection is copied correctly
                //
                DictionaryEntry curr = (DictionaryEntry)en.Current;

                if (String.Compare(curr.Value.ToString(), ((DictionaryEntry)destination.GetValue(i + len)).Value.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, ((DictionaryEntry)destination.GetValue(i + len)).Value, curr.Value));
                }

                if (String.Compare(curr.Key.ToString(), ((DictionaryEntry)destination.GetValue(i + len)).Key.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, ((DictionaryEntry)destination.GetValue(i + len)).Key, curr.Key));
                }
            }

            //
            // Intl strings
            // [] add intl strings and CopyTo(Array, 0)
            //

            string[] intlValues = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }

            Boolean caseInsensitive = false;
            for (int i = 0; i < len * 2; i++)
            {
                if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
                    caseInsensitive = true;
            }

            sd.Clear();
            for (int i = 0; i < len; i++)
            {
                sd.Add(intlValues[i + len], intlValues[i]);
            }
            if (sd.Count != (len))
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
            }

            destination = Array.CreateInstance(typeof(Object), len);
            sd.CopyTo(destination, 0);

            en = sd.GetEnumerator();
            //
            // order of items is the same as order of enumerator
            //
            for (int i = 0; i < len; i++)
            {
                en.MoveNext();
                // verify that collection is copied correctly
                //
                DictionaryEntry curr = (DictionaryEntry)en.Current;

                if (String.Compare(curr.Value.ToString(), ((DictionaryEntry)destination.GetValue(i)).Value.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, ((DictionaryEntry)destination.GetValue(i)).Value, curr.Value));
                }

                if (String.Compare(curr.Key.ToString(), ((DictionaryEntry)destination.GetValue(i)).Key.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, ((DictionaryEntry)destination.GetValue(i)).Key, curr.Key));
                }
            }

            //
            // Intl strings
            // [] add intl strings and CopyTo(Array, middle_index)
            //


            destination = Array.CreateInstance(typeof(Object), len * 2);
            sd.CopyTo(destination, len);

            en = sd.GetEnumerator();
            //
            // order of items is the same as order of enumerator
            //
            for (int i = 0; i < len; i++)
            {
                en.MoveNext();
                // verify that collection is copied correctly
                //
                DictionaryEntry curr = (DictionaryEntry)en.Current;

                if (String.Compare(curr.Value.ToString(), ((DictionaryEntry)destination.GetValue(i + len)).Value.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, ((DictionaryEntry)destination.GetValue(i + len)).Value, curr.Value));
                }

                if (String.Compare(curr.Key.ToString(), ((DictionaryEntry)destination.GetValue(i + len)).Key.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, ((DictionaryEntry)destination.GetValue(i + len)).Key, curr.Key));
                }
            }


            //
            // [] Case sensitivity
            //

            string[] intlValuesLower = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                intlValues[i] = intlValues[i].ToUpperInvariant();
            }

            for (int i = 0; i < len * 2; i++)
            {
                intlValuesLower[i] = intlValues[i].ToLowerInvariant();
            }

            sd.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                sd.Add(intlValues[i + len], intlValues[i]);     // adding uppercase strings
            }

            destination = Array.CreateInstance(typeof(Object), len);
            sd.CopyTo(destination, 0);

            en = sd.GetEnumerator();
            //
            // order of items is the same as order of enumerator
            //
            for (int i = 0; i < len; i++)
            {
                en.MoveNext();
                // verify that collection is copied correctly
                //
                DictionaryEntry curr = (DictionaryEntry)en.Current;

                if (String.Compare(curr.Value.ToString(), ((DictionaryEntry)destination.GetValue(i)).Value.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, ((DictionaryEntry)destination.GetValue(i)).Value, curr.Value));
                }

                if (!caseInsensitive && (Array.IndexOf(intlValuesLower, ((DictionaryEntry)destination.GetValue(i)).Value.ToString()) != -1))
                {
                    Assert.False(true, string.Format("Error, copied lowercase string"));
                }

                if (String.Compare(curr.Key.ToString(), ((DictionaryEntry)destination.GetValue(i)).Key.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, ((DictionaryEntry)destination.GetValue(i)).Key, curr.Key));
                }

                if (Array.IndexOf(intlValuesLower, ((DictionaryEntry)destination.GetValue(i)).Key.ToString()) == -1)
                {
                    Assert.False(true, string.Format("Error, copied uppercase key"));
                }
            }


            //
            //  [] CopyTo(null, int)
            //
            destination = null;
            Assert.Throws<ArgumentNullException>(() => { sd.CopyTo(destination, 0); });

            //
            //  [] CopyTo(string[], -1)
            //
            cnt = sd.Count;

            destination = Array.CreateInstance(typeof(Object), cnt);
            Assert.Throws<ArgumentOutOfRangeException>(() => { sd.CopyTo(destination, -1); });

            //
            // [] CopyTo(Array, upperBound+1)
            //
            if (sd.Count < 1)
            {
                for (int i = 0; i < len; i++)
                {
                    sd.Add(keys[i], values[i]);
                }
            }

            destination = Array.CreateInstance(typeof(Object), len);
            Assert.Throws<ArgumentException>(() => { sd.CopyTo(destination, len); });

            //
            // [] CopyTo(Array, upperBound+2)
            //
            Assert.Throws<ArgumentException>(() => { sd.CopyTo(destination, len + 1); });

            //
            // [] CopyTo(Array, not_enough_space)
            //
            Assert.Throws<ArgumentException>(() => { sd.CopyTo(destination, len / 2); });

            //
            // [] CopyTo(multidim_Array, 0)
            //

            destination = new object[len, len];
            Assert.Throws<ArgumentException>(() => { sd.CopyTo(destination, 0); });
        }
        public void Test01()
        {
            StringDictionary sd;
            IEnumerator en;
            DictionaryEntry curr;        // Enumerator.Current value
            // simple string values
            string[] values =
            {
                "a",
                "aa",
                "",
                " ",
                "text",
                "     spaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "one",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            // [] StringDictionary GetEnumerator()
            //-----------------------------------------------------------------

            sd = new StringDictionary();

            // [] Enumerator for empty dictionary
            //
            en = sd.GetEnumerator();
            string type = en.GetType().ToString();
            if (type.IndexOf("Enumerator", 0) == 0)
            {
                Assert.False(true, string.Format("Error, type is not Enumerator"));
            }

            //
            //  MoveNext should return false
            //
            bool res = en.MoveNext();
            if (res)
            {
                Assert.False(true, string.Format("Error, MoveNext returned true"));
            }

            //
            //  Attempt to get Current should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; });

            //
            //   Filled collection
            // [] Enumerator for filled dictionary
            //
            for (int i = 0; i < values.Length; i++)
            {
                sd.Add(keys[i], values[i]);
            }

            en = sd.GetEnumerator();
            type = en.GetType().ToString();
            if (type.IndexOf("Enumerator", 0) == 0)
            {
                Assert.False(true, string.Format("Error, type is not Enumerator"));
            }

            //
            //  MoveNext should return true
            //

            for (int i = 0; i < sd.Count; i++)
            {
                res = en.MoveNext();
                if (!res)
                {
                    Assert.False(true, string.Format("Error, MoveNext returned false", i));
                }

                curr = (DictionaryEntry)en.Current;
                //
                //enumerator enumerates in different than added order
                // so we'll check Contains
                //
                if (!sd.ContainsValue(curr.Value.ToString()))
                {
                    Assert.False(true, string.Format("Error, Current dictionary doesn't contain value from enumerator", i));
                }
                if (!sd.ContainsKey(curr.Key.ToString()))
                {
                    Assert.False(true, string.Format("Error, Current dictionary doesn't contain key from enumerator", i));
                }
                if (String.Compare(sd[curr.Key.ToString()], curr.Value.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, Value for current Key is different in dictionary", i));
                }

                // while we didn't MoveNext, Current should return the same value
                DictionaryEntry curr1 = (DictionaryEntry)en.Current;
                if (!curr.Equals(curr1))
                {
                    Assert.False(true, string.Format("Error, second call of Current returned different result", i));
                }
            }

            // next MoveNext should bring us outside of the collection
            //
            res = en.MoveNext();
            res = en.MoveNext();
            if (res)
            {
                Assert.False(true, string.Format("Error, MoveNext returned true"));
            }

            //
            //  Attempt to get Current should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; });
            en.Reset();

            //
            //  Attempt to get Current should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; });

            //
            // [] Modify dictionary when enumerating
            //
            if (sd.Count < 1)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    sd.Add(keys[i], values[i]);
                }
            }

            en = sd.GetEnumerator();
            res = en.MoveNext();
            if (!res)
            {
                Assert.False(true, string.Format("Error, MoveNext returned false"));
            }
            curr = (DictionaryEntry)en.Current;
            int cnt = sd.Count;
            sd.Remove(keys[0]);
            if (sd.Count != cnt - 1)
            {
                Assert.False(true, string.Format("Error, didn't remove item with 0th key"));
            }

            // will return just removed item
            DictionaryEntry curr2 = (DictionaryEntry)en.Current;
            if (!curr.Equals(curr2))
            {
                Assert.False(true, string.Format("Error, current returned different value after modification"));
            }

            // exception expected
            Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); });

            //
            // [] Modify dictionary when enumerated beyond the end
            //
            sd.Clear();
            for (int i = 0; i < values.Length; i++)
            {
                sd.Add(keys[i], values[i]);
            }

            en = sd.GetEnumerator();
            for (int i = 0; i < sd.Count; i++)
            {
                en.MoveNext();
            }
            curr = (DictionaryEntry)en.Current;

            curr = (DictionaryEntry)en.Current;
            cnt = sd.Count;
            sd.Remove(keys[0]);
            if (sd.Count != cnt - 1)
            {
                Assert.False(true, string.Format("Error, didn't remove item with 0th key"));
            }

            // will return just removed item
            curr2 = (DictionaryEntry)en.Current;
            if (!curr.Equals(curr2))
            {
                Assert.False(true, string.Format("Error, current returned different value after modification"));
            }

            // exception expected
            Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); });
        }
Exemple #16
0
        public void Test01()
        {
            IntlStrings intl;
            StringDictionary sd;
            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aa",
                "tExt",
                "     spAces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "one",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            Array arr;
            ICollection ks;         // Keys collection
            int ind;

            // initialize IntStrings
            intl = new IntlStrings();


            // [] StringDictionary is constructed as expected
            //-----------------------------------------------------------------

            sd = new StringDictionary();

            // [] get Keys on empty dictionary
            //
            if (sd.Count > 0)
                sd.Clear();

            if (sd.Keys.Count != 0)
            {
                Assert.False(true, string.Format("Error, returned Keys.Count = {0}", sd.Keys.Count));
            }

            //
            // [] get Keys on filled dictionary
            //
            int len = values.Length;
            sd.Clear();
            for (int i = 0; i < len; i++)
            {
                sd.Add(keys[i], values[i]);
            }
            if (sd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
            }

            ks = sd.Keys;
            if (ks.Count != len)
            {
                Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count));
            }
            arr = Array.CreateInstance(typeof(string), len);
            ks.CopyTo(arr, 0);
            for (int i = 0; i < len; i++)
            {
                ind = Array.IndexOf(arr, keys[i].ToLowerInvariant());
                if (ind < 0)
                {
                    Assert.False(true, string.Format("Error, Keys doesn't contain \"{1}\" key. Search result: {2}", i, keys[i], ind));
                }
            }



            //
            // [] get Keys on dictionary with identical values
            //

            sd.Clear();
            string intlStr = intl.GetRandomString(MAX_LEN);

            sd.Add("keykey1", intlStr);        // 1st duplicate
            for (int i = 0; i < len; i++)
            {
                sd.Add(keys[i], values[i]);
            }
            sd.Add("keykey2", intlStr);        // 2nd duplicate
            if (sd.Count != len + 2)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len + 2));
            }

            // get Keys
            //

            ks = sd.Keys;
            if (ks.Count != sd.Count)
            {
                Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count));
            }
            arr = Array.CreateInstance(typeof(string), len + 2);
            ks.CopyTo(arr, 0);
            for (int i = 0; i < len; i++)
            {
                ind = Array.IndexOf(arr, keys[i].ToLowerInvariant());
                if (ind < 0)
                {
                    Assert.False(true, string.Format("Error, Keys doesn't contain \"{1}\" key", i, keys[i]));
                }
            }
            ind = Array.IndexOf(arr, "keykey1");
            if (ind < 0)
            {
                Assert.False(true, string.Format("Error, Keys doesn't contain {0} key", "keykey1"));
            }

            ind = Array.IndexOf(arr, "keykey2");
            if (ind < 0)
            {
                Assert.False(true, string.Format("Error, Keys doesn't contain \"{0}\" key", "keykey2"));
            }

            //
            // Intl strings
            // [] get Keys on dictionary filled with Intl strings
            //

            string[] intlValues = new string[len * 2];
            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }

            //
            // will use first half of array as values and second half as keys
            //
            sd.Clear();
            for (int i = 0; i < len; i++)
            {
                sd.Add(intlValues[i + len], intlValues[i]);
            }
            if (sd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
            }

            ks = sd.Keys;
            if (ks.Count != len)
            {
                Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count));
            }
            arr = Array.CreateInstance(typeof(string), len);
            ks.CopyTo(arr, 0);
            for (int i = 0; i < arr.Length; i++)
            {
                ind = Array.IndexOf(arr, intlValues[i + len].ToLowerInvariant());
                if (ind < 0)
                {
                    Assert.False(true, string.Format("Error, Keys doesn't contain \"{1}\" key", i, intlValues[i + len]));
                }
            }

            //
            //  Case sensitivity: keys are always lowercased - not doing it
            // [] Change dictionary and check Keys
            //

            sd.Clear();
            for (int i = 0; i < len; i++)
            {
                sd.Add(keys[i], values[i]);
            }
            if (sd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
            }

            ks = sd.Keys;
            if (ks.Count != len)
            {
                Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count));
            }

            sd.Remove(keys[0]);
            if (sd.Count != len - 1)
            {
                Assert.False(true, string.Format("Error, didn't remove element"));
            }
            if (ks.Count != len - 1)
            {
                Assert.False(true, string.Format("Error, Keys were not updated after removal"));
            }
            arr = Array.CreateInstance(typeof(string), sd.Count);
            ks.CopyTo(arr, 0);
            ind = Array.IndexOf(arr, keys[0].ToLowerInvariant());
            if (ind >= 0)
            {
                Assert.False(true, string.Format("Error, Keys still contains removed key " + ind));
            }

            sd.Add(keys[0], "new item");
            if (sd.Count != len)
            {
                Assert.False(true, string.Format("Error, didn't add element"));
            }
            if (ks.Count != len)
            {
                Assert.False(true, string.Format("Error, Keys were not updated after addition"));
            }
            arr = Array.CreateInstance(typeof(string), sd.Count);
            ks.CopyTo(arr, 0);
            ind = Array.IndexOf(arr, keys[0].ToLowerInvariant());
            if (ind < 0)
            {
                Assert.False(true, string.Format("Error, Keys doesn't contain added key "));
            }
        }
Exemple #17
0
        public void Test01()
        {
            IntlStrings intl;
            StringDictionary sd;
            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aa",
                "text",
                "     spaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "one",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            string itm;         // returned Item
            // initialize IntStrings
            intl = new IntlStrings();


            // [] StringDictionary is constructed as expected
            //-----------------------------------------------------------------

            sd = new StringDictionary();

            // [] get Item() on empty dictionary
            //
            if (sd.Count > 0)
                sd.Clear();

            for (int i = 0; i < keys.Length; i++)
            {
                itm = sd[keys[i]];
                if (itm != null)
                {
                    Assert.False(true, string.Format("Error, returned non-null for {0} key", i));
                }
            }

            // [] get Item() on filled dictionary
            //
            int len = values.Length;
            sd.Clear();
            for (int i = 0; i < len; i++)
            {
                sd.Add(keys[i], values[i]);
            }
            if (sd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
            }

            for (int i = 0; i < len; i++)
            {
                if (String.Compare(sd[keys[i]], values[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned {1} instead of {2}", i, sd[keys[i]], values[i]));
                }
            }



            //
            //  [] get Item on dictionary with identical values
            //

            sd.Clear();
            string intlStr = intl.GetRandomString(MAX_LEN);

            sd.Add("keykey1", intlStr);        // 1st duplicate
            for (int i = 0; i < len; i++)
            {
                sd.Add(keys[i], values[i]);
            }
            sd.Add("keykey2", intlStr);        // 2nd duplicate
            if (sd.Count != len + 2)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len + 2));
            }

            // get Item
            //
            if (String.Compare(sd["keykey1"], intlStr) != 0)
            {
                Assert.False(true, string.Format("Error, returned {1} instead of {2}", sd["keykey1"], intlStr));
            }

            if (String.Compare(sd["keykey2"], intlStr) != 0)
            {
                Assert.False(true, string.Format("Error, returned {1} instead of {2}", sd["keykey2"], intlStr));
            }

            //
            // Intl strings
            // [] get Item() on dictionary filled with Intl strings
            //

            string[] intlValues = new string[len * 2];
            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }

            //
            // will use first half of array as values and second half as keys
            //
            sd.Clear();
            for (int i = 0; i < len; i++)
            {
                sd.Add(intlValues[i + len], intlValues[i]);
            }
            if (sd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
            }

            // get item
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(sd[intlValues[i + len]], intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned {1} instead of {2}", i, sd[intlValues[i + len]], intlValues[i]));
                }
            }

            //
            // [] Case sensitivity: keys are always lowercased
            //

            sd.Clear();

            string[] intlValuesUpper = new string[len];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                intlValues[i] = intlValues[i].ToLowerInvariant();
            }

            // array of uppercase keys
            for (int i = 0; i < len; i++)
            {
                intlValuesUpper[i] = intlValues[i + len].ToUpperInvariant();
            }

            sd.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                sd.Add(intlValues[i + len], intlValues[i]);     // adding lowercase strings
            }
            if (sd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
            }

            // get Item
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(sd[intlValuesUpper[i]], intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned {1} instead of {2}", i, sd[intlValuesUpper[i]], intlValues[i]));
                }
            }

            //
            // [] Invalid parameter
            //
            Assert.Throws<ArgumentNullException>(() => { itm = sd[null]; });
        }