public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method IDictionaryContains when specified key existed.");

        try
        {
            IDictionary dictionary = new Dictionary<string, string>();

            dictionary.Add("txt", "notepad.exe");
            dictionary.Add("bmp", "paint.exe");
            dictionary.Add("dib", "paint.exe");
            dictionary.Add("rtf", "wordpad.exe");

            bool testVerify = dictionary.Contains("txt") && dictionary.Contains("bmp") &&
                              dictionary.Contains("dib") && dictionary.Contains("rtf");

            if (testVerify == false)
            {
                TestLibrary.TestFramework.LogError("001.1", "Method IDictionaryContains Err .");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Example #2
0
 public void Dictionary_kvp_Contains_checks_key_and_value()
 {
     IDictionary<int,string> dictionary = new Dictionary<int, string>();
     dictionary[1] = "foo";
     Assert.IsTrue(dictionary.Contains(new KeyValuePair<int, string>(1, "foo")));
     Assert.IsFalse(dictionary.Contains(new KeyValuePair<int, string>(1, "bar")));
 }
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: The IDictionary contains the key");

        try
        {
            IDictionary iDictionary = new Dictionary<object,object>();
            Int32[] key = new Int32[1000];
            Byte[] value = new Byte[1000];
            for (int i = 0; i < 1000; i++)
            {
                key[i] = i;
            }
            TestLibrary.Generator.GetBytes(-55, value);
            for (int i = 0; i < 1000; i++)
            {
                iDictionary.Add(key[i], value[i]);
            }
            int keyValue = this.GetInt32(0, 1000);
            if (!iDictionary.Contains(keyValue))
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected ");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest2()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method IDictionaryRemove when the specified key is not exist.");

        try
        {
            IDictionary dictionary = new Dictionary<string, string>();

            dictionary.Remove("txt");

            if (dictionary.Contains("txt") == true)
            {
                TestLibrary.TestFramework.LogError("002.1", "Method IDictionary.GetEnumerator Err .");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Example #5
0
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: The key to be remove is a custom class");

        try
        {
            IDictionary iDictionary = new Dictionary<object,object>();
            MyClass mc = new MyClass();
            int value = TestLibrary.Generator.GetInt32(-55);
            iDictionary.Add(mc, value);
            iDictionary.Remove(mc);
            if (iDictionary.Contains(mc))
            {
                TestLibrary.TestFramework.LogError("003", "The result is not the value as expected ");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method ICollectionContains when k/v existed.");

        try
        {
            ICollection<KeyValuePair<String, String>> dictionary = new Dictionary<String, String>();

            KeyValuePair<string, string> kvp1 = new KeyValuePair<String, String>("txt", "notepad.exe");
            KeyValuePair<string, string> kvp2 = new KeyValuePair<String, String>("bmp", "paint.exe");
            KeyValuePair<string, string> kvp3 = new KeyValuePair<String, String>("dib", "paint.exe");
            KeyValuePair<string, string> kvp4 = new KeyValuePair<String, String>("rtf", "wordpad.exe");

            dictionary.Add(kvp1);
            dictionary.Add(kvp2);
            dictionary.Add(kvp3);
            dictionary.Add(kvp4);

            bool actual  = dictionary.Contains(kvp1) &&
                           dictionary.Contains(kvp1) &&
                           dictionary.Contains(kvp1) &&
                           dictionary.Contains(kvp1);
            bool expected = true;

            if (actual != expected)
            {
                TestLibrary.TestFramework.LogError("001.1", "Method ICollectionContains Err.");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
        public void VersionSetsCorrectTagKeyAndValue()
        {
            IDictionary<string, string> tags = new Dictionary<string, string>();
            var component = new ComponentContext(tags);

            string componentVersion = "fakeVersion";
            component.Version = componentVersion;

            Assert.True(tags.Contains(new KeyValuePair<string, string>(ContextTagKeys.Keys.ApplicationVersion, componentVersion)));
        }
		public void CharHistogramTest()
		{
			Dictionary<char, int> expectedDictionary = new Dictionary<char, int>()
			{
			//	expected - 'P': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1, '!': 2
				{'P', 1},
				{'y', 1},
				{'t', 1},
				{'h', 1},
				{'o', 1},
				{'n', 1},
				{'!', 2},
			};
			/*Dictionary<char, int> resultDictionary = new Dictionary<char, int>() {
				{'P', 1},
				{'y', 1},
				{'t', 1},
				{'h', 1},
				{'o', 1},
				{'n', 1},
				{'!', 2},};
				*/
				Histogram rclass = new Histogram();
				var resultDictionary = rclass.CharHistogram("Phyton!!");
				Assert.AreEqual(true,resultDictionary.All(e => expectedDictionary.Contains(e)));
			/*Assert.AreEqual(resultDictionary,expectedDictionary);
			Histogram rclass = new Histogram();
			//var result = res.CharHistogram("Phyton!!");
			foreach (var exp in expectedDictionary)
			{
				foreach (var res in resultDictionary)
				{
					if (exp.Key == res.Key)
					{
						if (exp.Value != res.Value)
						{
							Assert.Fail("exp.Val= {0} res.Val = {1} ", exp.Value, res.Value);
						}
					}
					else
					{
						Assert.Fail("exp.Key= {0} res.Key = {1} ",exp.Key,res.Key);
					}
				}
			}
			*/
		}
        public static bool IsEquals(Dictionary<BaseSi, int> d1, Dictionary<BaseSi, int> d2)
        {
            if(d1.Count == d2.Count)
            {
                foreach(var item in d1)
                {
                    if(!d2.Contains(item))
                    {
                        return false;
                    }
                }
            }
            else
            {
                return false;
            }

            return true;
        }
Example #10
0
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Using Dictionary<string,Byte> to implemented the clear method");

        try
        {
            IDictionary iDictionary = new Dictionary<string,Byte>();
            string[] key = new string[1000];
            Byte[] value = new Byte[1000];
            for (int i = 0; i < 1000; i++)
            {
                key[i] = TestLibrary.Generator.GetString(-55, false, 1, 100);
            }
            TestLibrary.Generator.GetBytes(-55, value);
            for (int i = 0; i < 1000; i++)
            {
                while (iDictionary.Contains(key[i]))
                {
                    key[i] = TestLibrary.Generator.GetString(false, 1, 100);
                }
                iDictionary.Add(key[i], value[i]);
            }
            iDictionary.Clear();
            if (iDictionary.Count != 0)
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected ");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
        public void UnionDictionariesTest()
        {
            IDictionary<int, string> target = new Dictionary<int, string>();
            IDictionary<int, string> source = new Dictionary<int, string>();
            // simple add
            target.Add(1, "one");
            source.Add(2, "two");
            CollectionUtil.UnionDictionaries(target, source);
            Assert.IsTrue(target.ContainsKey(2));
            Assert.IsTrue(target.Contains(new KeyValuePair<int,string>(2, "two")));
            Assert.AreEqual(2, target.Count);

            // skip existing
            source.Add(3, "three");
            CollectionUtil.UnionDictionaries(target, source);
            Assert.AreEqual(3, target.Count);

            // replace
            source[3] = "new three";
            CollectionUtil.UnionDictionaries(target, source);
            Assert.AreEqual("new three", target[3]);

        }
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: The key is a string of white space");

        try
        {
            IDictionary iDictionary = new Dictionary<object,object>();
            iDictionary.Add("  ", true);
            if (!iDictionary.Contains("  "))
            {
                TestLibrary.TestFramework.LogError("003", "The result is not the value as expected ");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
Example #13
0
 private bool AssertCorrectParameters(Dictionary<string, string> expected, Dictionary<string, string> paramsToCheck)
 {
     return paramsToCheck.Count == expected.Count && paramsToCheck.All(p => expected.Contains(p));
 }
 private void RemoveSendStatuses(Dictionary<int, int> temp_statuses)
 {
     Dictionary<int, int> temp_statuses2 = new Dictionary<int, int>();
     try
     {
         lock (statuses)
         {
             foreach (KeyValuePair<int, int> o in statuses)
                 if (!temp_statuses.Contains(o))
                     temp_statuses2.Add(o.Key, o.Value);
             statuses.Clear();
             foreach (KeyValuePair<int, int> o in temp_statuses2)
                 statuses.Add(o.Key, o.Value);
         }
     }
     catch (Exception ex) { Console.WriteLine("Произошла ошибка при очистке статусов "+ex.Message); }
     finally
     {
         if (temp_statuses2 != null) { temp_statuses2.Clear(); GC.SuppressFinalize(temp_statuses2); }
     }
 }
Example #15
0
        /// <summary>
        /// Returns an alt present in the passed dictionary
        /// </summary>
        /// <param name="nick"></param>
        public string FindPlayerAlt(string nick, Dictionary<string,Player>.KeyCollection allNames)
        {
            try
            {
                StreamReader reader = new StreamReader(".//AlternateNames.txt");
                string input;
                string newNick;

                do
                {
                    // Get line of alts
                    input = reader.ReadLine();
                    input = input.ToUpper();

                    // See if the current line of alts contains the input nick
                    if (input.Contains(nick.ToUpper()))
                    {
                        int index = 0;
                        while (true)
                        {
                            // Parse a nick
                            int commaLocation = input.IndexOf(",", index);
                            if (commaLocation == -1)
                            {
                                // Get all remaining characters for a final match attempt
                                newNick = input.Substring(index, input.Length - index).Trim();
                                if (allNames.Contains(newNick))
                                {
                                    errorwriter.Write("Match found: " + newNick);
                                    reader.Close();
                                    return newNick;
                                }
                                break;
                            }
                            else
                            {
                                newNick = input.Substring(index, commaLocation - index);

                                // If the new nick is found in the collection of players, return the new nick
                                if (allNames.Contains(newNick))
                                {
                                    errorwriter.Write("Match found: " + newNick);
                                    reader.Close();
                                    return newNick;
                                }

                                // Advance past the comma
                                index = commaLocation + 1;
                            }
                        }
                    }
                } while (!reader.EndOfStream);

                // Search failed
                errorwriter.Write("No match found");
                reader.Close();
                return string.Empty;
            }
            catch (FileNotFoundException e)
            {
                errorwriter.Write("Could not find AlternateNames.txt (" + e.Message + ")");
                return string.Empty;
            }
            catch (Exception e)
            {
                errorwriter.Write("Error reading alternate name file (" + e.Message + ")");
                return string.Empty;
            }
        }
        public void ShouldReportContainsCorrectly()
        {
            var bag = new Dictionary<string, object>();
            bag.Add(new Url("/2"));

            Assert.That(bag.Contains<Url>());
            Assert.That(bag.Contains(typeof(Url)));
        }
Example #17
0
        private Dictionary<int, string> GetPop3NewMessagesIDs(Pop3Client client)
        {
            var newMessages = new Dictionary<int, string>();

            var emailIds = client.GetUniqueIds();

            if (!emailIds.Any() || emailIds.Count == Account.MessagesCount)
                return newMessages;

            var i = 0;
            var chunk = tasksConfig.ChunkOfPop3Uidl;

            var emails = emailIds.Skip(i).Take(chunk).ToList();

            do
            {
                var checkList = emails.Select(e => e.UniqueId).Distinct().ToList();

                var existingUidls = mailBoxManager.CheckUidlExistance(Account.MailBoxId, checkList);

                if (!existingUidls.Any())
                {
                    foreach (
                        var item in
                            emails.Select(email => new KeyValuePair<int, string>(email.Index, email.UniqueId))
                                  .Where(item => !newMessages.Contains(item)))
                    {
                        newMessages.Add(item.Key, item.Value);
                    }
                }
                else if (existingUidls.Count != emails.Count)
                {
                    foreach (var item in (from email in emails
                                          where !existingUidls.Contains(email.UniqueId)
                                          select new KeyValuePair<int, string>(email.Index, email.UniqueId)).Where(
                                              item => !newMessages.Contains(item)))
                    {
                        newMessages.Add(item.Key, item.Value);
                    }
                }

                i += chunk;

                emails = emailIds.Skip(i).Take(chunk).ToList();

            } while (emails.Any());

            return newMessages;
        }
        public void GetOrAddTestCase()
        {
            var dictionary = new Dictionary<String, String>();
            var key = RandomValueEx.GetRandomString();
            var value = RandomValueEx.GetRandomString();

            var actual = dictionary.GetOrAdd( key, value );
            Assert.AreEqual( value, actual );
            Assert.IsTrue( dictionary.Contains( new KeyValuePair<String, String>( key, value ) ) );
            Assert.AreEqual( 1, dictionary.Count );

            actual = dictionary.GetOrAdd( key, value );
            Assert.AreEqual( value, actual );
            Assert.IsTrue( dictionary.Contains( new KeyValuePair<String, String>( key, value ) ) );
            Assert.AreEqual( 1, dictionary.Count );
        }
 private static void CheckMetadataSubset(Dictionary<string, string> expected, Dictionary<string, string> actual)
 {
     foreach (var pair in expected)
         Assert.IsTrue(actual.Contains(pair), "Expected metadata item {{ {0} : {1} }} not found.", pair.Key, pair.Value);
 }
        private static void VerifyEntry(
            Dictionary<string, object> expectedFullMetadataObject,
            ODataEntry entry,
            ODataNavigationLink[] userSpecifiedNavigationLinks,
            ODataProperty[] userSpecifiedMediaProperties,
            Dictionary<string, object> metadataNotYetVerified,
            string mimeType,
            bool autoComputePayloadMetadataInJson)
        {
            if (autoComputePayloadMetadataInJson && !mimeType.Contains(MimeTypes.ODataParameterMinimalMetadata))
            {
                // Verify fullmedata result against fullmetadata expected object, for nometadata, verify metadata does not exist in the result
                foreach (var pair in expectedFullMetadataObject)
                {
                    // whether the expected metadata is in the result
                    bool existInEntry = metadataNotYetVerified.Contains(pair);

                    bool isMetadata = pair.Key.Contains("odata.");

                    // special handling for actions since each action is a Dictionary<string, object> in the expect/actual with key value "#Namespace.ActionName"
                    if (pair.Key.StartsWith("#" + WritePayloadHelper.Model.EntityContainer.Namespace))
                    {
                        isMetadata = true;
                        var expectedActionObject = pair.Value as Dictionary<string, object>;
                        if (metadataNotYetVerified.ContainsKey(pair.Key))
                        {
                            var actualActionObject = metadataNotYetVerified[pair.Key] as Dictionary<string, object>;
                            existInEntry = true;
                            foreach (var item in expectedActionObject)
                            {
                                // verify action title/target
                                existInEntry = existInEntry && actualActionObject.Contains(item);
                            }
                        }
                    }

                    // whether expectedFullMetadataObject property is in the result
                    if (!isMetadata)
                    {
                        existInEntry = metadataNotYetVerified.ContainsKey(pair.Key);
                    }

                    if (mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                    {
                        // nometadata result should contain properties but not metadata
                        Assert.IsTrue(isMetadata != existInEntry, "Unexpected " + pair.Key);
                    }
                    else if (mimeType.Contains(MimeTypes.ODataParameterFullMetadata))
                    {
                        // fullmetadata result should contain properties and metadata
                        Assert.IsTrue(existInEntry, "Expected item not found " + pair.Key);
                    }

                    metadataNotYetVerified.Remove(pair.Key);
                }
            }
            else
            {
                VerifyAgainstODataEntry(entry, userSpecifiedNavigationLinks, userSpecifiedMediaProperties, metadataNotYetVerified);
            }

            // additional verification for mimimalmetadata, only include odata.type in derived type instances
            if (!autoComputePayloadMetadataInJson || mimeType.Contains(MimeTypes.ODataParameterMinimalMetadata))
            {
                object value = null;
                bool typeAnnotationFound = metadataNotYetVerified.TryGetValue(JsonLightConstants.ODataTypeAnnotationName, out value);
                Assert.IsTrue(!typeAnnotationFound || (typeAnnotationFound && (value as string).Contains("Employee")));

                metadataNotYetVerified.Remove(JsonLightConstants.ODataTypeAnnotationName);
            }

            // make sure all metadata in the actual object is verified
            foreach (var pair in metadataNotYetVerified)
            {
                Assert.IsFalse(pair.Key.Contains("odata.") && !pair.Key.Contains("odata.associationLink"));
                Assert.IsFalse(pair.Key.StartsWith("#"));
            }
        }
Example #21
0
        private object MapDataInternal(Dictionary<string, object> row, DataSchemaKey key, Type type, Dictionary<DataSchemaIterator, int> interatorsIndexes)
        {
            Contract.Requires(type != null);

            object generetedObject = Activator.CreateInstance(type);
            var p = type.GetProperties();
            foreach (DataSchemaKey childKey in key.Childs)
            {
                PropertyInfo property = type.GetProperty("_" + childKey.Name);
                object value = new object();
                switch (childKey.Type)
                {
                    case DataSchemaKeyType.Container:
                        value = MapDataInternal(row, childKey, property.PropertyType, interatorsIndexes);
                        break;

                    case DataSchemaKeyType.Value:
                        DataSchemaValue v = (DataSchemaValue)childKey;
                        value = row[v.MappedColumn];
                        break;

                    case DataSchemaKeyType.Iterator:
                        DataSchemaIterator iterator = (DataSchemaIterator)childKey;
                        interatorsIndexes.Add(iterator, 0);
                        Array array = Array.CreateInstance(property.PropertyType.GetElementType(), iterator.MaxItemCount);

                        for (int i = 0; i < iterator.MaxItemCount; i++)
                        {
                            interatorsIndexes[iterator] = i;
                            object arrayValue = MapDataInternal(row, childKey, property.PropertyType.GetElementType(), interatorsIndexes);
                            array.SetValue(arrayValue, i);
                        }
                        value = array;
                        break;

                    case DataSchemaKeyType.IteratedValue:
                        DataSchemaIteratorValue va = (DataSchemaIteratorValue)childKey;
                        foreach (DataSchemaIteratorValueMappedColumn mc in va.MappedColumns)
                        {
                            bool match = true;
                            foreach (KeyValuePair<DataSchemaIterator, int> index in mc.IteratorIndexes)
                            {
                                if (!interatorsIndexes.Contains(index))
                                {
                                    match = false;
                                    break;
                                }
                            }
                            if (match)
                            {
                                value = row[mc.ColumnName];
                                break;
                            }
                        }
                        break;
                }

                property.SetValue(generetedObject, value, null);
            }
            return generetedObject;
        }
Example #22
0
        //选择乘客
        async void chkContact_Click(object sender, RoutedEventArgs e)
        {
            string val = "";
            CheckBox chk;
            foreach (var c in gContacts.Children)
            {
                if (c is CheckBox)
                {
                    chk = c as CheckBox;
                    if (chk.IsChecked == true)
                    {
                        val += chk.Tag + ",";
                    }
                }
            }
            string train = lblTicket.Content.ToString().Substring(lblTicket.Content.ToString().IndexOf("(") + 1, 1), trainType = "";
            trainType = !"DZTK".Contains(train) ? "QT" : train;
            trainType = "GC".Contains(train) ? "D" : "QT";
            Dictionary<string, string> seatType = await GetTickType(trainType);//席别
            IDictionary<string, string> seat_Type = new Dictionary<string, string>();
            var type = seatTypes.Split('@');
            for (int i = 0; i < type.Count(); i++)
            {
                if (type[i] != "")
                {
                    var _seatType = (from s in seatType
                                     where s.Value == type[i]
                                     select s).ToDictionary(t => t.Key, t => t.Value);
                    foreach (var t in _seatType)
                    {
                        if (!seat_Type.Contains(t))
                        {
                            seat_Type.Add(t);
                        }
                    }
                }
            }

            Dictionary<string, string> tickType = new Dictionary<string, string>();//票种
            tickType.Add("成人票", "1");
            tickType.Add("儿童票", "2");
            tickType.Add("学生票", "3");
            tickType.Add("残军票", "4");
            Dictionary<string, string> idType = new Dictionary<string, string>();//证件类型
            idType.Add("二代身份证", "1");
            idType.Add("一代身份证", "2");
            idType.Add("港澳通行证", "C");
            idType.Add("台湾通行证", "G");
            idType.Add("护照", "B");

            List<SubmitOrder> subOrder = new List<SubmitOrder>();
            if (val != "")
            {
                var selPassenger = val.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);//选中的乘客
                if (selPassenger.Count() > 5)
                {
                    MessageBox.Show("乘客数不能超过5个", "消息", MessageBoxButton.OK, MessageBoxImage.Warning);
                    CheckBox chkItem = e.Source as CheckBox;
                    chkItem.IsChecked = false;
                    return;
                }
                for (int j = 0; j < selPassenger.Count(); j++)
                {
                    if (selPassenger[j] != "")
                    {
                        var item = selPassenger[j].Split('#');
                        SubmitOrder subOrderModel = new SubmitOrder();
                        subOrderModel.SeatType = seat_Type.ToDictionary(m => m.Key, m => m.Value);
                        subOrderModel.SelSeatType = subOrderModel.SeatType.Keys.Last();
                        subOrderModel.TickType = (from t in tickType
                                                  where t.Key.Contains(item[0])
                                                  select t).ToDictionary(m => m.Key, m => m.Value);
                        subOrderModel.SelTickType = subOrderModel.TickType.Values.First();
                        subOrderModel.PassengerName = item[1];
                        subOrderModel.IDType = (from d in idType
                                                where d.Key.Contains(item[2])
                                                select d).ToDictionary(m => m.Key, m => m.Value);
                        subOrderModel.SelIDType = subOrderModel.IDType.Values.First();
                        subOrderModel.PassengerId = item[3];
                        subOrderModel.PassengerMobile = item[4];
                        subOrder.Add(subOrderModel);
                    }
                }
            }

            gridPassenger.ItemsSource = subOrder;
        }
    public bool PosTest3()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest3: The key is a custom class");

        try
        {
            IDictionary iDictionary = new Dictionary<object,object>();
            MyClass mc = new MyClass();
            iDictionary.Add(mc, true);
            if (!iDictionary.Contains(mc))
            {
                TestLibrary.TestFramework.LogError("005", "The result is not the value as expected ");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
Example #24
0
        public static FncFile Parse(string sourceFile)
        {
            var sourceText = File.ReadAllText(sourceFile);
            var boxes = new List<Box>();

            // Turn into array of characters
            var lines = (sourceText.Replace("\r", "") + "\n\n").Split('\n');
            var source = new SourceAsChars(lines);

            if (lines.Length == 0)
                return new FncFile { Boxes = boxes, Source = source };

            var visited = new Dictionary<int, HashSet<int>>();

            // Find boxes
            for (int y = 0; y < source.NumLines; y++)
            {
                for (int x = 0; x < source[y].Length; x++)
                {
                    // Go looking for a box only if this is a top-left corner of a box
                    if (source.TopLine(x, y) != LineType.None || source.LeftLine(x, y) != LineType.None || source.RightLine(x, y) == LineType.None || source.BottomLine(x, y) == LineType.None)
                        continue;

                    if (visited.Contains(x, y))
                        continue;

                    // Find width of box by walking along top edge
                    var top = source.RightLine(x, y);
                    var index = x + 1;
                    while (index < source[y].Length && source.RightLine(index, y) == top)
                        index++;
                    if (index == source[y].Length || source.BottomLine(index, y) == LineType.None || source.TopLine(index, y) != LineType.None || source.RightLine(index, y) != LineType.None)
                        continue;
                    var width = index - x;

                    // Find height of box by walking along left edge
                    var left = source.BottomLine(x, y);
                    index = y + 1;
                    while (index < source.NumLines && source.BottomLine(x, index) == left)
                        index++;
                    if (index == source.NumLines || source.RightLine(x, index) == LineType.None || source.LeftLine(x, index) != LineType.None || source.BottomLine(x, index) != LineType.None)
                        continue;
                    var height = index - y;

                    // Verify the bottom edge
                    var bottom = source.RightLine(x, y + height);
                    index = x + 1;
                    while (index < source[y].Length && source.RightLine(index, y + height) == bottom)
                        index++;
                    if (index == source[y].Length || source.TopLine(index, y + height) == LineType.None || source.BottomLine(index, y + height) != LineType.None || source.RightLine(index, y + height) != LineType.None)
                        continue;
                    if (index - x != width)
                        continue;

                    // Verify the right edge
                    var right = source.BottomLine(x + width, y);
                    index = y + 1;
                    while (index < source.NumLines && source.BottomLine(x + width, index) == right)
                        index++;
                    if (index == source.NumLines || source.LeftLine(x + width, index) == LineType.None || source.RightLine(x + width, index) != LineType.None || source.BottomLine(x + width, index) != LineType.None)
                        continue;
                    if (index - y != height)
                        continue;

                    // If all edges are single lines, this is not a box
                    if (top == LineType.Single && right == LineType.Single && bottom == LineType.Single && left == LineType.Single)
                        continue;

                    for (int xx = 0; xx <= width; xx++)
                    {
                        visited.AddSafe(x + xx, y);
                        visited.AddSafe(x + xx, y + height);
                    }
                    for (int yy = 0; yy <= height; yy++)
                    {
                        visited.AddSafe(x, y + yy);
                        visited.AddSafe(x + width, y + yy);
                    }

                    boxes.Add(new Box
                    {
                        X = x,
                        Y = y,
                        Width = width,
                        Height = height,
                        LineTypes = Helpers.MakeDictionary(top, right, bottom, left)
                    });
                }
            }

            // Determine the location of text lines within every box
            foreach (var box in boxes)
            {
                var curTextLines = new HashSet<TextLine>();
                for (int by = 1; by < box.Height; by++)
                {
                    var y = box.Y + by;
                    TextLine curTextLine = null;
                    var curLineText = new StringBuilder();
                    for (int bx = 1; bx < box.Width; bx++)
                    {
                        var x = box.X + bx;

                        if (source.AnyLine(x, y))
                        {
                            if (curTextLine != null)
                            {
                                curTextLine.Content = curLineText.ToString();
                                curTextLines.Add(curTextLine);
                                curTextLine = null;
                                curLineText.Clear();
                            }
                        }
                        else
                        {
                            if (curTextLine == null)
                                curTextLine = new TextLine { X = x, Y = y };
                            curLineText.Append(source[y][x]);
                        }
                    }
                    if (curTextLine != null)
                    {
                        curTextLine.Content = curLineText.ToString();
                        curTextLines.Add(curTextLine);
                    }
                }

                // Group text lines by vertical adjacency
                var textAreas = new List<TextLine[]>();
                while (curTextLines.Count > 0)
                {
                    var first = curTextLines.First();
                    curTextLines.Remove(first);
                    var curGroup = new List<TextLine> { first };
                    while (true)
                    {
                        var next = curTextLines.FirstOrDefault(one => curGroup.Any(two => (one.Y == two.Y + 1 || one.Y == two.Y - 1) && one.X + one.Content.Length > two.X && one.X < two.X + two.Content.Length));
                        if (next == null)
                            break;
                        curGroup.Add(next);
                        curTextLines.Remove(next);
                    }
                    curGroup.Sort(CustomComparer<TextLine>.By(l => l.Y).ThenBy(l => l.X));
                    textAreas.Add(curGroup.ToArray());
                }
                box.TextAreas = textAreas.ToArray();
            }

            return new FncFile { Boxes = boxes, Source = source };
        }
        private List<string> CompareDictionaries(Dictionary<string, object> publishedValues, Dictionary<string, string> editedValues)
        {
            var notMatchingFields = new List<string>();

            // Check if values match JUST by checking values from PUBLISHED values which is containing just data from coupled table (no document specific data)
            foreach (var publishedItem in publishedValues)
            {
                // Check if the column is present in both published and edited dictionaries
                // Kentico does not store field in CMS_Version history if its value is set null
                if (!editedValues.ContainsKey(publishedItem.Key))
                {
                    // Check if published value is also empty
                    if (!string.IsNullOrEmpty(publishedItem.Value.ToString()))
                    {
                        // Published value is not empty, but Edited value is
                        notMatchingFields.Add(publishedItem.Key);
                    }
                    continue;
                }

                // Handle different types of values
                if (publishedItem.Value is DateTime)
                {
                    // Compare dates
                    DateTime publishedDate;
                    DateTime editedDate;

                    DateTime.TryParse(publishedItem.Value.ToString(), out publishedDate);
                    DateTime.TryParse(editedValues[publishedItem.Key], out editedDate);

                    bool datesMatch = publishedDate.CompareTo(editedDate) == 0;

                    if (!datesMatch)
                    {
                        notMatchingFields.Add(publishedItem.Key);
                    }

                }
                else if (publishedItem.Value is bool)
                {
                    bool publishedBool;
                    bool editedBool;

                    bool.TryParse(publishedItem.Value.ToString(), out publishedBool);
                    bool.TryParse(editedValues[publishedItem.Key], out editedBool);

                    bool boolsMatch = publishedBool.CompareTo(editedBool) == 0;

                    if (!boolsMatch)
                    {
                        notMatchingFields.Add(publishedItem.Key);
                    }
                }
                else
                {
                    // Check if the column has the same value as edited value
                    if (!editedValues.Contains(new KeyValuePair<string, string>(publishedItem.Key, publishedItem.Value.ToString())))
                    {
                        notMatchingFields.Add(publishedItem.Key);
                    }
                }
            }

            return notMatchingFields;
        }
    public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: The argument is a null reference");

        try
        {
            IDictionary iDictionary = new Dictionary<object,object>();
            iDictionary.Contains(null);
            TestLibrary.TestFramework.LogError("101", "The ArgumentNullException was not thrown as expected");
            retVal = false;
        }
        catch (ArgumentNullException)
        {
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
        public void GetOrAddTestCase1()
        {
            var dictionary = new Dictionary<String, String>();
            var keyValuePair = new KeyValuePair<String, String>( RandomValueEx.GetRandomString(),
                                                                 RandomValueEx.GetRandomString() );

            var actual = dictionary.GetOrAdd( keyValuePair );
            Assert.AreEqual( keyValuePair.Value, actual );
            Assert.IsTrue( dictionary.Contains( keyValuePair ) );
            Assert.AreEqual( 1, dictionary.Count );

            actual = dictionary.GetOrAdd( keyValuePair );
            Assert.AreEqual( keyValuePair.Value, actual );
            Assert.IsTrue( dictionary.Contains( keyValuePair ) );
            Assert.AreEqual( 1, dictionary.Count );
        }
    public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown.");

        try
        {
            IDictionary dictionary = new Dictionary<string, string>();

            dictionary.Add("txt", "notepad.exe");
            dictionary.Add("bmp", "paint.exe");
            dictionary.Add("dib", "paint.exe");
            dictionary.Add("rtf", "wordpad.exe");

            string key = null;

            dictionary.Contains(key);

            TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown.");
            retVal = false;
        }
        catch (ArgumentNullException) { }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Example #29
0
        private void gridViewTags_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            GridView view = gridViewTags;
            if (!IsLoaded) {
                if (!Cleared) {
                    if (view != null && view.SelectedRowsCount > 0) {
                        Cleared = true;
                        view.ClearSelection();
                    }
                }
                if (dictionarySelectedTags != null) {
                    KeyValuePair<string, int> kvTag;
                    questiontag qt;
                    for (int i = 0; i < view.RowCount; i++) {
                        qt = view.GetRow(i) as questiontag;
                        if (qt != null) {
                            kvTag = dictionarySelectedTags.FirstOrDefault(d => d.Value == qt.id);
                            if (kvTag.Key != null && kvTag.Value != 0) {
                                if (!view.IsRowSelected(i)) {
                                    view.SelectRow(i);
                                    view.FocusedRowHandle = i;
                                }
                            }
                        }
                    }
                    textEditSelectedTags.Text = string.Join(",", dictionarySelectedTags.Keys.ToArray());
                }
                IsLoaded = true;
                if (view.RowCount <= 0) {
                    btnEditTag.Enabled = false;
                    btnDeleteTag.Enabled = false;
                } else {
                    btnEditTag.Enabled = true;
                    btnDeleteTag.Enabled = true;
                }
                return;
            }

            if (view == null || view.SelectedRowsCount == 0) return;

            if (view.SelectedRowsCount > 1) btnEditTag.Enabled = false;
            else btnEditTag.Enabled = true;

            questiontag[] rows = new questiontag[view.SelectedRowsCount];
            for (int i = 0; i < view.SelectedRowsCount; i++) {
                rows[i] = view.GetRow(view.GetSelectedRows()[i]) as questiontag;
            }

            view.BeginSort();
            dictionarySelectedTags = new Dictionary<string, int>();
            try
            {
                //[@jeff 09.27.2011]: http://brightvision.jira.com/browse/PLATFORM-541
                KeyValuePair<string, int> iTag;
                foreach (questiontag row in rows)
                    if (row != null)
                    {
                        iTag = new KeyValuePair<string, int>(row.title, row.id);
                        if (!dictionarySelectedTags.Contains(iTag) && !dictionarySelectedTags.Keys.Contains(row.title))
                            dictionarySelectedTags.Add(row.title, row.id);
                    }
            }
            finally
            {
                view.EndSort();
            }
            textEditSelectedTags.Text = string.Join(",", dictionarySelectedTags.Keys.ToArray());
        }
 public void TestDictionary()
 {
     var dict = new Dictionary<YamlNode, int>();
     var key = (YamlScalar)"abc";
     dict[key] = 4;
     Assert.Throws<ArgumentException>(() => dict.Add(key, 5));
     key.Value = "def";
     Assert.IsFalse(dict.ContainsKey(key));
     Assert.IsFalse(dict.Remove(key));
     Assert.IsFalse(dict.Contains(new KeyValuePair<YamlNode, int>(key, 4)));
     var entry = dict.First(e => e.Key == key);
     Assert.IsFalse(dict.Contains(entry));
     Assert.IsFalse(((ICollection<KeyValuePair<YamlNode,int>>)dict).Remove(entry));
     Assert.IsTrue(( (ICollection<YamlNode>)dict.Keys ).IsReadOnly);
 }