Beispiel #1
0
        public void OrderedRegistry()
        {
            var reg = new OrderedRegistry <OrderedClazz>();

            Aver.IsTrue(reg.Register(new OrderedClazz("Apple", 8, 1)));
            Aver.IsTrue(reg.Register(new OrderedClazz("Banana", -2, 2)));
            Aver.IsFalse(reg.Register(new OrderedClazz("Apple", 22, 3)));

            Aver.AreEqual(2, reg.Count);

            Aver.AreEqual(1, reg["Apple"].Data);
            Aver.AreEqual(2, reg["Banana"].Data);
            Aver.AreObjectsEqual(null, reg["Grapes"]);

            var ordered = reg.OrderedValues.ToArray();

            Aver.AreEqual(2, ordered.Length);
            Aver.AreEqual("Banana", ordered[0].Name);
            Aver.AreEqual("Apple", ordered[1].Name);

            Aver.IsTrue(reg.Register(new OrderedClazz("Zukini", 0, 180)));

            ordered = reg.OrderedValues.ToArray();
            Aver.AreEqual(3, ordered.Length);
            Aver.AreEqual("Banana", ordered[0].Name);
            Aver.AreEqual("Zukini", ordered[1].Name);
            Aver.AreEqual("Apple", ordered[2].Name);


            Aver.IsFalse(reg.Unregister(new OrderedClazz("I was never added before", 1, 1)));
            Aver.AreEqual(3, reg.Count);

            Aver.IsTrue(reg.Unregister(new OrderedClazz("Apple", 2, 1)));
            Aver.AreEqual(2, reg.Count);
            Aver.AreObjectsEqual(null, reg["Apple"]);
            Aver.AreEqual(2, reg["Banana"].Data);
            Aver.AreEqual(180, reg["Zukini"].Data);
        }
Beispiel #2
0
        public void AddAndRetainAll(int COUNT)
        {
            using (var cache = PileCacheTestCore.MakeDurableCache())
            {
                var tA = cache.GetOrCreateTable <Guid>("A");
                var tB = cache.GetOrCreateTable <string>("B");

                Aver.AreObjectsEqual(CollisionMode.Durable, tA.CollisionMode);
                Aver.AreObjectsEqual(CollisionMode.Durable, tB.CollisionMode);


                var dict = new Dictionary <Guid, string>();

                for (var i = 0; i < COUNT; i++)
                {
                    var key   = Guid.NewGuid();
                    var value = "this is a value of " + key;
                    dict.Add(key, value);

                    var pr = tA.Put(key, value);
                    Aver.IsTrue(PutResult.Inserted == pr);

                    pr = tB.Put(key.ToString(), value);
                    Aver.IsTrue(PutResult.Inserted == pr);
                }

                Aver.AreEqual(COUNT, dict.Count);
                Aver.AreEqual(COUNT, tA.Count);
                Aver.AreEqual(COUNT, tB.Count);

                foreach (var kvp in  dict)
                {
                    Aver.IsTrue(tA.ContainsKey(kvp.Key));
                    Aver.AreEqual(kvp.Value, tA.Get(kvp.Key) as string);
                    Aver.AreEqual(kvp.Value, tB.Get(kvp.Key.ToString()) as string);
                }
            }
        }
        public void Rowset_FromJSON_FieldMissed(bool rowsAsMap)
        {
            var row = new Person {
                Name = "Henry", Age = 43
            };
            var rowSet = new Rowset(row.Schema);

            rowSet.Add(row);
            var options = new Azos.Serialization.JSON.JSONWritingOptions
            {
                RowsetMetadata = true,
                RowsAsMap      = rowsAsMap
            };
            var json = rowSet.ToJSON(options);
            var map  = JSONReader.DeserializeDataObject(json) as JSONDataMap;
            var rows = (map["Rows"] as IList <object>);

            if (rowsAsMap)
            {
                var pers = rows[0] as IDictionary <string, object>;
                pers.Remove("Age");
            }
            else
            {
                var pers = rows[0] as IList <object>;
                pers.RemoveAt(1);
            }

            bool allMatched;
            var  trg = RowsetBase.FromJSON(map, out allMatched);

            Aver.IsFalse(allMatched);
            var trgRow = trg[0];

            Aver.AreEqual(trgRow.Schema.FieldCount, 2);
            Aver.AreObjectsEqual(trgRow["Name"], "Henry");
            Aver.IsNull(trgRow["Age"]);
        }
Beispiel #4
0
        public static void KeyString_ManyPutGet(int cnt)
        {
            using (var cache = MakeCache())
            {
                cache.TableOptions.Register(new TableOptions("A")
                {
                    InitialCapacity = cnt //*2,
                                          //   MaximumCapacity = cnt*2
                });

                var tA = cache.GetOrCreateTable <string>("A", StringComparer.Ordinal);

                for (var i = 0; i < cnt; i++)
                {
                    tA.Put(i.ToString(), "value-" + i.ToString());
                }

                var hit  = 0;
                var miss = 0;
                for (var i = 0; i < cnt; i++)
                {
                    var d = tA.Get(i.ToString());
                    if (d == null)
                    {
                        miss++;
                    }
                    else
                    {
                        hit++;
                        Aver.AreObjectsEqual("value-" + i.ToString(), d);
                    }
                }
                Console.WriteLine("Did {0:n0} ->  hits: {1:n0} ({2:n0}%)  ;  misses: {3:n0} ({4:n0}%)", cnt, hit, (hit / (double)cnt) * 100d, miss, (miss / (double)cnt) * 100d);

                Aver.IsTrue(hit > miss);
                Aver.IsTrue((miss / (double)cnt) <= 0.1d);//misses <=10%
            }
        }
Beispiel #5
0
        public void Object_3()
        {
            var json = @"{ s: $'/*
      ""a"": 1, ''b'': true, ""c"": null, d: false, e: {}, |* some comment *| f: [],
       g: ''string'',

    this
    is
    all
    comment

       h: ""string2""
 //this is a complex
 //multiline

  ,
    list: [
        +11,   -12,





        -345e3, null ,
      ], //notice trailing comma
    */',
     a: -123, }";
            var src  = new StringSource(json);
            var got  = JazonParser.Parse(src, true) as JsonDataMap;

            Aver.IsNotNull(got);

            got["s"].See();

            Aver.AreEqual(2, got.Count);
            Aver.IsTrue(got["s"].ToString().MatchPattern("/* 'b': true*g: 'string',*+11,   -12*trailing comma*/"));
            Aver.AreObjectsEqual(-123, got["a"]);
        }
Beispiel #6
0
        public void CopyFields_TypedRow_To_Amorphous_NotIncludeAmorphous()
        {
            var from = new Person
            {
                FirstName        = "Ivan",
                LastName         = "Petrov",
                Amount           = 10,
                Classification   = "class1",
                YearsWithCompany = null
            };

            var to = new AmorphousDynamicDoc(Schema.GetForTypedDoc(typeof(Empty)));

            to.AmorphousData["field1"]    = 123;
            to.AmorphousData["FirstName"] = "John";

            from.CopyFields(to, includeAmorphousData: false);

            Aver.AreEqual(0, to.Schema.FieldCount);
            Aver.AreEqual(2, to.AmorphousData.Count);
            Aver.AreObjectsEqual(123, to.AmorphousData["field1"]);
            Aver.AreObjectsEqual("John", to.AmorphousData["FirstName"]);
        }
Beispiel #7
0
        public void T020_Comparers()
        {
            using (var cache = PileCacheTestCore.MakeCache())
            {
                var tA = cache.GetOrCreateTable <string>("A", StringComparer.Ordinal);
                var tB = cache.GetOrCreateTable <string>("B", StringComparer.OrdinalIgnoreCase);

                Aver.IsTrue(PutResult.Inserted == tA.Put("key1", "avalue1"));
                Aver.IsTrue(PutResult.Inserted == tA.Put("Key1", "avalue2"));
                Aver.IsTrue(PutResult.Inserted == tB.Put("key1", "bvalue1"));
                Aver.IsTrue(PutResult.Replaced == tB.Put("Key1", "bvalue2"));

                Aver.AreEqual(2, tA.Count);
                Aver.AreEqual(1, tB.Count);

                Aver.AreObjectsEqual("avalue1", tA.Get("key1"));
                Aver.AreObjectsEqual("avalue2", tA.Get("Key1"));
                Aver.IsNull(tA.Get("key3"));

                Aver.AreObjectsEqual("bvalue2", tB.Get("key1"));
                Aver.AreObjectsEqual("bvalue2", tB.Get("Key1"));
            }
        }
