Esempio n. 1
0
        public void TokenFunctionTest(string equalsToken, string plusToken, int collectionSize)
        {
            var kvps = new KeyValuePair <string, string> [collectionSize];

            Random rand1 = new Random();

            for (int i = 0; i < collectionSize; i++)
            {
                kvps[i] = new KeyValuePair <string, string>($"key{i}", $"{Guid.NewGuid()}{Guid.NewGuid()}{Guid.NewGuid()}");
            }

            string value1 = kvps[rand1.Next(0, collectionSize - 1)].Value;
            string value2 = kvps[rand1.Next(0, collectionSize - 1)].Value;

            string queryString = $"value{equalsToken}{value1}{plusToken}{value2}";

            var sw         = Stopwatch.StartNew();
            var expression = ExpressionBuilder.BuildFunction <KeyValuePair <string, string> >(queryString);

            kvps.FirstOrDefault(expression).Should().NotBeNull().And
            .Should().BeAnyOf(kvps.Where(kvp => kvp.Value == value1 || kvp.Value == value2));

            kvps.Where(expression).Should().NotBeNullOrEmpty().And
            .Contain(kvps.Where(kvp => kvp.Value == value1 || kvp.Value == value2));

            kvps.Any(expression).Should().BeTrue();
            kvps.All(expression).Should().BeFalse();
            kvps.Count(expression).Should().Be(kvps.Count(q => q.Value == value1 || q.Value == value2));

            sw.Stop();
        }
Esempio n. 2
0
        public void IntTest(int collectionSize)
        {
            var kvps = new KeyValuePair <string, int> [collectionSize];

            Random rand1 = new Random();

            for (int i = 0; i < collectionSize; i++)
            {
                Random rand2 = new Random(rand1.Next(0, int.MaxValue));

                kvps[i] = new KeyValuePair <string, int>($"key{i}", rand2.Next(1, collectionSize));
            }

            int value1 = kvps[rand1.Next(0, collectionSize - 1)].Value;
            int value2 = kvps[rand1.Next(0, collectionSize - 1)].Value;

            string queryString = $"value={value1}%2B{value2}";

            var sw         = Stopwatch.StartNew();
            var expression = ExpressionBuilder.BuildFunction <KeyValuePair <string, int> >(queryString);

            kvps.FirstOrDefault(expression).Should().NotBeNull().And
            .Should().BeAnyOf(kvps.Where(kvp => kvp.Value == value1 || kvp.Value == value2));

            kvps.Where(expression).Should().NotBeNullOrEmpty().And
            .Contain(kvps.Where(kvp => kvp.Value == value1 || kvp.Value == value2));

            kvps.Any(expression).Should().BeTrue();
            kvps.All(expression).Should().BeFalse();
            kvps.Count(expression).Should().Be(kvps.Count(q => q.Value == value1 || q.Value == value2));

            sw.Stop();
        }
Esempio n. 3
0
        public void DateTimeListTest(int collectionSize, int maxSubCollectionSize)
        {
            var kvps = new KeyValuePair <string, List <DateTime> > [collectionSize];

            int day   = 1;
            int month = 1;
            int year  = 2016;

            for (int i = 0; i < collectionSize; i++)
            {
                string key = $"key{i}";

                KeyValuePair <string, List <DateTime> > kvp = new KeyValuePair <string, List <DateTime> >(key, new List <DateTime>());

                for (int j = 0; j < maxSubCollectionSize; j++)
                {
                    kvp.Value.Add(new DateTime(year, month, day++));

                    if (day > 28)
                    {
                        day = 1;
                        month++;
                    }

                    if (month <= 12)
                    {
                        continue;
                    }

                    month = 1;
                    year++;
                }

                kvps[i] = kvp;
            }

            Random rand = new Random();

            DateTime value1 = kvps[rand.Next(0, collectionSize - 1)].Value[0];
            DateTime value2 = kvps[rand.Next(0, collectionSize - 1)].Value[0];

            string queryString = $"value={value1}%2B{value2}";

            var sw = Stopwatch.StartNew();

            var expression = ExpressionBuilder.BuildFunction <KeyValuePair <string, List <DateTime> > >(queryString);

            kvps.FirstOrDefault(expression).Should().NotBeNull().And
            .Should().BeAnyOf(kvps.Where(kvp => kvp.Value.Contains(value1) || kvp.Value.Contains(value2)));

            kvps.Where(expression).Should().NotBeNullOrEmpty().And
            .Contain(kvps.Where(kvp => kvp.Value.Contains(value1) || kvp.Value.Contains(value2)));

            kvps.Any(expression).Should().BeTrue();
            kvps.All(expression).Should().BeFalse();
            kvps.Count(expression).Should().Be(kvps.Count(q => q.Value.Contains(value1) || q.Value.Contains(value2)));

            sw.Stop();
        }