Beispiel #8
0
        public void ErlPortTest()
        {
            var t = new ErlPort("test", 10, 1);

            Aver.IsTrue(t.Equals(new ErlPort("test", 10, 1)));
            Aver.AreObjectsEqual(t, new ErlPort("test", 10, 1));
            Aver.AreEqual(1, new ErlPort("tesu", 10, 1).CompareTo(t));
            Aver.AreEqual(-1, new ErlPort("tess", 10, 1).CompareTo(t));
            Aver.AreEqual(-1, new ErlPort("test", 9, 1).CompareTo(t));
            Aver.AreEqual(1, new ErlPort("test", 12, 1).CompareTo(t));
            Aver.AreEqual(-1, new ErlPort("test", 10, 0).CompareTo(t));
            Aver.AreEqual(1, new ErlPort("test", 10, 2).CompareTo(t));
            Aver.AreEqual("#Port<test.10>", t.ToString());
            Aver.AreEqual("#Port<test.10>", t.ValueAsString);
            Aver.IsTrue(t.IsScalar);
            Aver.IsTrue(ErlTypeOrder.ErlPort == t.TypeOrder);

            Aver.IsTrue(t.Matches(new ErlPort("test", 10, 1)));
            Aver.IsTrue(new ErlVarBind().SequenceEqual(t.Match(new ErlPort("test", 10, 1))));

            doesNotThrow(() => { var x = t.ValueAsObject; });
            Aver.Throws <ErlIncompatibleTypesException>(() => { var x = t.ValueAsInt; });
            Aver.Throws <ErlIncompatibleTypesException>(() => { var x = t.ValueAsLong; });
            Aver.Throws <ErlIncompatibleTypesException>(() => { var x = t.ValueAsDecimal; });
            Aver.Throws <ErlIncompatibleTypesException>(() => { var x = t.ValueAsDateTime; });
            Aver.Throws <ErlIncompatibleTypesException>(() => { var x = t.ValueAsTimeSpan; });
            Aver.Throws <ErlIncompatibleTypesException>(() => { var x = t.ValueAsDouble; });
            Aver.AreEqual("#Port<test.10>", t.ValueAsString);
            Aver.Throws <ErlIncompatibleTypesException>(() => { var x = t.ValueAsBool; });
            Aver.Throws <ErlIncompatibleTypesException>(() => { var x = t.ValueAsChar; });
            Aver.Throws <ErlIncompatibleTypesException>(() => { var x = t.ValueAsByteArray; });

            IErlObject temp = null;

            Aver.IsFalse(t.Subst(ref temp, new ErlVarBind()));
            Aver.IsTrue(t.Visit(false, (acc, o) => acc |= o is ErlPort));
        }
Beispiel #9
0
        public void SetValuesAsDifferentTypes()
        {
            var person = new DynamicDoc(Schema.GetForTypedDoc(typeof(Person)));

            person["ID"]           = "POP1";
            person["FirstName"]    = "Oleg";
            person["LastName"]     = "Popov";
            person["DOB"]          = new DateTime(1953, 12, 10);
            person["YearsInSpace"] = 12;

            Aver.AreObjectsEqual("POP1", person["ID"]);
            Aver.AreObjectsEqual("Oleg", person["FirstName"]);
            Aver.AreObjectsEqual("Popov", person["LastName"]);
            Aver.AreObjectsEqual(new DateTime(1953, 12, 10), person["DOB"]);
            Aver.AreObjectsEqual(12, person["YearsInSpace"]);

            person["DOB"] = "05/15/2009 18:00";
            Aver.AreObjectsEqual(new DateTime(2009, 5, 15, 18, 0, 0), person["DOB"]);

            person["DOB"] = null;
            Aver.IsNull(person["DOB"]);

            person["YearsInSpace"] = "-190";
            Aver.AreObjectsEqual(-190, person["YearsInSpace"]);

            person["Description"] = 2 + 2;
            Aver.AreObjectsEqual("4", person["Description"]);

            person["Amount"] = "180.12";
            Aver.AreObjectsEqual(180.12m, person["Amount"]);

            person["GoodPerson"] = "true";
            Aver.AreObjectsEqual(true, person["GoodPerson"]);

            person["LuckRatio"] = 123;
            Aver.AreObjectsEqual(123d, person["LuckRatio"]);
        }
Beispiel #10
0
        public void Parallel_PutGet()
        {
            const int CNT    = 1000000;
            var       tuples = new Tuple <PilePointer, ChargeRow> [CNT];

            using (var pile = new DefaultPile())
            {
                pile.Start();

                var ipile = pile as IPile;

                Parallel.For(0, CNT, i => {
                    var ch    = ChargeRow.MakeFake(new GDID(0, (ulong)i));
                    var pp    = ipile.Put(ch);
                    tuples[i] = new Tuple <PilePointer, ChargeRow>(pp, ch);
                });

                Aver.AreEqual(CNT, ipile.ObjectCount);

                Parallel.ForEach(tuples, t => {
                    Aver.AreObjectsEqual(t.Item2, ipile.Get(t.Item1));
                });
            }
        }
Beispiel #11
0
        public void Canvas_DrawEllipse()
        {
            using (var canvas = TestImg1.CreateCanvas())
            {
                var clr = Color.FromArgb(12, 34, 120);
                var pen = canvas.CreatePen(clr, 1, PenDashStyle.Solid);
                canvas.DrawEllipse(pen, 1, 1, 3, 2);

                for (int h = 0; h < TestImg2.Height; h++)
                {
                    for (int w = 0; w < TestImg2.Width; w++)
                    {
                        if ((h == 1 && (w == 2 || w == 3)) || (h == 2 && (w == 1 || w == 4)) || (h == 3 && (w == 2 || w == 3)))
                        {
                            Aver.AreObjectsEqual(clr, TestImg1.GetPixel(w, h));
                        }
                        else
                        {
                            Aver.AreObjectsNotEqual(clr, TestImg1.GetPixel(w, h));
                        }
                    }
                }
            }
        }
Beispiel #12
0
        public void Canvas_DrawRectangle()
        {
            using (var canvas = TestImg1.CreateCanvas())
            {
                var clr = Color.FromArgb(12, 34, 120);
                var pen = canvas.CreatePen(clr, 1, PenDashStyle.Solid);
                canvas.DrawRectangle(pen, 1, 1, 5, 3);

                for (int h = 0; h < TestImg2.Height; h++)
                {
                    for (int w = 0; w < TestImg2.Width; w++)
                    {
                        if (w >= 1 && w <= 5 && h >= 1 && h <= 3 && (w == 1 || w == 5 || h == 1 || h == 3))
                        {
                            Aver.AreObjectsEqual(clr, TestImg1.GetPixel(w, h));
                        }
                        else
                        {
                            Aver.AreObjectsNotEqual(clr, TestImg1.GetPixel(w, h));
                        }
                    }
                }
            }
        }
Beispiel #13
0
        public void Canvas_FillRectangle()
        {
            using (var canvas = TestImg1.CreateCanvas())
            {
                var clr = Color.FromArgb(12, 34, 120);
                var br  = canvas.CreateSolidBrush(clr);
                canvas.FillRectangle(br, 1, 1, 2, 3);

                for (int h = 0; h < TestImg2.Height; h++)
                {
                    for (int w = 0; w < TestImg2.Width; w++)
                    {
                        if (w >= 1 && w <= 2 && h >= 1 && h <= 3)
                        {
                            Aver.AreObjectsEqual(clr, TestImg1.GetPixel(w, h));
                        }
                        else
                        {
                            Aver.AreObjectsNotEqual(clr, TestImg1.GetPixel(w, h));
                        }
                    }
                }
            }
        }
        public void GDIDSymbol()
        {
            object obj = new GDIDSymbol(new GDID(3, 4, 5), "ABC");

            Aver.AreObjectsEqual(obj, obj.AsGDIDSymbol());
            Aver.AreObjectsEqual(obj, obj.AsGDIDSymbol(new GDIDSymbol(new GDID(23, 14, 15), "ABC")));


            var link = new ELink(new GDID(4, 12, 8721));


            Aver.AreEqual(link.AsGDIDSymbol, link.Link.AsGDIDSymbol());
            Aver.AreEqual(link.AsGDIDSymbol, "3rewtfef:4:5".AsGDIDSymbol(link.AsGDIDSymbol()));

            try
            {
                "3rewtfef:4:5".AsGDIDSymbol(link.AsGDIDSymbol, handling: ConvertErrorHandling.Throw);
                Aver.Fail("No excepetion");
            }
            catch
            {
                Aver.Pass();
            }
        }
Beispiel #15
0
        private void schemaAssertions(Schema trg, Schema src)
        {
            Aver.AreEqual(trg.FieldCount, src.FieldCount);

            Aver.AreObjectsEqual(trg["BoolField"].Type, typeof(bool));
            Aver.AreObjectsEqual(trg["CharField"].Type, typeof(string));
            Aver.AreObjectsEqual(trg["StringField"].Type, typeof(string));
            Aver.AreObjectsEqual(trg["DateTimeField"].Type, typeof(DateTime));
            Aver.AreObjectsEqual(trg["GDIDField"].Type, typeof(object));
            Aver.AreObjectsEqual(trg["ByteField"].Type, typeof(uint));
            Aver.AreObjectsEqual(trg["UShortField"].Type, typeof(uint));
            Aver.AreObjectsEqual(trg["UInt16Field"].Type, typeof(uint));
            Aver.AreObjectsEqual(trg["UIntField"].Type, typeof(uint));
            Aver.AreObjectsEqual(trg["UInt32Field"].Type, typeof(uint));
            Aver.AreObjectsEqual(trg["SByteField"].Type, typeof(int));
            Aver.AreObjectsEqual(trg["ShortField"].Type, typeof(int));
            Aver.AreObjectsEqual(trg["Int16Field"].Type, typeof(int));
            Aver.AreObjectsEqual(trg["IntField"].Type, typeof(int));
            Aver.AreObjectsEqual(trg["Int32Field"].Type, typeof(int));
            Aver.AreObjectsEqual(trg["ULongField"].Type, typeof(ulong));
            Aver.AreObjectsEqual(trg["UInt64Field"].Type, typeof(ulong));
            Aver.AreObjectsEqual(trg["LongField"].Type, typeof(long));
            Aver.AreObjectsEqual(trg["Int64Field"].Type, typeof(long));
            Aver.AreObjectsEqual(trg["FloatField"].Type, typeof(double));
            Aver.AreObjectsEqual(trg["SingleField"].Type, typeof(double));
            Aver.AreObjectsEqual(trg["DoubleField"].Type, typeof(double));
            Aver.AreObjectsEqual(trg["DecimalField"].Type, typeof(decimal));
            Aver.AreObjectsEqual(trg["NullableField"].Type, typeof(int?));
            Aver.AreObjectsEqual(trg["ArrayInt"].Type, typeof(List <object>));
            Aver.AreObjectsEqual(trg["ListString"].Type, typeof(List <object>));
            Aver.AreObjectsEqual(trg["DictionaryIntStr"].Type, typeof(Dictionary <string, object>));
            Aver.AreObjectsEqual(trg["RowField"].Type, typeof(object));

            Aver.IsTrue(trg["FieldWithAttrs1"].Attrs.SequenceEqual(src["FieldWithAttrs1"].Attrs));
            Aver.IsTrue(trg["FieldWithAttrs2"].Attrs.SequenceEqual(src["FieldWithAttrs2"].Attrs));
        }
        public void T_09_DynamicRow()
        {
            var BYTES = new byte[] { 0x00, 0x79, 0x14 };

            var schema = new Schema("Dynamic Schema",
                                    new Schema.FieldDef("ID", typeof(int), new List <FieldAttribute> {
                new FieldAttribute(required: true, key: true)
            }),
                                    new Schema.FieldDef("Description", typeof(string), new List <FieldAttribute> {
                new FieldAttribute(required: true)
            }),
                                    new Schema.FieldDef("Bytes", typeof(byte[]), new List <FieldAttribute> {
                new FieldAttribute(required: true)
            })
                                    );

            var row = new DynamicDoc(schema);

            row["ID"]          = 123;
            row["Description"] = "T-90 Tank";
            row["Bytes"]       = BYTES;

            var rc = new DataDocConverter();

            var doc = rc.DataDocToBSONDocument(row, "A");

            Console.WriteLine(doc.ToString());

            var row2 = new DynamicDoc(schema);

            rc.BSONDocumentToDataDoc(doc, row2, "A");

            Aver.AreObjectsEqual(123, row2["ID"]);
            Aver.AreObjectsEqual("T-90 Tank", row2["Description"]);
            Aver.IsTrue(BYTES.SequenceEqual((byte[])row2["Bytes"]));
        }
Beispiel #17
0
        private void averTestImage(Image img)
        {
            //[ g, b, r, b, b, r, b, g ]
            //[ g, b, b, b, b, b, b, g ]
            //[ g, b, r, b, b, r, b, g ]
            //[ g, g, b, r, r, b, g, g ]

            var r = Color.FromArgb(255, 0, 0);
            var g = Color.FromArgb(0, 255, 0);
            var b = Color.FromArgb(0, 0, 255);

            Aver.AreEqual(8, img.Width);
            Aver.AreEqual(4, img.Height);

      #warning Why is this not passing?
            //  Aver.AreEqual(119, img.XResolution);
            //  Aver.AreEqual(119, img.YResolution);

            Aver.AreObjectsEqual(ImagePixelFormat.RGBA32, img.PixelFormat);

            Aver.AreObjectsEqual(g, img.GetPixel(0, 0));
            Aver.AreObjectsEqual(b, img.GetPixel(1, 0));
            Aver.AreObjectsEqual(r, img.GetPixel(2, 0));
            Aver.AreObjectsEqual(b, img.GetPixel(3, 0));
            Aver.AreObjectsEqual(g, img.GetPixel(7, 0));
            Aver.AreObjectsEqual(g, img.GetPixel(0, 1));
            Aver.AreObjectsEqual(b, img.GetPixel(2, 1));
            Aver.AreObjectsEqual(b, img.GetPixel(5, 1));
            Aver.AreObjectsEqual(g, img.GetPixel(7, 1));
            Aver.AreObjectsEqual(b, img.GetPixel(1, 2));
            Aver.AreObjectsEqual(b, img.GetPixel(3, 2));
            Aver.AreObjectsEqual(r, img.GetPixel(5, 2));
            Aver.AreObjectsEqual(b, img.GetPixel(2, 3));
            Aver.AreObjectsEqual(r, img.GetPixel(4, 3));
            Aver.AreObjectsEqual(g, img.GetPixel(6, 3));
        }
        public void T_00_Enum_Equals()
        {
            var row1 = new EnumRow
            {
                ETest1  = ETest.One,
                EFlags1 = EFlags.FirstSecond
            };

            var rc = new DataDocConverter();

            var docOriginal = rc.DataDocToBSONDocument(row1, "A");
            var doc         = fullCopy(docOriginal);

            Console.WriteLine(doc.ToString());

            var row2 = new EnumRow();

            rc.BSONDocumentToDataDoc(doc, row2, "A");

            Aver.AreObjectsEqual(row1, row2);

            Aver.IsTrue(ETest.One == row2.ETest1);
            Aver.IsTrue(EFlags.FirstSecond == row2.EFlags1);
        }