Esempio n. 4
0
        public void UT_CacheDictionaryObject(Context context)
        {
            string key1 = "UT_CacheDictionaryObject1";

            context.Cache.Remove(key1);
            var users = GetUsers();
            var rd    = context.Collections.GetRedisDictionary <int, User>(key1);
            // Test AddMultiple
            var usersKv = users.Select(x => new KeyValuePair <int, User>(x.Id, x));

            rd.AddRange(usersKv);
            // Test GetEnumerator
            foreach (var item in rd)
            {
                Assert.IsTrue(users.Any(u => u.Id == item.Key));
            }
            // Test Count
            Assert.AreEqual(users.Count, rd.Count);
            // Test ContainsKey
            Assert.IsTrue(rd.ContainsKey(users[1].Id));
            // Test Contains
            Assert.IsTrue(rd.Contains(new KeyValuePair <int, User>(users.Last().Id, users.Last())));
            // Test Add
            rd.Add(0, new User()
            {
                Id = 0
            });
            Assert.AreEqual(users.Count + 1, rd.Count);
            Assert.AreEqual(0, rd[0].Id);
            // Test Remove
            rd.Remove(0);
            Assert.IsFalse(rd.ContainsKey(0));
            // Test Keys
            foreach (var k in rd.Keys)
            {
                Assert.IsTrue(users.Any(u => u.Id == k));
            }
            // Test Values
            foreach (var u in rd.Values)
            {
                Assert.IsTrue(users.Any(user => user.Id == u.Id));
            }
            // Test TryGetValue
            User userTest = new User();
            bool b        = rd.TryGetValue(999, out userTest);

            Assert.IsFalse(b);
            Assert.IsNull(userTest);
            b = rd.TryGetValue(1, out userTest);
            Assert.IsTrue(b);
            Assert.AreEqual(1, userTest.Id);
            // Test CopyTo
            var array = new KeyValuePair <int, User> [50];

            rd.CopyTo(array, 10);
            Assert.AreEqual(users.Count, array.Count(x => x.Value != null));
            // Test Clear
            rd.Clear();
            Assert.AreEqual(0, rd.Count);
        }
Esempio n. 5
0
        private static Dictionary <int, Type> generateIdTypeHashMap <T>()
        {
            Dictionary <int, Type> resultDictionary = new Dictionary <int, Type>();
            Type type = typeof(T);

            var types = AppDomain.CurrentDomain.GetAssemblies()
                        .SelectMany(s => s.GetTypes())
                        .Where(p => type.IsAssignableFrom(p) && p.IsClass && !p.IsAbstract);


            KeyValuePair <string, Type>[] nameTypePairs = new KeyValuePair <string, Type> [types.Count()];

            // and put them in a static dictionary.
            int index = 0;

            foreach (Type t in types)
            {
                nameTypePairs[index++] = new KeyValuePair <string, Type>(t.Name, t);
            }

            Array.Sort(nameTypePairs, keyComparison);

            for (int i = 0; i < nameTypePairs.Count(); i++)
            {
                resultDictionary.Add(i, nameTypePairs[i].Value);
            }
            return(resultDictionary);
        }
 public void UT_CacheDictionaryObject(Context context)
 {
     string key1 = "UT_CacheDictionaryObject1";
     context.Cache.Remove(key1);
     var users = GetUsers();
     var rd = context.Collections.GetRedisDictionary<int, User>(key1);
     // Test AddMultiple
     var usersKv = users.Select(x => new KeyValuePair<int, User>(x.Id, x));
     rd.AddRange(usersKv);
     // Test GetEnumerator
     foreach (var item in rd)
     {
         Assert.IsTrue(users.Any(u => u.Id == item.Key));
     }
     // Test Count
     Assert.AreEqual(users.Count, rd.Count);
     // Test ContainsKey
     Assert.IsTrue(rd.ContainsKey(users[1].Id));
     // Test Contains
     Assert.IsTrue(rd.Contains(new KeyValuePair<int, User>(users.Last().Id, users.Last())));
     // Test Add
     rd.Add(0, new User() {Id = 0});
     Assert.AreEqual(users.Count + 1, rd.Count);
     Assert.AreEqual(0, rd[0].Id);
     // Test Remove
     rd.Remove(0);
     Assert.IsFalse(rd.ContainsKey(0));
     // Test Keys
     foreach (var k in rd.Keys)
     {
         Assert.IsTrue(users.Any(u => u.Id == k));
     }
     // Test Values
     foreach (var u in rd.Values)
     {
         Assert.IsTrue(users.Any(user => user.Id == u.Id));
     }
     // Test TryGetValue
     User userTest = new User();
     bool b = rd.TryGetValue(999, out userTest);
     Assert.IsFalse(b);
     Assert.IsNull(userTest);
     b = rd.TryGetValue(1, out userTest);
     Assert.IsTrue(b);
     Assert.AreEqual(1, userTest.Id);
     // Test CopyTo
     var array = new KeyValuePair<int, User>[50];
     rd.CopyTo(array, 10);
     Assert.AreEqual(users.Count, array.Count(x => x.Value != null));
     // Test Clear
     rd.Clear();
     Assert.AreEqual(0, rd.Count);
 }