Beispiel #19
0
        public void T_02_Update_Parallel()
        {
            const int CNT = 11973;
            var       BIN = new byte[] { 0x00, 0x79, 0x14 };

            using (var client = new MongoClient("My Test"))
            {
                var db = client.DefaultLocalServer["db1"];

                db["t1"].Drop();

                var t1 = db["t1"];

                var rows = new TestRow[CNT];

                var rc = new NFX.Serialization.BSON.RowConverter();

                var sw = new Stopwatch();

                sw.Start();

                Parallel.For(0, CNT, i =>
                {
                    var row = new TestRow()
                    {
                        _id = i,

                        String1  = "Mudaker",
                        String2  = null,
                        Date1    = new DateTime(1980, 07, 12, 10, 13, 27, DateTimeKind.Utc),
                        Date2    = null,
                        Bool1    = true,
                        Bool2    = null,
                        Guid1    = new Guid("{9195F7DB-FE21-4BB2-B006-2496F4E24D14}"),
                        Guid2    = null,
                        Gdid1    = new NFX.DataAccess.Distributed.GDID(0, 12345),
                        Gdid2    = null,
                        Float1   = 127.0123f,
                        Float2   = null,
                        Double1  = 122345.012d,
                        Double2  = null,
                        Decimal1 = 1234567.098M,
                        Decimal2 = null,
                        Amount1  = new Amount("din", 123.11M),
                        Amount2  = null,
                        Bytes1   = BIN,
                        Bytes2   = null,

                        Byte1   = 23,
                        SByte1  = -3,
                        Short1  = -32761,
                        UShort1 = 65535,
                        Int1    = 4324,
                        Uint1   = 42345,
                        Long1   = 993,
                        ULong1  = 8829383762,
                        ETest1  = ETest.Two,
                        EFlags1 = EFlags.First | EFlags.Third,

                        Byte2   = null,
                        SByte2  = null,
                        Short2  = null,
                        UShort2 = null,
                        Int2    = null,
                        Uint2   = null,
                        Long2   = null,
                        ULong2  = null,
                        ETest2  = null,
                        EFlags2 = null
                    };

                    rows[i] = row;

                    var doc = rc.RowToBSONDocument(row, "A");
                    Aver.AreEqual(1, t1.Insert(doc).TotalDocumentsAffected);
                });
                sw.Stop();
                Console.WriteLine("{0:N0} row inserted in {1:N3} sec on {2:N0} ops/sec", CNT, sw.Elapsed.TotalSeconds, CNT / sw.Elapsed.TotalSeconds);

                sw.Restart();
                Parallel.For(0, CNT, i => {
                    var row     = rows[i];
                    row.String1 = "makaka" + i.ToString();
                    row.Int1    = 9789 + (i * 100);

                    var doc = rc.RowToBSONDocument(row, "A");

                    var r = t1.Save(doc);
                    Aver.AreEqual(1, r.TotalDocumentsAffected);
                    Aver.AreEqual(1, r.TotalDocumentsUpdatedAffected);
                    Aver.IsNull(r.WriteErrors);
                });
                sw.Stop();
                Console.WriteLine("{0:N0} row updated in {1:N3} sec on {2:N0} ops/sec", CNT, sw.Elapsed.TotalSeconds, CNT / sw.Elapsed.TotalSeconds);

                sw.Restart();
                var RCNT = CNT * 3;
                Parallel.For(0, RCNT, i => {
                    var j   = i % CNT;
                    var got = db["t1"].FindOne(Query.ID_EQ_Int32(j));
                    Aver.IsNotNull(got);

                    var row1 = new TestRow();
                    rc.BSONDocumentToRow(got, row1, "A");

                    Aver.AreObjectsEqual(rows[j], row1);
                });
                sw.Stop();
                Console.WriteLine("{0:N0} row red in {1:N3} sec on {2:N0} ops/sec", RCNT, sw.Elapsed.TotalSeconds, RCNT / sw.Elapsed.TotalSeconds);
            }
        }
Beispiel #20
0
        public void InsertManyAndLoadCursor()
        {
            const int CNT = 1000;

            for (var i = 0; i < CNT; i++)
            {
                var row = new MyData
                {
                    ID   = i,
                    Data = "i is " + i.ToString()
                };

                m_Store.Insert(row);
            }

            {
                var cursor = m_Store.OpenCursor(new Query("CRUD.LoadAllMyData", typeof(MyData)));
                Aver.IsNotNull(cursor);
                var lst = new List <Doc>();
                foreach (var row in cursor)
                {
                    lst.Add(row);
                }

                Aver.AreEqual(CNT, lst.Count);
                Aver.IsTrue(cursor.Disposed);

                Console.WriteLine(lst[0].ToJSON());
                Console.WriteLine("..............................");
                Console.WriteLine(lst[lst.Count - 1].ToJSON());

                Aver.AreObjectsEqual(0, lst[0]["ID"].AsInt());
                Aver.AreObjectsEqual(CNT - 1, lst[lst.Count - 1]["ID"].AsInt());
            }
            Console.WriteLine("A");
            {
                Cursor cursor;
                var    lst = new List <Doc>();

                using (cursor = m_Store.OpenCursor(new Query("CRUD.LoadAllMyData", typeof(MyData))))
                {
                    Aver.IsNotNull(cursor);
                    foreach (var row in cursor)
                    {
                        lst.Add(row);
                    }

                    try
                    {
                        foreach (var row in cursor)
                        {
                            lst.Add(row);
                        }
                        Aver.Fail("Can not iterate the second time");
                    }
                    catch (Exception error)
                    {
                        Console.WriteLine("Expected and got: " + error.ToMessageWithType());
                    }
                }
                Aver.AreEqual(CNT, lst.Count);
                Aver.IsTrue(cursor.Disposed);
            }
            Console.WriteLine("B");
            {
                Cursor cursor;

                using (cursor = m_Store.OpenCursor(new Query("CRUD.LoadAllMyData", typeof(MyData))))
                {
                    Aver.IsNotNull(cursor);
                    var en = cursor.GetEnumerator();
                    Aver.IsTrue(en.MoveNext());
                    Aver.IsTrue(en.MoveNext());
                    Aver.IsTrue(en.MoveNext());
                    //Notice, We DO NOT iterate to the very end
                    //... not till the end
                }
                Aver.IsTrue(cursor.Disposed);
            }
            Console.WriteLine("C");
        }
Beispiel #21
0
        public void ManyRow_PutReadDeleteRead()
        {
            using (var pile = new DefaultPile())
            {
                pile.SegmentSize = DefaultPile.SEG_SIZE_MIN;
                pile.Start();
                var ipile = pile as IPile;

                var lst = new List <KeyValuePair <PilePointer, CheckoutRow> >();

                int totalPut    = 0;
                int totalDelete = 0;

                var sw = Stopwatch.StartNew();
                while (ipile.SegmentCount < 4)
                {
                    var rowIn = CheckoutRow.MakeFake(new GDID(0, (ulong)lst.Count));
                    var pp    = ipile.Put(rowIn);
                    totalPut++;
                    lst.Add(new KeyValuePair <PilePointer, CheckoutRow>(pp, rowIn));

                    var chance = ExternalRandomGenerator.Instance.NextRandomInteger > 1000000000; //periodically delete
                    if (!chance)
                    {
                        continue;
                    }

                    var idx = ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, lst.Count - 1);
                    var kvp = lst[idx];
                    lst.RemoveAt(idx);
                    Aver.AreObjectsEqual(kvp.Value, ipile.Get(kvp.Key));

                    Aver.IsTrue(ipile.Delete(kvp.Key));
                    totalDelete++;
                }

                var wms = sw.ElapsedMilliseconds;


                Console.WriteLine("Created {0:n0} in {1:n0} ms at {2:n0} ops/sec".Args(totalPut, wms, totalPut / (wms / 1000d)));
                Console.WriteLine("Read and deleted {0:n0} in {1:n0} ms at {2:n0} ops/sec".Args(totalDelete, wms, totalDelete / (wms / 1000d)));
                Console.WriteLine("Left {0:n0}".Args(lst.Count));
                Console.WriteLine("Occupied bytes {0:n0}".Args(pile.AllocatedMemoryBytes));


                sw.Restart();
                foreach (var kvp in lst)
                {
                    Aver.IsNotNull(ipile.Get(kvp.Key));
                }
                var rms = sw.ElapsedMilliseconds;
                Console.WriteLine("Read {0:n0} in {1:n0} ms at {2:n0} ops/sec".Args(lst.Count, rms, lst.Count / (rms / 1000d)));


                Console.WriteLine("Will verify all rows...");
                foreach (var kvp in lst)
                {
                    var rowIn  = kvp.Value;
                    var rowOut = ipile.Get(kvp.Key) as CheckoutRow;
                    Aver.AreObjectsEqual(rowIn, rowOut);
                }
            }
        }