Esempio n. 7
0
        static void Main()
        {
            #region Initial boring stuff

            DynamitConfig.Init(enableEscapeStrings: true);
            foreach (var x in Db.SQL <DDictionary>($"SELECT t FROM {typeof(DDictionary).FullName} t"))
            {
                Db.TransactAsync(() => x.Delete());
            }
            foreach (var x in Db.SQL <DList>($"SELECT t FROM {typeof(DList).FullName} t"))
            {
                Db.TransactAsync(() => x.Delete());
            }

            #endregion

            // TEST BEGIN

            #region Inserting and removing values of various types

            MyDict myDict = null;
            Db.TransactAsync(() =>
            {
                myDict        = new MyDict();
                dynamic d     = myDict;
                d.Id          = 1;
                d.Bool        = true;
                d.Byte        = (byte)125;
                d.DateTime    = DateTime.Now;
                d.Decimal     = 123.123123123123M;
                d.Double      = 123.123321123321123321;
                d.Int         = 124421;
                d.Long        = 33219239321L;
                d.Sbyte       = (sbyte)123;
                d.Short       = (short)332;
                d.Single      = (float)123.1;
                d.String      = "\"ASddsddsa\"";
                d.Uint        = (uint)123321;
                d.Ulong       = (ulong)123321123;
                d.Ushort      = (ushort)12331;
                d.Null        = null;
                d.Thing       = "SwooBoo";
                d.EmptyString = "";
                d.JustAQuote  = "\"";

                new MyDict
                {
                    ["Id"]     = 2,
                    ["Byte"]   = (byte)12,
                    ["String"] = "A",
                    ["Bool"]   = true,
                    ["Goo"]    = 123
                };

                new MyDict
                {
                    Foo        = "TheThird",
                    ["Id"]     = 3,
                    ["Byte"]   = (byte)122,
                    ["String"] = "A",
                    ["Bool"]   = true
                };
            });

            Assert(!myDict.ContainsKey("Null"));
            Assert(myDict.ContainsKey("Thing"));
            Db.TransactAsync(() => myDict["Thing"] = null);
            Assert(!myDict.ContainsKey("Thing"));

            #endregion

            #region Checking that things exist

            Assert(Db.SQL <DDictionary>("SELECT t FROM Dynamit.DDictionary t").Any());
            Assert(Db.SQL <DKeyValuePair>("SELECT t FROM Dynamit.DKeyValuePair t").Any());
            Assert(Db.SQL <ValueObject>("SELECT t FROM Dynamit.ValueObjects.ValueObject t").Any());

            #endregion

            #region Type consistency assertions

            dynamic dyn = myDict;
            Assert(dyn.Id is int);
            Assert(dyn.Bool is bool);
            Assert(dyn.Byte is byte);
            Assert(dyn.DateTime is DateTime);
            Assert(dyn.Decimal is Decimal);
            Assert(dyn.Double is double);
            Assert(dyn.Int is int);
            Assert(dyn.Long is long);
            Assert(dyn.Sbyte is sbyte);
            Assert(dyn.Short is short);
            Assert(dyn.Single is float);
            Assert(dyn.String is string);
            Assert(dyn.Uint is uint);
            Assert(dyn.Ulong is ulong);
            Assert(dyn.Ushort is ushort);
            Assert(dyn.Null is null);

            #endregion

            #region DDictionary instance member checks

            Assert(myDict.KvpTable == typeof(MyDictKVP).FullName);
            Db.TransactAsync(() => myDict.Add("Test1", "Swoo"));
            Assert(myDict.TryGetValue("Test1", out var t01) && t01.Equals("Swoo"));
            var test2kvp = new KeyValuePair <string, object>("Test2", "Goo");
            Db.TransactAsync(() => myDict.Add(test2kvp));
            Assert(myDict.TryGetValue("Test2", out var t02) && t02.Equals("Goo"));
            Assert(myDict.Contains(test2kvp));
            Assert(myDict.Count == myDict.KeyValuePairs.Count());
            Assert(myDict.ContainsKey("Test2"));
            Db.TransactAsync(() => myDict.Remove("Test1"));
            Assert(!myDict.TryGetValue("Test1", out t01));
            Db.TransactAsync(() => myDict.Remove("Test1"));
            Assert(!myDict.TryGetValue("Test1", out t01));
            Db.TransactAsync(() => myDict.Remove(test2kvp.Key));
            Assert(!myDict.TryGetValue("Test2", out t01));
            var arr = new KeyValuePair <string, object> [100];
            myDict.CopyTo(arr, 0);
            Assert(arr[0].Key != null);
            Assert(arr.Count(a => a.Key != null) == myDict.KeyValuePairs.Count());

            MyDict testThingy = null;
            Db.TransactAsync(() => testThingy = new MyDict {
                ["Test"] = true
            });
            Assert(testThingy.Any());
            Db.TransactAsync(() => testThingy.Clear());
            Assert(!testThingy.Any());
            Db.TransactAsync(() => testThingy.Delete());

            object thing = myDict.SafeGet("Swoofooboasd");
            Assert(thing == null);
            var otherThing = myDict.SafeGet("Bool");
            Assert(otherThing is bool);

            #endregion

            #region Finder

            var all = Finder <MyDict> .All;
            var As  = Finder <MyDict> .Where("String", EQUALS, "A");

            var third = Finder <MyDict> .Where("Id", EQUALS, 3);

            var firstAndSecond = Finder <MyDict> .All.Where(dict => dict["Id"] < 3);

            var second = Finder <MyDict> .Where(("String", EQUALS, "A"), ("Byte", NOT_EQUALS, 122));

            var alsoThird = Finder <MyDict> .Where(("String", EQUALS, "A")).Where(dict => dict["Byte"] == 122).FirstOrDefault();

            var alsoThird3 = Finder <MyDict> .Where("$Foo", EQUALS, "TheThird").FirstOrDefault();

            Assert(alsoThird.Equals(alsoThird3));

            var objectNo = myDict.GetObjectNo();
            var objectId = myDict.GetObjectID();
            var _first   = Finder <MyDict> .Where("$ObjectID", EQUALS, objectId).FirstOrDefault();

            var _first2 = Finder <MyDict> .Where("$ObjectNo", EQUALS, objectNo).FirstOrDefault();

            Assert(_first.Equals(_first2) && _first.Equals(myDict));

            var firstAndThird = Finder <MyDict> .Where("Goo", EQUALS, null);

            var alsoSecond = Finder <MyDict> .Where("Goo", NOT_EQUALS, null);

            var json = JsonConvert.SerializeObject(all);

            var alsoAll1 = Finder <MyDict> .Where();

            var alsoAll2 = Finder <MyDict> .Where(("Gooo", EQUALS, null));

            var alsoAll3 = Finder <MyDict> .Where(("Gooo", EQUALS, null));

            Assert(alsoAll1.Count() == 3);
            Assert(alsoAll2.Count() == 3);
            Assert(alsoAll3.Count() == 3);

            Assert(all.Count() == 3);
            Assert(As.Count() == 2);
            bool thirdOk = third.Count() == 1 && third.First()["Id"] == 3;
            Assert(thirdOk);
            var firstAndSecondOk = firstAndSecond.Count() == 2;
            Assert(firstAndSecondOk);
            bool secondOk = second.Count() == 1 && second.First()["Id"] == 2;
            Assert(secondOk);
            bool alsoThirdOk = third.Count() == 1 && third.First()["Id"] == 3;
            Assert(alsoThirdOk);

            Assert(firstAndThird.Count() == 2);
            bool alsoSecondOk = alsoSecond.Count() == 1 && alsoSecond.First()["Id"] == 2;
            Assert(alsoSecondOk);

            #endregion

            #region Handling errors in input

            Db.TransactAsync(() =>
            {
                try
                {
                    myDict["T"] = new { A = "ASD" };
                }
                catch (Exception e)
                {
                    Assert(e is InvalidValueTypeException);
                }
                try
                {
                    myDict["V"] = new Stopwatch();
                }
                catch (Exception e)
                {
                    Assert(e is InvalidValueTypeException);
                }
                try
                {
                    myDict["X"] = new JObject {
                        ["A"] = 123
                    };
                }
                catch (Exception e)
                {
                    Assert(e is InvalidValueTypeException);
                }
            });
            Assert(!myDict.ContainsKey("T"));
            Assert(!myDict.ContainsKey("V"));
            Assert(!myDict.ContainsKey("X"));

            #endregion

            #region JSON serialization

            var asJson = JsonConvert.SerializeObject(myDict);

            #endregion

            #region Deleting rows

            Db.TransactAsync(() =>
            {
                myDict.Delete();
                second.First().Delete();
                third.First().Delete();
            });

            #endregion

            #region Checking that things don't exist anymore

            Assert(!Db.SQL <DDictionary>("SELECT t FROM Dynamit.DDictionary t").Any());
            Assert(!Db.SQL <DKeyValuePair>("SELECT t FROM Dynamit.DKeyValuePair t").Any());
            Assert(!Db.SQL <ValueObject>("SELECT t FROM Dynamit.ValueObjects.ValueObject t").Any());

            #endregion

            // TEST END

            var s = 0;
        }
 /// <summary>
 /// Draw a piechart
 /// </summary>
 private static void DrawPieChart(ref Chart chart, KeyValuePair<string, double>[] dataSeries)
 {
     if(dataSeries == null || dataSeries.Count() == 0 || chart == null || chart.Series == null)
     {
         return;
     }
     if (chart.Series != null && chart.Series.Count == 0)
     {
         chart.Series.Add(new PieSeries());
     }
     ((PieSeries)chart.Series[0]).ItemsSource = dataSeries;
 }
        public void GetTransactionsForSearchCriterias(KeyValuePair<string, string>[] queryExpected,
                                                      ConsumerTransactionsTestSource.FunctionHolder getCall)
        {
            var httpClient = Substitute.For<IHttpClient>();
            var response = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent(@"{
                            receiptId : '134567',
                            type : 'Create',
                            judoId : '12456',
                            originalAmount : 20,
                            amount : 20,
                            netAmount : 20,
                            cardDetails :
                                {
                                    cardLastfour : '1345',
                                    endDate : '1214',
                                    cardToken : 'ASb345AE',
                                    cardType : 'VISA'
                                },
                            currency : 'GBP',
                            consumer :
                                {
                                    consumerToken : 'B245SEB',
                                    yourConsumerReference : 'Consumer1'
                                }
                            }")};

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var responseTask = new TaskCompletionSource<HttpResponseMessage>();
            responseTask.SetResult(response);

            httpClient.SendAsync(Arg.Any<HttpRequestMessage>()).Returns(responseTask.Task);

            var client = new Client(new Connection(httpClient,
                                                    DotNetLoggerFactory.Create,
                                                    "http://something.com"));

            var judo = new JudoPayApi(DotNetLoggerFactory.Create, client);

            getCall.Func(judo.Consumers);

            httpClient.Received().SendAsync(Arg.Any<HttpRequestMessage>());
            var calls = httpClient.ReceivedCalls();

            // ReSharper disable once PossibleNullReferenceException
            var request = calls.FirstOrDefault(call => call.GetMethodInfo().Name == "SendAsync").
                                    GetArguments().FirstOrDefault() as HttpRequestMessage;

            Assert.IsNotNull(request);

            var numberOfMatchingParameters = request.RequestUri.Query
                                    .Remove(0, 1)
                                    .Split('&').Select(kv =>
                                    {
                                        var keyValue = kv.Split('=');
                                        return new KeyValuePair<string, string>(keyValue[0], keyValue[1]);
                                    }).Intersect(queryExpected).Count();

            Assert.AreEqual(queryExpected.Count(), numberOfMatchingParameters);
            Assert.AreEqual("payments", request.RequestUri.AbsolutePath.Split('/').Last());
        }