Beispiel #22
0
        public void Parallel_ManyMixed_PutReadDeleteRead(int tcount)
        {
            using (var pile = new DefaultPile())
            {
                pile.SegmentSize = DefaultPile.SEG_SIZE_MIN;
                pile.Start();
                var ipile = pile as IPile;

                var lst = new List <KeyValuePair <PilePointer, CheckoutRow> >();

                int  totalBuff   = 0;
                long totalBuffSz = 0;
                int  totalPut    = 0;
                int  totalDelete = 0;


                var sw = Stopwatch.StartNew();

                var tasks = new List <Task>();

                while (tasks.Count < tcount)
                {
                    var task = Task.Factory.StartNew(() =>
                    {
                        var llst  = new List <KeyValuePair <PilePointer, CheckoutRow> >();
                        var pBuff = PilePointer.Invalid;

                        while (ipile.SegmentCount < 64)
                        {
                            var chance = ExternalRandomGenerator.Instance.NextRandomInteger > 0;
                            if (chance)
                            {
                                var fakeBuf = new byte[ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, 128 * 1024)];
                                Interlocked.Increment(ref totalBuff);
                                Interlocked.Add(ref totalBuffSz, fakeBuf.Length);
                                if (pBuff.Valid && ExternalRandomGenerator.Instance.NextRandomInteger > 0)
                                {
                                    ipile.Delete(pBuff);                                                                    //periodically delete buffers
                                }
                                pBuff = ipile.Put(fakeBuf);
                            }

                            var rowIn = CheckoutRow.MakeFake(new GDID(0, (ulong)llst.Count));
                            var pp    = ipile.Put(rowIn);
                            Interlocked.Increment(ref totalPut);
                            llst.Add(new KeyValuePair <PilePointer, CheckoutRow>(pp, rowIn));

                            chance = ExternalRandomGenerator.Instance.NextRandomInteger > 1000000000; //periodically delete rows
                            if (!chance)
                            {
                                continue;
                            }

                            var idx = ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, llst.Count - 1);
                            var kvp = llst[idx];
                            llst.RemoveAt(idx);
                            Aver.AreObjectsEqual(kvp.Value, ipile.Get(kvp.Key));

                            Aver.IsTrue(ipile.Delete(kvp.Key));
                            Interlocked.Increment(ref totalDelete);
                        }
                        lock (lst)
                            lst.AddRange(llst);
                    });
                    tasks.Add(task);
                }
                Task.WaitAll(tasks.ToArray());

                var wms = sw.ElapsedMilliseconds;

                Console.WriteLine("Buff Created {0:n0} size {1:n0} bytes".Args(totalBuff, totalBuffSz));
                Console.WriteLine("Row Created {0:n0} in {1:n0} ms at {2:n0} ops/sec".Args(totalPut, wms, totalPut / (wms / 1000d)));
                Console.WriteLine("Read and deleted {0:n0} in {1:n0} ms at {2:n0} ops/sec".Args(totalDelete, wms, totalDelete / (wms / 1000d)));
                Console.WriteLine("Left {0:n0}".Args(lst.Count));
                Console.WriteLine("Occupied bytes {0:n0}".Args(pile.AllocatedMemoryBytes));
                Console.WriteLine("Utilized bytes {0:n0}".Args(pile.UtilizedBytes));
                Console.WriteLine("Objects {0:n0}".Args(pile.ObjectCount));


                sw.Restart();
                foreach (var kvp in lst)
                {
                    Aver.IsNotNull(ipile.Get(kvp.Key));
                }
                var rms = sw.ElapsedMilliseconds;
                Console.WriteLine("Read {0:n0} in {1:n0} ms at {2:n0} ops/sec".Args(lst.Count, rms, lst.Count / (rms / 1000d)));


                Console.WriteLine("Will verify all rows...");
                Parallel.ForEach(lst, kvp =>
                {
                    var rowIn  = kvp.Value;
                    var rowOut = ipile.Get(kvp.Key) as CheckoutRow;
                    Aver.AreObjectsEqual(rowIn, rowOut);
                });
            }
        }
Beispiel #23
0
 public void DoubleLiterals()
 {
     Aver.AreObjectsEqual(12.7, new JL(new StringSource(@"12.7")).Tokens.First(t => t.IsPrimary).Value);
     Aver.AreObjectsEqual(4e+8, new JL(new StringSource(@"4e+8")).Tokens.First(t => t.IsPrimary).Value);
 }
        public void Insert_Find_PrimitiveTypesSingleEntry()
        {
            using (var client = new MongoClient(NOPApplication.Instance, "My client"))
            {
                var db = client.DefaultLocalServer["db1"];
                db["t1"].Drop();
                var collection = db["t1"];

                var item = new BSONDocument().Set(new BSONInt32Element("int", int.MaxValue))
                           .Set(new BSONStringElement("string", "min"))
                           .Set(new BSONBooleanElement("bool", true))
                           .Set(new BSONDateTimeElement("datetime", new DateTime(2000, 1, 4, 12, 34, 56, DateTimeKind.Utc)))
                           .Set(new BSONNullElement("null"))
                           .Set(new BSONArrayElement("array",
                                                     new BSONElement[]
                {
                    new BSONInt32Element(int.MaxValue),
                    new BSONInt32Element(int.MinValue)
                }))
                           .Set(new BSONBinaryElement("binary", new BSONBinary(BSONBinaryType.UserDefined, Encoding.UTF8.GetBytes("Hello world"))))
                           .Set(new BSONDocumentElement("document",
                                                        new BSONDocument().Set(new BSONInt64Element("innerlong", long.MinValue))))
                           .Set(new BSONDoubleElement("double", -123.456D))
                           .Set(new BSONInt64Element("long", long.MaxValue))
                           .Set(new BSONJavaScriptElement("js", "function(a){var x = a;return x;}"))
                           .Set(new BSONJavaScriptWithScopeElement("jswithscope",
                                                                   new BSONCodeWithScope("function(a){var x = a;return x+z;}",
                                                                                         new BSONDocument().Set(new BSONInt32Element("z", 12)))))
                           .Set(new BSONMaxKeyElement("maxkey"))
                           .Set(new BSONMinKeyElement("minkey"))
                           .Set(new BSONObjectIDElement("oid", new BSONObjectID(1, 2, 3, 400)))
                           .Set(new BSONRegularExpressionElement("regex",
                                                                 new BSONRegularExpression(@"^[-.\w]+@(?:[a-z\d]{2,}\.)+[a-z]{2,6}$", BSONRegularExpressionOptions.I | BSONRegularExpressionOptions.M)))
                           .Set(new BSONTimestampElement("timestamp", new BSONTimestamp(new DateTime(2000, 1, 4, 12, 34, 56, DateTimeKind.Utc), 12345)));

                Aver.AreEqual(1, collection.Insert(item).TotalDocumentsAffected);

                var all = collection.Find(new Query());

                all.MoveNext();
                Aver.AreEqual(all.Current.Count, 18);
                Aver.AreEqual(((BSONInt32Element)all.Current["int"]).Value, int.MaxValue);
                Aver.AreEqual(((BSONStringElement)all.Current["string"]).Value, "min");
                Aver.AreEqual(((BSONBooleanElement)all.Current["bool"]).Value, true);
                Aver.AreEqual(((BSONDateTimeElement)all.Current["datetime"]).Value, new DateTime(2000, 1, 4, 12, 34, 56, DateTimeKind.Utc));
                Aver.IsTrue(all.Current["null"] is BSONNullElement);
                var array = ((BSONArrayElement)all.Current["array"]).Value;
                Aver.AreEqual(array.Length, 2);
                Aver.AreEqual(((BSONInt32Element)array[0]).Value, int.MaxValue);
                Aver.AreEqual(((BSONInt32Element)array[1]).Value, int.MinValue);
                var binary = ((BSONBinaryElement)all.Current["binary"]).Value;
                Aver.IsTrue(binary.Data.MemBufferEquals(Encoding.UTF8.GetBytes("Hello world")));
                Aver.IsTrue(binary.Type == BSONBinaryType.UserDefined);
                var doc = ((BSONDocumentElement)all.Current["document"]).Value;
                Aver.AreEqual(doc.Count, 1);
                Aver.AreEqual(((BSONInt64Element)doc["innerlong"]).Value, long.MinValue);
                Aver.AreEqual(((BSONDoubleElement)all.Current["double"]).Value, -123.456D);
                Aver.AreEqual(((BSONInt64Element)all.Current["long"]).Value, long.MaxValue);
                Aver.AreEqual(((BSONJavaScriptElement)all.Current["js"]).Value, "function(a){var x = a;return x;}");
                var jsScope = ((BSONJavaScriptWithScopeElement)all.Current["jswithscope"]).Value;
                Aver.AreEqual(jsScope.Code, "function(a){var x = a;return x+z;}");
                Aver.AreEqual(jsScope.Scope.Count, 1);
                Aver.AreEqual(((BSONInt32Element)jsScope.Scope["z"]).Value, 12);
                Aver.IsTrue(all.Current["maxkey"] is BSONMaxKeyElement);
                Aver.IsTrue(all.Current["minkey"] is BSONMinKeyElement);
                var oid = ((BSONObjectIDElement)all.Current["oid"]).Value;
                Aver.IsTrue(oid.Bytes.MemBufferEquals(new BSONObjectID(1, 2, 3, 400).Bytes));
                Aver.AreObjectsEqual(((BSONRegularExpressionElement)all.Current["regex"]).Value,
                                     new BSONRegularExpression(@"^[-.\w]+@(?:[a-z\d]{2,}\.)+[a-z]{2,6}$", BSONRegularExpressionOptions.I | BSONRegularExpressionOptions.M));
                Aver.AreObjectsEqual(((BSONTimestampElement)all.Current["timestamp"]).Value,
                                     new BSONTimestamp(new DateTime(2000, 1, 4, 12, 34, 56, DateTimeKind.Utc), 12345));

                all.MoveNext();
                Aver.AreEqual(true, all.EOF);
            }
        }
Beispiel #25
0
        public void Parallel_PutGetDelete_Random()
        {
            const int PUTTER_CNT = 2, PUTTER_OP_CNT = 2 * 10000;
            const int GETTER_CNT = 6, GETTER_OP_CNT = 2 * 30000;
            const int DELETER_CNT = 2, DELETER_OP_CNT = 2 * 10000;

            var data = new ConcurrentDictionary <PilePointer, string>();

            var getAccessViolations    = new ConcurrentDictionary <int, int>();
            var deleteAccessViolations = new ConcurrentDictionary <int, int>();

            using (var pile = new DefaultPile())
            {
                pile.Start();

                var ipile = pile as IPile;

                // putter tasks
                var putters = new Task[PUTTER_CNT];
                for (int it = 0; it < PUTTER_CNT; it++)
                {
                    var task = new Task(() =>
                    {
                        for (int i = 0; i < PUTTER_OP_CNT; i++)
                        {
                            var str = NFX.Parsing.NaturalTextGenerator.Generate();
                            var pp  = ipile.Put(str);
                            data.TryAdd(pp, str);
                        }
                    });

                    putters[it] = task;
                }

                // getter tasks
                var getters = new Task[GETTER_CNT];
                for (int it = 0; it < GETTER_CNT; it++)
                {
                    var task = new Task(() =>
                    {
                        for (int i = 0; i < GETTER_OP_CNT; i++)
                        {
                            if (data.Count == 0)
                            {
                                System.Threading.Thread.Yield();
                                continue;
                            }
                            var idx = ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, data.Count - 1);
                            var kvp = data.ElementAt(idx);
                            try
                            {
                                var str = ipile.Get(kvp.Key);
                                Aver.AreObjectsEqual(str, kvp.Value);
                            }
                            catch (PileAccessViolationException)
                            {
                                getAccessViolations.AddOrUpdate(System.Threading.Thread.CurrentThread.ManagedThreadId, 1, (mid, val) => val + 1);
                            }
                        }
                    });
                    getters[it] = task;
                }

                // deleter tasks
                var deleters = new Task[DELETER_CNT];
                for (int it = 0; it < DELETER_CNT; it++)
                {
                    var task = new Task(() =>
                    {
                        for (int i = 0; i < DELETER_OP_CNT; i++)
                        {
                            if (data.Count == 0)
                            {
                                System.Threading.Thread.Yield();
                                continue;
                            }
                            var idx = ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, data.Count - 1);
                            var kvp = data.ElementAt(idx);
                            try
                            {
                                ipile.Delete(kvp.Key);
                            }
                            catch (PileAccessViolationException)
                            {
                                deleteAccessViolations.AddOrUpdate(System.Threading.Thread.CurrentThread.ManagedThreadId, 1, (mid, val) => val + 1);
                            }
                        }
                    });
                    deleters[it] = task;
                }


                foreach (var task in putters)
                {
                    task.Start();
                }
                foreach (var task in getters)
                {
                    task.Start();
                }
                foreach (var task in deleters)
                {
                    task.Start();
                }


                Task.WaitAll(putters.Concat(getters).Concat(deleters).ToArray());

                foreach (var kvp in getAccessViolations)
                {
                    Console.WriteLine("Get thread '{0}' {1:n0} times accessed deleted pointer", kvp.Key, kvp.Value);
                }

                foreach (var kvp in deleteAccessViolations)
                {
                    Console.WriteLine("Del thread '{0}' {1:n0} times accessed deleted pointer", kvp.Key, kvp.Value);
                }
            }
        }
Beispiel #26
0
        public void ManyMixed_PutReadDeleteRead()
        {
            using (var pile = new DefaultPile(NOPApplication.Instance))
            {
                pile.SegmentSize = DefaultPile.SEG_SIZE_MIN;
                pile.Start();
                var ipile = pile as IPile;

                var lst = new List <KeyValuePair <PilePointer, CheckoutRow> >();

                int  totalBuff   = 0;
                long totalBuffSz = 0;
                int  totalPut    = 0;
                int  totalDelete = 0;

                var pBuff = PilePointer.Invalid;

                var sw = Stopwatch.StartNew();
                while (ipile.SegmentCount < 16)
                {
                    var chance = Ambient.Random.NextRandomInteger > 0;
                    if (chance)
                    {
                        var fakeBuf = new byte[Ambient.Random.NextScaledRandomInteger(0, 128 * 1024)];
                        totalBuff++;
                        totalBuffSz += fakeBuf.Length;
                        if (pBuff.Valid && Ambient.Random.NextRandomInteger > 0)
                        {
                            ipile.Delete(pBuff);                                            //periodically delete buffers
                        }
                        pBuff = ipile.Put(fakeBuf);
                    }

                    var rowIn = CheckoutRow.MakeFake(new GDID(0, (ulong)lst.Count));
                    var pp    = ipile.Put(rowIn);
                    totalPut++;
                    lst.Add(new KeyValuePair <PilePointer, CheckoutRow>(pp, rowIn));

                    chance = Ambient.Random.NextRandomInteger > 1000000000; //periodically delete rows
                    if (!chance)
                    {
                        continue;
                    }

                    var idx = Ambient.Random.NextScaledRandomInteger(0, lst.Count - 1);
                    var kvp = lst[idx];
                    lst.RemoveAt(idx);
                    Aver.AreObjectsEqual(kvp.Value, ipile.Get(kvp.Key));

                    Aver.IsTrue(ipile.Delete(kvp.Key));
                    totalDelete++;
                }

                var wms = sw.ElapsedMilliseconds;

                Console.WriteLine("Buff Created {0:n0} size {1:n0} bytes".Args(totalBuff, totalBuffSz));
                Console.WriteLine("Row Created {0:n0} in {1:n0} ms at {2:n0} ops/sec".Args(totalPut, wms, totalPut / (wms / 1000d)));
                Console.WriteLine("Read and deleted {0:n0} in {1:n0} ms at {2:n0} ops/sec".Args(totalDelete, wms, totalDelete / (wms / 1000d)));
                Console.WriteLine("Left {0:n0}".Args(lst.Count));
                Console.WriteLine("Occupied bytes {0:n0}".Args(pile.AllocatedMemoryBytes));
                Console.WriteLine("Utilized bytes {0:n0}".Args(pile.UtilizedBytes));
                Console.WriteLine("Objects {0:n0}".Args(pile.ObjectCount));


                sw.Restart();
                foreach (var kvp in lst)
                {
                    Aver.IsNotNull(ipile.Get(kvp.Key));
                }
                var rms = sw.ElapsedMilliseconds;
                Console.WriteLine("Read {0:n0} in {1:n0} ms at {2:n0} ops/sec".Args(lst.Count, rms, lst.Count / (rms / 1000d)));


                Console.WriteLine("Will verify all rows...");
                foreach (var kvp in lst)
                {
                    var rowIn  = kvp.Value;
                    var rowOut = ipile.Get(kvp.Key) as CheckoutRow;
                    Aver.AreObjectsEqual(rowIn, rowOut);
                }
            }
        }
Beispiel #27
0
        public void T_01_Insert()
        {
            var BIN = new byte[] { 0x00, 0x79, 0x14 };

            using (var client = new MongoClient("My Test"))
            {
                var db = client.DefaultLocalServer["db1"];

                db["t1"].Drop();

                var t1 = db["t1"];

                var row = new TestRow()
                {
                    _id = 1,

                    String1  = "Mudaker",
                    String2  = null,
                    Date1    = new DateTime(1980, 07, 12, 10, 13, 27, DateTimeKind.Utc),
                    Date2    = null,
                    Bool1    = true,
                    Bool2    = null,
                    Guid1    = new Guid("{9195F7DB-FE21-4BB2-B006-2496F4E24D14}"),
                    Guid2    = null,
                    Gdid1    = new NFX.DataAccess.Distributed.GDID(0, 12345),
                    Gdid2    = null,
                    Float1   = 127.0123f,
                    Float2   = null,
                    Double1  = 122345.012d,
                    Double2  = null,
                    Decimal1 = 1234567.098M,
                    Decimal2 = null,
                    Amount1  = new Amount("din", 123.11M),
                    Amount2  = null,
                    Bytes1   = BIN,
                    Bytes2   = null,

                    Byte1   = 23,
                    SByte1  = -3,
                    Short1  = -32761,
                    UShort1 = 65535,
                    Int1    = 4324,
                    Uint1   = 42345,
                    Long1   = 993,
                    ULong1  = 8829383762,
                    ETest1  = ETest.Two,
                    EFlags1 = EFlags.First | EFlags.Third,

                    Byte2   = null,
                    SByte2  = null,
                    Short2  = null,
                    UShort2 = null,
                    Int2    = null,
                    Uint2   = null,
                    Long2   = null,
                    ULong2  = null,
                    ETest2  = null,
                    EFlags2 = null
                };

                var rc  = new NFX.Serialization.BSON.RowConverter();
                var doc = rc.RowToBSONDocument(row, "A");
                Aver.AreEqual(1, t1.Insert(doc).TotalDocumentsAffected);

                var got = db["t1"].FindOne(Query.ID_EQ_Int32(1));
                Aver.IsNotNull(got);

                var row1 = new TestRow();
                rc.BSONDocumentToRow(got, row1, "A");

                Aver.AreObjectsEqual(row, row1);
            }
        }
Beispiel #28
0
        public void Record_MapJSToCLRKinds()
        {
            var json =
                @"{
  'fields': 
   [
     {
       'def': {
         'Name': 'LOCAL',
         'Type': 'datetime',
         'Kind': 'datetime-local'
       },
       'val': '2016-03-23 12:23:59'
     },
     {
       'def': {
         'Name': 'TEL',
         'Type': 'string',
         'Kind': 'tel'
       },
       'val': '(111) 222-33-44'
     },
     {
       'def': {
         'Name': 'DFT'
       },
       'val': 'Default kind is Text'
     }
   ]
}";

            var rec    = new Record(json);
            var errors = rec.ServerErrors.ToList();

            Aver.AreEqual(0, errors.Count);

            Aver.AreEqual(3, rec.Schema.FieldCount);

            var fdef = rec.Schema["LOCAL"];

            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("LOCAL", fdef.Name);
            Aver.AreObjectsEqual(typeof(DateTime), fdef.Type);
            var attr = fdef.Attrs.First();

            Aver.IsTrue(DataKind.DateTimeLocal == attr.Kind);
            Aver.AreObjectsEqual("2016-03-23 12:23:59".AsDateTime(), rec["LOCAL"]);

            fdef = rec.Schema["TEL"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("TEL", fdef.Name);
            Aver.AreObjectsEqual(typeof(string), fdef.Type);
            attr = fdef.Attrs.First();
            Aver.IsTrue(DataKind.Telephone == attr.Kind);
            Aver.AreObjectsEqual("(111) 222-33-44", rec["TEL"]);

            fdef = rec.Schema["DFT"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("DFT", fdef.Name);
            Aver.AreObjectsEqual(typeof(string), fdef.Type);
            attr = fdef.Attrs.First();
            Aver.IsTrue(DataKind.Text == attr.Kind);
            Aver.AreObjectsEqual("Default kind is Text", rec["DFT"]);
        }
Beispiel #29
0
        public void Record_MapJSToCLRTypes()
        {
            var json =
                @"{
  'fields': 
   [
     {
       'def': {
         'Name': 'STR',
         'Type': 'string'
       },
       'val': 'ABBA'
     },
     {
       'def': {
         'Name': 'INT',
         'Type': 'int'
       },
       'val': -23
     },
     {
       'def': {
         'Name': 'NUM',
         'Type': 'real'
       },
       'val': -123.456
     },
     {
       'def': {
         'Name': 'BOOL',
         'Type': 'bool'
       },
       'val': true
     },
     {
       'def': {
         'Name': 'DATE',
         'Type': 'datetime'
       },
       'val': '2016-03-23 12:23:59'
     },
     {
       'def': {
         'Name': 'OBJ',
         'Type': 'object'
       },
       'val': { 'n': 'name', 'age': 23 }
     },
     {
       'def': {
         'Name': 'DFT'
       },
       'val': 'Default type is string'
     }
   ]
}";

            var rec    = new Record(json);
            var errors = rec.ServerErrors.ToList();

            Aver.AreEqual(0, errors.Count);

            Aver.AreEqual(7, rec.Schema.FieldCount);

            var fdef = rec.Schema["STR"];

            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("STR", fdef.Name);
            Aver.AreObjectsEqual(typeof(string), fdef.Type);
            Aver.AreObjectsEqual("ABBA", rec["STR"]);

            fdef = rec.Schema["INT"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("INT", fdef.Name);
            Aver.AreObjectsEqual(typeof(long), fdef.Type);
            Aver.AreObjectsEqual((long)-23, rec["INT"]);

            fdef = rec.Schema["NUM"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("NUM", fdef.Name);
            Aver.AreObjectsEqual(typeof(double), fdef.Type);
            Aver.AreObjectsEqual(-123.456, rec["NUM"]);

            fdef = rec.Schema["BOOL"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("BOOL", fdef.Name);
            Aver.AreObjectsEqual(typeof(bool), fdef.Type);
            Aver.AreObjectsEqual(true, rec["BOOL"]);

            fdef = rec.Schema["DATE"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("DATE", fdef.Name);
            Aver.AreObjectsEqual(typeof(DateTime), fdef.Type);
            Aver.AreObjectsEqual("2016-03-23 12:23:59".AsDateTime(), rec["DATE"]);

            fdef = rec.Schema["OBJ"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("OBJ", fdef.Name);
            Aver.AreObjectsEqual(typeof(object), fdef.Type);
            var value = JsonReader.DeserializeDataObject("{ 'n': 'name', 'age': 23 }") as JsonDataMap;

            var got = rec["OBJ"] as JsonDataMap;

            Aver.IsNotNull(got);
            Aver.IsTrue(value.SequenceEqual(got));

            fdef = rec.Schema["DFT"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("DFT", fdef.Name);
            Aver.AreObjectsEqual(typeof(string), fdef.Type);
            Aver.AreObjectsEqual("Default type is string", rec["DFT"]);
        }
Beispiel #30
0
        public void Record_ValidInitJSON()
        {
            var json =
                @"{
  'OK': true,
  'ID': '39a833dd-b48f-46c1-83a6-96603cc962a6',
  'ISOLang': 'eng',
  '__FormMode': 'Edit',
  '__CSRFToken': '1kk_qzXPLyScAa2A5y5GLTo9IlCqjuP',
  '__Roundtrip': '{\'GDID\':\'0:1:5\'}',
  'fields': [
      {
        'def': {
          'Name': 'Mnemonic',
          'Type': 'string',
          'Description': 'Mnemonic',
          'Required': true,
          'MinSize': 1,
          'Size': 25,
          'Placeholder': 'Mnemonic',
          'Stored': false
        },
        'val': 'Dns'
      },
      {
        'def': {
          'Name': 'Vertical_ID',
          'Type': 'string',
          'Description': 'Vertical',
          'Required': false,
          'Visible': false,
          'Size': 15,
          'DefaultValue': 'HAB',
          'Key': true,
          'Case': 'Upper',
          'LookupDict': {
            'HAB': 'HAB.rs Health and Beauty',
            'READRS': 'READ.rs Book Business',
            'SLRS': 'SL.RS General Business'
          }
        },
        'val': 'HAB'
      },
      {
        'def': {
          'Name': 'Table_ID',
          'Type': 'int',
          'Key': true,
          'Description': 'Table',
          'Required': true,
          'Visible': false,
          'MinValue': 1,
          'MaxValue': 123,
          'DefaultValue': 15,
          'Kind': 'Number',
          'Stored': true
        },
        'val': 2
      }
    ]
}";

            var init = JsonReader.DeserializeDataObject(json) as JsonDataMap;
            var rec  = new Record(init);

            Aver.AreEqual(0, rec.ServerErrors.Count());

            Aver.AreEqual(true, rec.OK);
            Aver.AreObjectsEqual("eng", rec.ISOLang);
            Aver.AreEqual(new Guid("39a833dd-b48f-46c1-83a6-96603cc962a6"), rec.ID);
            Aver.AreObjectsEqual("Edit", rec.FormMode);
            Aver.AreObjectsEqual("1kk_qzXPLyScAa2A5y5GLTo9IlCqjuP", rec.CSRFToken);

            var roundtrip = rec.Roundtrip;

            Aver.IsNotNull(roundtrip);
            Aver.AreEqual(roundtrip.Count, 1);
            Aver.AreObjectsEqual("0:1:5", roundtrip["GDID"]);

            Aver.AreEqual(3, rec.Schema.FieldCount);

            var fdef = rec.Schema["Mnemonic"];

            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("Mnemonic", fdef.Name);
            Aver.AreObjectsEqual(typeof(string), fdef.Type);
            Aver.AreEqual(false, fdef.AnyTargetKey);
            Aver.IsNotNull(fdef.Attrs);
            Aver.AreEqual(1, fdef.Attrs.Count());
            var attr = fdef.Attrs.First();

            Aver.AreObjectsEqual("Mnemonic", attr.Description);
            Aver.AreEqual(true, attr.Required);
            Aver.AreEqual(true, attr.Visible);
            Aver.IsNull(attr.Min);
            Aver.IsNull(attr.Max);
            Aver.AreEqual(1, attr.MinLength);
            Aver.AreEqual(25, attr.MaxLength);
            Aver.IsNull(attr.Default);
            Aver.AreEqual(0, attr.ParseValueList().Count);
            Aver.IsTrue(StoreFlag.OnlyLoad == attr.StoreFlag);
            Aver.AreEqual(@"''{Name=Mnemonic Type=string Description=Mnemonic Required=True MinSize=1 Size=25 Placeholder=Mnemonic Stored=False}", attr.MetadataContent);
            Aver.AreObjectsEqual("Dns", rec["Mnemonic"]);

            fdef = rec.Schema["Vertical_ID"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("Vertical_ID", fdef.Name);
            Aver.AreObjectsEqual(typeof(string), fdef.Type);
            Aver.AreEqual(true, fdef.AnyTargetKey);
            Aver.IsNotNull(fdef.Attrs);
            Aver.AreEqual(1, fdef.Attrs.Count());
            attr = fdef.Attrs.First();
            Aver.AreObjectsEqual("Vertical", attr.Description);
            Aver.AreEqual(false, attr.Required);
            Aver.AreEqual(false, attr.Visible);
            Aver.IsNull(attr.Min);
            Aver.IsNull(attr.Max);
            Aver.AreEqual(0, attr.MinLength);
            Aver.AreEqual(15, attr.MaxLength);
            Aver.IsTrue(CharCase.Upper == attr.CharCase);
            Aver.AreObjectsEqual("HAB", attr.Default);

            var map1 = FieldAttribute.ParseValueListString("HAB:HAB.rs Health and Beauty,READRS:READ.rs Book Business,SLRS:SL.RS General Business", true);
            var map2 = attr.ParseValueList(true);

            Aver.IsTrue(map1.SequenceEqual(map2));

            Aver.AreObjectsEqual("''{Name=Vertical_ID Type=string Description=Vertical Required=False Visible=False Size=15 DefaultValue=HAB Key=True Case=Upper LookupDict=\"{\\\"HAB\\\":\\\"HAB.rs Health and Beauty\\\",\\\"READRS\\\":\\\"READ.rs Book Business\\\",\\\"SLRS\\\":\\\"SL.RS General Business\\\"}\"}", attr.MetadataContent);
            Aver.AreObjectsEqual("HAB", rec["Vertical_ID"]);

            fdef = rec.Schema["Table_ID"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("Table_ID", fdef.Name);
            Aver.AreObjectsEqual(typeof(long), fdef.Type);
            Aver.AreEqual(true, fdef.AnyTargetKey);
            Aver.IsNotNull(fdef.Attrs);
            Aver.AreEqual(1, fdef.Attrs.Count());
            attr = fdef.Attrs.First();
            Aver.AreObjectsEqual("Table", attr.Description);
            Aver.AreEqual(true, attr.Required);
            Aver.AreEqual(false, attr.Visible);
            Aver.AreObjectsEqual(1, attr.Min);
            Aver.AreObjectsEqual(123, attr.Max);
            Aver.AreObjectsEqual(15, attr.Default);
            Aver.IsTrue(DataKind.Number == attr.Kind);
            Aver.IsTrue(StoreFlag.LoadAndStore == attr.StoreFlag);
            Aver.AreEqual(0, attr.ParseValueList(true).Count);
            Aver.AreObjectsEqual("''{Name=Table_ID Type=int Key=True Description=Table Required=True Visible=False MinValue=1 MaxValue=123 DefaultValue=15 Kind=Number Stored=True}", attr.MetadataContent);
            Aver.AreObjectsEqual((long)2, rec["Table_ID"]);
        }