예제 #1
0
파일: TestBSON.cs 프로젝트: rayleyva/ejdb
 public void TestFilteredDoc()
 {
     var doc = new BSONDocument();
     doc["c"] = "d";
     doc["aaa"] = 11;
     doc["ndoc"] = BSONDocument.ValueOf(new {
         aaaa = "nv1",
         d = "nv2",
         nnd = BSONDocument.ValueOf(new {
             nnv = true,
             nns = "s"
         })
     });
     doc["ndoc2"] = BSONDocument.ValueOf(new {
         n = "v"
     });
     doc["f"] = "f";
     BSONIterator it = new BSONIterator(doc);
     BSONDocument doc2 = it.ToBSONDocument("c", "ndoc.d", "ndoc.nnd.nns", "f");
     Assert.AreEqual(3, doc2.KeysCount);
     Assert.AreEqual("d", doc2["c"]);
     Assert.AreEqual(2, ((BSONDocument) doc2["ndoc"]).KeysCount);
     Assert.AreEqual("nv2", ((BSONDocument) doc2["ndoc"])["d"]);
     Assert.AreEqual("s", ((BSONDocument) ((BSONDocument) doc2["ndoc"])["nnd"])["nns"]);
     Assert.AreEqual("s", doc2["ndoc.nnd.nns"]);
     Assert.AreEqual("f", "f");
     //Console.WriteLine("doc2=" + doc2);
 }
예제 #2
0
        private void btnCreateIndex_Click(object sender, EventArgs e)
        {
            var db = MongoClient.Instance.DefaultLocalServer["db1"];

            var idx = new BSONDocument(@"
              {
               createIndexes: 't1',
            indexes: [
              {
                key: {name: 1},
                name: 'idxT1_Name',
                unique: false
              },
              {
                key: {age: -11},
                name: 'idxT1_Age',
                unique: false
              }
            ]
              }

            ",false);

            MessageBox.Show( db.RunCommand( idx ).ToString() );
        }
예제 #3
0
 public UpdateEntry(BSONDocument query, BSONDocument update, bool multi, bool upsert)
 {
   Query  = query;
   Update = update;
   Multi  = multi;
   Upsert = upsert;
 }
예제 #4
0
        public void InferSchema()
        {
            var doc = new BSONDocument();
            doc.Set( new BSONStringElement("FullName", "Alex Bobby") );
            doc.Set( new BSONInt32Element("Age", 123) );
            doc.Set( new BSONBooleanElement("IsGood", true) );

            var c = new RowConverter();

            var schema = c.InferSchemaFromBSONDocument(doc);

            Assert.AreEqual(3, schema.FieldCount);

            Assert.AreEqual(0, schema["FullName"].Order);
            Assert.AreEqual(1, schema["Age"].Order);
            Assert.AreEqual(2, schema["IsGood"].Order);

            Assert.AreEqual(typeof(object), schema["FullName"].NonNullableType);
            Assert.AreEqual(typeof(object), schema["Age"].NonNullableType);
            Assert.AreEqual(typeof(object), schema["IsGood"].NonNullableType);

            var row = new DynamicRow(schema);
            c.BSONDocumentToRow(doc, row, null);

            Assert.AreEqual("Alex Bobby", row[0]);
            Assert.AreEqual(123,          row[1]);
            Assert.AreEqual(true,         row[2]);

            Assert.AreEqual("Alex Bobby", row["FullName"]);
            Assert.AreEqual(123,          row["Age"]);
            Assert.AreEqual(true,         row["IsGood"]);
        }
예제 #5
0
파일: TestEJDB.cs 프로젝트: JulianLiu/ejdb
        public void Test3SaveLoad()
        {
            EJDB jb = new EJDB("testdb1", EJDB.DEFAULT_OPEN_MODE | EJDB.JBOTRUNC);
            Assert.IsTrue(jb.IsOpen);
            BSONDocument doc = new BSONDocument().SetNumber("age", 33);
            Assert.IsNull(doc["_id"]);
            bool rv = jb.Save("mycoll", doc);
            Assert.IsTrue(rv);
            Assert.IsNotNull(doc["_id"]);
            Assert.IsInstanceOf(typeof(BSONOid), doc["_id"]);
            rv = jb.Save("mycoll", doc);
            Assert.IsTrue(rv);

            BSONIterator it = jb.Load("mycoll", doc["_id"] as BSONOid);
            Assert.IsNotNull(it);

            BSONDocument doc2 = it.ToBSONDocument();
            Assert.AreEqual(doc.ToDebugDataString(), doc2.ToDebugDataString());
            Assert.IsTrue(doc == doc2);

            Assert.AreEqual(1, jb.CreateQueryFor("mycoll").Count());
            Assert.IsTrue(jb.Remove("mycoll", doc["_id"] as BSONOid));
            Assert.AreEqual(0, jb.CreateQueryFor("mycoll").Count());

            jb.Save("mycoll", doc);
            Assert.AreEqual(1, jb.CreateQueryFor("mycoll").Count());
            Assert.IsTrue(jb.DropCollection("mycoll"));
            Assert.AreEqual(0, jb.CreateQueryFor("mycoll").Count());

            Assert.IsTrue(jb.Sync());
            jb.Dispose();
        }
예제 #6
0
파일: EJDBQuery.cs 프로젝트: JulianLiu/ejdb
 internal EJDBQuery(EJDB jb, BSONDocument qdoc, string defaultcollection = null)
 {
     _qptr = _ejdbcreatequery(jb.DBPtr, qdoc.ToByteArray());
     if (_qptr == IntPtr.Zero) {
         throw new EJDBQueryException(jb);
     }
     _jb = jb;
     _defaultcollection = defaultcollection;
 }
예제 #7
0
 public void WriteBigIntegers(Stream stream)
 {
     stream.Position = 0;
       var root = new BSONDocument();
       root.Set(new BSONInt32Element("intMin", int.MinValue));
       root.Set(new BSONInt32Element("intMax", int.MaxValue));
       root.Set(new BSONInt64Element("longMin", long.MinValue));
       root.Set(new BSONInt64Element("longMax", long.MaxValue));
       root.WriteAsBSON(stream);
 }
예제 #8
0
파일: BSON.cs 프로젝트: vlapchenko/nfx
        public void ReadEmptyDocument()
        {
            var src = Convert.FromBase64String(@"BQAAAAA=");

              using (var stream = new MemoryStream(src))
              {
            var root = new BSONDocument(stream);

            Assert.AreEqual(root.ByteSize, 5);
            Assert.AreEqual(root.Count, 0);
            Assert.AreEqual(stream.Position, 5); // ensure whole document readed
              }
        }
예제 #9
0
        /// <summary>
        /// Finds a document that satisfied query or null
        /// </summary>
        public BSONDocument FindOne(Query query, BSONDocument selector = null)
        {
          EnsureObjectNotDisposed();

          if (query==null)
           throw new MongoDBConnectorException(StringConsts.ARGUMENT_ERROR+"Collection.FindOne(query==null)");

          var connection = Server.AcquireConnection();
          try
          {
            var reqId = Database.NextRequestID;
            return connection.FindOne(reqId, this, query, selector);
          }
          finally
          {
            connection.Release();
          }
        }
예제 #10
0
        public void CollectionDrop()
        {
            using(var client= new MongoClient("My Test"))
              {
            var collection = client.DefaultLocalServer["db1"]["ToDrop"];
            var doc1 = new BSONDocument();

            doc1.Set( new BSONStringElement("_id", "id1"))
            .Set( new BSONStringElement("val", "My value"))
            .Set( new BSONInt32Element("age", 125));

            var r = collection.Insert(doc1);
            Assert.AreEqual(1, r.TotalDocumentsAffected);

            collection.Drop();
            Assert.IsTrue( collection.Disposed );
              }
        }
예제 #11
0
        public static Int32 Write_UPDATE(Stream stream,
                                         Int32 requestID,
                                         Collection collection,
                                         UpdateEntry[] updates)
        {
            var body = new BSONDocument();

            body.Set(new BSONStringElement("update", collection.Name));

            var writeConcern = getWriteConcern(collection);

            if (writeConcern != null)
            {
                body.Set(new BSONDocumentElement("writeConcern", writeConcern));
            }

            var arr = updates.Select(one =>
            {
                var doc = new BSONDocument();
                doc.Set(new BSONDocumentElement("q", one.Query));
                doc.Set(new BSONDocumentElement("u", one.Update));

                if (one.Multi)
                {
                    doc.Set(new BSONBooleanElement("multi", true));
                }

                if (one.Upsert)
                {
                    doc.Set(new BSONBooleanElement("upsert", true));
                }

                return(new BSONDocumentElement(doc));
            }
                                     ).ToArray();

            body.Set(new BSONArrayElement("updates", arr));

            return(Write_QUERY(stream, requestID, collection.Database, null, QueryFlags.None, 0, -1, body, null));
        }
예제 #12
0
파일: Protocol.cs 프로젝트: sergey-msu/azos
        public static Int32 Write_INSERT(Stream stream,
                                         Int32 requestID,
                                         Collection collection,
                                         BSONDocument[] data)
        {
            var body = new BSONDocument();

            body.Set(new BSONStringElement("insert", collection.Name));

            var writeConcern = getWriteConcern(collection);

            if (writeConcern != null)
            {
                body.Set(new BSONDocumentElement("writeConcern", writeConcern));
            }

            var arr = data.Select(elm => new BSONDocumentElement(elm)).ToArray();

            body.Set(new BSONArrayElement("documents", arr));

            return(Write_QUERY(stream, requestID, collection.Database, null, QueryFlags.None, 0, -1, body, null));
        }
예제 #13
0
        private BSONDocument toBSONUpdate(ProcessFrame frame, bool sysOnly)
        {
            var setDoc     = new BSONDocument();
            var descriptor = frame.Descriptor;

            setDoc.Set(new BSONInt32Element(FLD_PROCESS_STATUS, (int)descriptor.Status));
            setDoc.Set(elmStr(FLD_PROCESS_STATUS_DESCRIPTION, descriptor.StatusDescription));
            setDoc.Set(new BSONDateTimeElement(FLD_PROCESS_STATUS_TIMESTAMP, descriptor.StatusTimestamp));
            setDoc.Set(elmStr(FLD_PROCESS_STATUS_ABOUT, descriptor.StatusAbout));

            if (!sysOnly)
            {
                setDoc.Set(new BSONInt32Element(FLD_PROCESS_SERIALIZER, frame.Serializer));
                setDoc.Set(elmBin(FLD_PROCESS_CONTENT, frame.Content));
            }

            var result = new BSONDocument();

            result.Set(new BSONDocumentElement("$set", setDoc));

            return(result);
        }
예제 #14
0
        internal Cursor Find(int requestID, Collection collection, Query query, BSONDocument selector, int skipCount, int fetchBy)
        {
            EnsureObjectNotDisposed();

            if (fetchBy <= 0)
            {
                fetchBy = Cursor.DEFAULT_FETCH_BY;
            }

            if (selector == null)
            {
                selector = query.ProjectionSelector;
            }

            m_BufferStream.Position = 0;
            var total = Protocol.Write_QUERY(m_BufferStream,
                                             requestID,
                                             collection.Database,
                                             collection,
                                             Protocol.QueryFlags.None,
                                             skipCount,
                                             fetchBy,
                                             query,
                                             selector);

            writeSocket(total);

            var got   = readSocket();
            var reply = Protocol.Read_REPLY(got);

            Protocol.CheckReplyDataForErrors(reply);

            var result = new Cursor(reply.CursorID, collection, query, selector, reply.Documents)
            {
                FetchBy = fetchBy
            };

            return(result);
        }
예제 #15
0
파일: BSON.cs 프로젝트: itadapter/nfx
        public void ReadBigIntegers()
        {
            var src = Convert.FromBase64String(@"PwAAABBpbnRNaW4AAAAAgBBpbnRNYXgA////fxJsb25nTWluAAAAAAAAAACAEmxvbmdNYXgA/////////38A");

              using (var stream = new MemoryStream(src))
              {
            var root = new BSONDocument(stream);

            Assert.AreEqual(root.ByteSize, 63);
            Assert.AreEqual(root.Count, 4);

            var element1 = root["intMin"] as BSONInt32Element;
            Assert.IsNotNull(element1);
            Assert.AreEqual(element1.ElementType, BSONElementType.Int32);
            Assert.AreEqual(element1.Name, "intMin");
            Assert.AreEqual(element1.Value, int.MinValue);

            var element2 = root["intMax"] as BSONInt32Element;
            Assert.IsNotNull(element2);
            Assert.AreEqual(element2.ElementType, BSONElementType.Int32);
            Assert.AreEqual(element2.Name, "intMax");
            Assert.AreEqual(element2.Value, int.MaxValue);

            var element3 = root["longMin"] as BSONInt64Element;
            Assert.IsNotNull(element3);
            Assert.AreEqual(element3.ElementType, BSONElementType.Int64);
            Assert.AreEqual(element3.Name, "longMin");
            Assert.AreEqual(element3.Value, long.MinValue);

            var element4 = root["longMax"] as BSONInt64Element;
            Assert.IsNotNull(element4);
            Assert.AreEqual(element4.ElementType, BSONElementType.Int64);
            Assert.AreEqual(element4.Name, "longMax");
            Assert.AreEqual(element4.Value, long.MaxValue);

            Assert.AreEqual(stream.Position, 63); // ensure whole document readed
              }
        }
예제 #16
0
        private BSONDocument toBSON(TodoQueue queue, TodoFrame todo)
        {
            var result = new BSONDocument();
            var t      = todo.GetType();

            result.Set(RowConverter.GDID_CLRtoBSON(Query._ID, todo.ID));

            result.Set(new BSONStringElement(FLD_TODO_TYPE, todo.Type.ToString()));
            result.Set(new BSONDateTimeElement(FLD_TODO_CREATETIMESTAMP, todo.CreateTimestampUTC));

            result.Set(elmStr(FLD_TODO_SHARDINGKEY, todo.ShardingKey));
            result.Set(elmStr(FLD_TODO_PARALLELKEY, todo.ParallelKey));
            result.Set(new BSONInt32Element(FLD_TODO_PRIORITY, todo.Priority));
            result.Set(new BSONDateTimeElement(FLD_TODO_STARTDATE, todo.StartDate));
            result.Set(elmStr(FLD_TODO_CORRELATIONKEY, todo.CorrelationKey));
            result.Set(new BSONInt32Element(FLD_TODO_STATE, todo.State));
            result.Set(new BSONInt32Element(FLD_TODO_TRIES, todo.Tries));

            result.Set(new BSONInt32Element(FLD_TODO_SERIALIZER, todo.Serializer));
            result.Set(elmBin(FLD_TODO_CONTENT, todo.Content));

            return(result);
        }
예제 #17
0
        private BSONArrayElement getRndOrderLines(out double total)
        {
            var linesCnt = ExternalRandomGenerator.Instance.NextScaledRandomInteger(2, 7);
            var arr      = new BSONDocumentElement[linesCnt];

            total = 0;
            for (var i = 0; i < linesCnt; i++)
            {
                var k = i + 1;
                var e = new BSONDocument();
                e.Set(new BSONInt32Element("lid", k));
                e.Set(new BSONStringElement("desc", "odr-ln-" + k));
                e.Set(new BSONStringElement("name", "product-" + k));

                var amt = ExternalRandomGenerator.Instance.NextScaledRandomDouble(35, 749);
                total += amt;
                e.Set(new BSONDoubleElement("amnt", amt));

                arr[i] = new BSONDocumentElement(e);
            }

            return(new BSONArrayElement("lines", arr));
        }
예제 #18
0
        internal BSONDocument RunCommand(int requestID, Database database, BSONDocument command)
        {
            EnsureObjectNotDisposed();

            m_BufferStream.Position = 0;
            var total = Protocol.Write_RUN_COMMAND(m_BufferStream,
                                                   requestID,
                                                   database,
                                                   command);

            writeSocket(total);

            var got   = readSocket();
            var reply = Protocol.Read_REPLY(got);

            Protocol.CheckReplyDataForErrors(reply);

            if (Protocol.IsOKReplyDoc(reply))
            {
                return(reply.Documents[0]);
            }
            throw new MongoDBConnectorProtocolException(StringConsts.PROTO_RUN_COMMAND_REPLY_ERROR + command.ToString());
        }
예제 #19
0
        public void TestAnonTypes()
        {
            BSONDocument doc = BSONDocument.ValueOf(new { a = "b", c = 1 });

            //15-00-00-00
            //02-61-00
            //02-00-00-00
            //62-00
            //10-63-00-01-00-00-00-00
            Assert.AreEqual("15-00-00-00-02-61-00-02-00-00-00-62-00-10-63-00-01-00-00-00-00",
                            doc.ToDebugDataString());
            doc["d"] = new{ e = new BSONRegexp("r1", "o2") };         //subdocument
            //26-00-00-00-02-61-00-02-00-00-00-62-00-10-63-00-01-00-00-00-
            //03
            //64-00
            //0E-00-00-00
            //0B
            //65-00
            //72-31-00-6F-32-00-00-00
            Assert.AreEqual("26-00-00-00-02-61-00-02-00-00-00-62-00-10-63-00-01-00-00-00-" +
                            "03-64-00-0E-00-00-00-0B-65-00-72-31-00-6F-32-00-00-00",
                            doc.ToDebugDataString());
        }
예제 #20
0
        public void SerializeToBSON(BSONSerializer serializer, BSONDocument doc, IBSONSerializable parent, ref object context)
        {
            serializer.AddTypeIDField(doc, parent, this, context);

            doc.Set(new BSONStringElement("tname", TypeName))
            .Set(new BSONStringElement("msg", Message))
            .Set(new BSONInt32Element("code", Code))
            .Set(new BSONStringElement("app", ApplicationName))
            .Set(new BSONStringElement("src", Source))
            .Set(new BSONStringElement("trace", StackTrace));

            if (WrappedData != null)
            {
                doc.Set(new BSONStringElement("wdata", WrappedData));
            }

            if (m_InnerException == null)
            {
                return;
            }

            doc.Set(new BSONDocumentElement("inner", serializer.Serialize(m_InnerException, parent: this)));
        }
예제 #21
0
파일: Protocol.cs 프로젝트: sergey-msu/azos
        public static Int32 Write_QUERY(Stream stream,
                                        Int32 requestID,
                                        Database db,
                                        Collection collection,     //may be null for $CMD
                                        QueryFlags flags,
                                        Int32 numberToSkip,
                                        Int32 numberToReturn,
                                        BSONDocument query,
                                        BSONDocument selector    //may be null
                                        )
        {
            stream.Position = STD_HDR_LEN;              //skip the header

            BinUtils.WriteInt32(stream, (Int32)flags);

            //if collection==null then query the $CMD collection
            var fullNameBuffer = collection != null ? collection.m_FullNameCStringBuffer : db.m_CMD_NameCStringBuffer;

            stream.Write(fullNameBuffer, 0, fullNameBuffer.Length);


            BinUtils.WriteInt32(stream, numberToSkip);
            BinUtils.WriteInt32(stream, numberToReturn);

            query.WriteAsBSON(stream);

            if (selector != null)
            {
                selector.WriteAsBSON(stream);
            }

            var total = (Int32)stream.Position;

            stream.Position = 0;
            writeStandardHeader(stream, total, requestID, 0, OP_QUERY);
            return(total);
        }
예제 #22
0
        public void Test3SaveLoad()
        {
            EJDB jb = new EJDB("testdb1", EJDB.DEFAULT_OPEN_MODE | EJDB.JBOTRUNC);

            Assert.IsTrue(jb.IsOpen);
            BSONDocument doc = new BSONDocument().SetNumber("age", 33);

            Assert.IsNull(doc["_id"]);
            bool rv = jb.Save("mycoll", doc);

            Assert.IsTrue(rv);
            Assert.IsNotNull(doc["_id"]);
            Assert.IsInstanceOf(typeof(BSONOid), doc["_id"]);
            rv = jb.Save("mycoll", doc);
            Assert.IsTrue(rv);

            BSONIterator it = jb.Load("mycoll", doc["_id"] as BSONOid);

            Assert.IsNotNull(it);

            BSONDocument doc2 = it.ToBSONDocument();

            Assert.AreEqual(doc.ToDebugDataString(), doc2.ToDebugDataString());
            Assert.IsTrue(doc == doc2);

            Assert.AreEqual(1, jb.CreateQueryFor("mycoll").Count());
            Assert.IsTrue(jb.Remove("mycoll", doc["_id"] as BSONOid));
            Assert.AreEqual(0, jb.CreateQueryFor("mycoll").Count());

            jb.Save("mycoll", doc);
            Assert.AreEqual(1, jb.CreateQueryFor("mycoll").Count());
            Assert.IsTrue(jb.DropCollection("mycoll"));
            Assert.AreEqual(0, jb.CreateQueryFor("mycoll").Count());

            Assert.IsTrue(jb.Sync());
            jb.Dispose();
        }
예제 #23
0
파일: Protocol.cs 프로젝트: sergey-msu/azos
        public static Int32 Write_COUNT(Stream stream,
                                        Int32 requestID,
                                        Collection collection,
                                        Query query,
                                        Int32 limit,
                                        Int32 skip,
                                        object hint)
        {
            var body = new BSONDocument();

            body.Set(new BSONStringElement("count", collection.Name));

            if (query != null)
            {
                body.Set(new BSONDocumentElement("query", query));
            }
            if (limit > 0)
            {
                body.Set(new BSONInt32Element("limit", limit));
            }
            if (skip > 0)
            {
                body.Set(new BSONInt32Element("skip", limit));
            }

            if (hint is string)
            {
                body.Set(new BSONStringElement("hint", (string)hint));
            }
            else
            if (hint is BSONDocument)
            {
                body.Set(new BSONDocumentElement("hint", (BSONDocument)hint));
            }

            return(Write_QUERY(stream, requestID, collection.Database, null, QueryFlags.None, 0, -1, body, null));
        }
예제 #24
0
파일: SetUser.cs 프로젝트: erxdkh/azos
        protected override object ExecuteBody()
        {
            var crud = Context.Access((tx) => {
                var cusr = tx.Db[BsonDataModel.GetCollectionName(this.Realm, BsonDataModel.COLLECTION_USER)];
                var user = new BSONDocument();
                user.Set(new BSONInt64Element(BsonDataModel._ID, Id));
                user.Set(new BSONInt32Element(BsonDataModel.FLD_STATUS, (int)Status.Value));
                user.Set(new BSONDateTimeElement(BsonDataModel.FLD_CREATEUTC, Context.App.TimeSource.UTCNow));
                user.Set(new BSONDateTimeElement(BsonDataModel.FLD_STARTUTC, StartUtc.Value));
                user.Set(new BSONDateTimeElement(BsonDataModel.FLD_ENDUTC, EndUtc.Value));

                user.Set(new BSONStringElement(BsonDataModel.FLD_ROLE, Role.Default(string.Empty)));

                user.Set(new BSONStringElement(BsonDataModel.FLD_NAME, Name));
                user.Set(new BSONStringElement(BsonDataModel.FLD_DESCRIPTION, Description));
                user.Set(new BSONStringElement(BsonDataModel.FLD_NOTE, Note));

                var cr = cusr.Save(user);
                Aver.IsNull(cr.WriteErrors, cr.WriteErrors?.FirstOrDefault().Message);
                return(cr);
            });

            return(crud);
        }
예제 #25
0
        private BSONDocument toBSONUpdate(TodoQueue queue, TodoFrame todo, bool sysOnly)
        {
            var setDoc = new BSONDocument();

            setDoc.Set(elmStr(FLD_TODO_SHARDINGKEY, todo.ShardingKey));
            setDoc.Set(elmStr(FLD_TODO_PARALLELKEY, todo.ParallelKey));
            setDoc.Set(new BSONInt32Element(FLD_TODO_PRIORITY, todo.Priority));
            setDoc.Set(new BSONDateTimeElement(FLD_TODO_STARTDATE, todo.StartDate));
            setDoc.Set(elmStr(FLD_TODO_CORRELATIONKEY, todo.CorrelationKey));
            setDoc.Set(new BSONInt32Element(FLD_TODO_STATE, todo.State));
            setDoc.Set(new BSONInt32Element(FLD_TODO_TRIES, todo.Tries));

            if (!sysOnly)
            {
                setDoc.Set(new BSONInt32Element(FLD_TODO_SERIALIZER, todo.Serializer));
                setDoc.Set(elmBin(FLD_TODO_CONTENT, todo.Content));
            }

            var result = new BSONDocument();

            result.Set(new BSONDocumentElement("$set", setDoc));

            return(result);
        }
예제 #26
0
        public void TestIterateRE()
        {
            var doc = new BSONDocument();

            doc["a"] = new BSONRegexp("b", "c");
            doc["d"] = 1;
            doc["e"] = BSONDocument.ValueOf(new { f = new BSONRegexp("g", "") });
            doc["h"] = 2;
            //28-00-00-00
            //0B-61-00-62-00-63-00
            //10-64-00-01-00-00-00
            //03-65-00-0B-00-00-00
            //0B-66-00-67-00-00-00
            //10-68-00-02-00-00-00-00
            var cs = "";

            foreach (var bt in new BSONIterator(doc))
            {
                cs += bt.ToString();
            }
            Assert.AreEqual("REGEXINTOBJECTINT", cs);
            cs = "";
            foreach (var bv in new BSONIterator(doc).Values())
            {
                if (bv.Key == "a")
                {
                    cs += ((BSONRegexp)bv.Value).Re;
                    cs += ((BSONRegexp)bv.Value).Opts;
                }
                else
                {
                    cs += bv.Value;
                }
            }
            Assert.AreEqual("bc1[BSONDocument: [BSONValue: BSONType=REGEX, Key=f, Value=[BSONRegexp: re=g, opts=]]]2", cs);
        }
예제 #27
0
 public override void SerializeToBSON(BSONSerializer serializer, BSONDocument doc, IBSONSerializable parent, ref object context)
 {
     base.SerializeToBSON(serializer, doc, parent, ref context);
     doc.Add(BSON_FLD_VALUE, m_Value);
 }
예제 #28
0
 public override void DeserializeFromBSON(BSONSerializer serializer, BSONDocument doc, ref object context)
 {
     base.DeserializeFromBSON(serializer, doc, ref context);
     m_Value = DataDocConverter.Amount_BSONtoCLR((BSONDocumentElement)doc[BSON_FLD_VALUE]);
 }
예제 #29
0
 public override void SerializeToBSON(BSONSerializer serializer, BSONDocument doc, IBSONSerializable parent, ref object context)
 {
     base.SerializeToBSON(serializer, doc, parent, ref context);
     doc.Set(DataDocConverter.Amount_CLRtoBSON(BSON_FLD_VALUE, m_Value));
 }
예제 #30
0
파일: BSON.cs 프로젝트: itadapter/nfx
        public void ReadSingleString()
        {
            var src = Convert.FromBase64String(@"IQAAAAJncmVldGluZ3MADQAAAEhlbGxvIFdvcmxkIQAA");

              using (var stream = new MemoryStream(src))
              {
            var root = new BSONDocument(stream);

            Assert.AreEqual(root.ByteSize, 33);
            Assert.AreEqual(root.Count, 1);

            var element = root["greetings"] as BSONStringElement;
            Assert.IsNotNull(element);
            Assert.AreEqual(element.ElementType, BSONElementType.String);
            Assert.AreEqual(element.Name, "greetings");
            Assert.AreEqual(element.Value, "Hello World!");
            Assert.AreEqual(stream.Position, 33); // ensure whole document readed
              }
        }
예제 #31
0
        public override object Visit(BinaryExpression binary)
        {
            binary.NonNull(nameof(binary));

            if (!binary.Operator.NonBlank(nameof(binary.Operator)).IsOneOf(Translator.BinaryOperators))
            {
                throw new ASTException(StringConsts.AST_UNSUPPORTED_BINARY_OPERATOR_ERROR.Args(binary.Operator));
            }

            var op = MapBinaryOperator(binary.Operator);

            var left = binary.LeftOperand
                       .NonNull(nameof(binary.LeftOperand))
                       .Accept(this);

            var isNull = (binary.RightOperand == null || binary.RightOperand is ValueExpression ve && ve.Value == null);

            if (left is string identifier) //{identifier: {$lt: value} }
            {
                if (isNull)
                {
                    return(new BSONDocumentElement(identifier, new BSONDocument().Set(new BSONNullElement(op))));
                }

                var value = binary.RightOperand.Accept(this);

                var right = new BSONDocument();
                if (value is IEnumerable vie)
                {
                    //todo: need to handle array
                    //   var arr = vie.Cast<object>().Select( e => new BSONElement(e));
                    //   right.Set(new BSONArrayElement(op, arr));
                }
                else
                {
                    try
                    {
                        right.Add(op, value, false, true);
                    }
                    catch
                    {
                        throwSyntaxErrorNear(binary, "unsupported RightOperand value `{0}`".Args(value == null ? "<null>" : value.GetType().Name));
                    }
                }
                return(new BSONDocumentElement(identifier, right));
            }

            if (left is BSONElement complex)
            {
                BSONElement right = null;
                if (isNull)
                {
                    throwSyntaxErrorNear(binary, "unexpected null in compound statement");
                }
                else
                {
                    right = binary.RightOperand.Accept(this) as BSONElement;
                    if (right == null)
                    {
                        throwSyntaxErrorNear(binary, "unsupported RightOperand value");
                    }
                }

                return(new BSONArrayElement(op, new[] { complex, right }));
            }

            return(throwSyntaxErrorNear(binary, "unsupported construct"));
        }
예제 #32
0
        public void TestSerializeEmpty()
        {
            BSONDocument doc = new BSONDocument();

            Assert.AreEqual("05-00-00-00-00", doc.ToDebugDataString());
        }
예제 #33
0
 public void SerializeToBSON(BSONSerializer serializer, BSONDocument doc, IBSONSerializable parent, ref object context)
 {
     serializer.AddTypeIDField(doc, parent, this, context);
     doc.Set(new BSONDocumentElement("wrp", serializer.Serialize(m_Wrapped, parent: this)));
 }
예제 #34
0
파일: EJDB.cs 프로젝트: kotanjan220/ejdb
 bool Save(IntPtr cptr, BSONDocument doc, bool merge)
 {
     bool rv;
     BSONValue bv = doc.GetBSONValue("_id");
     byte[] bsdata = doc.ToByteArray();
     byte[] oiddata = new byte[12];
     //static extern bool _ejdbsavebson([In] IntPtr coll, [In] byte[] bsdata, [Out] byte[] oid, bool merge);
     rv = _ejdbsavebson(cptr, bsdata, oiddata, merge);
     if (rv && bv == null) {
         doc.SetOID("_id", new BSONOid(oiddata));
     }
     if (_throwonfail && !rv) {
         throw new EJDBException(this);
     }
     return  rv;
 }
예제 #35
0
 public static BSONDocumentElement Amount_CLRtoBSON(string name, Amount amount)
 {
   var curEl = new BSONStringElement("c", amount.CurrencyISO);
   var valEl = Decimal_CLRtoBSON("v", amount.Value);
   var doc = new BSONDocument();
   doc.Set(curEl).Set(valEl);
  
   return name != null ? new BSONDocumentElement(name, doc) : new BSONDocumentElement(doc);
 }
예제 #36
0
파일: TestEJDB.cs 프로젝트: JulianLiu/ejdb
        public void Test4Q1()
        {
            EJDB jb = new EJDB("testdb1", EJDB.DEFAULT_OPEN_MODE | EJDB.JBOTRUNC);
            Assert.IsTrue(jb.IsOpen);
            BSONDocument doc = new BSONDocument().SetNumber("age", 33);
            Assert.IsNull(doc["_id"]);
            bool rv = jb.Save("mycoll", doc);
            Assert.IsTrue(rv);
            Assert.IsNotNull(doc["_id"]);
            EJDBQuery q = jb.CreateQuery(BSONDocument.ValueOf(new{age = 33}), "mycoll");
            Assert.IsNotNull(q);
            using (EJDBQCursor cursor = q.Find()) {
                Assert.IsNotNull(cursor);
                Assert.AreEqual(1, cursor.Length);
                int c = 0;
                foreach (BSONIterator oit in cursor) {
                    c++;
                    Assert.IsNotNull(oit);
                    BSONDocument rdoc = oit.ToBSONDocument();
                    Assert.IsTrue(rdoc.HasKey("_id"));
                    Assert.AreEqual(33, rdoc["age"]);
                }
                Assert.AreEqual(1, c);
            }
            using (EJDBQCursor cursor = q.Find(null, EJDBQuery.EXPLAIN_FLAG)) {
                Assert.IsNotNull(cursor);
                Assert.AreEqual(1, cursor.Length);
                Assert.IsTrue(cursor.Log.IndexOf("MAX: 4294967295") != -1);
                Assert.IsTrue(cursor.Log.IndexOf("SKIP: 0") != -1);
                Assert.IsTrue(cursor.Log.IndexOf("RS SIZE: 1") != -1);
            }
            q.Max(10);
            using (EJDBQCursor cursor = q.Find(null, EJDBQuery.EXPLAIN_FLAG)) {
                Assert.IsTrue(cursor.Log.IndexOf("MAX: 10") != -1);
            }

            q.Dispose();
            jb.Dispose();
        }
예제 #37
0
파일: BSON.cs 프로젝트: itadapter/nfx
        public void ReadStringArray()
        {
            var src = Convert.FromBase64String(@"OQAAAARmcnVpdHMALAAAAAIwAAYAAABhcHBsZQACMQAHAAAAb3JhbmdlAAIyAAUAAABwbHVtAAAA");

              using (var stream = new MemoryStream(src))
              {
            var root = new BSONDocument(stream);

            Assert.AreEqual(root.ByteSize, 57);
            Assert.AreEqual(root.Count, 1);

            var element = root["fruits"] as BSONArrayElement;
            Assert.IsNotNull(element);
            Assert.AreEqual(element.Name, "fruits");
            Assert.AreEqual(element.ElementType, BSONElementType.Array);
            Assert.IsNotNull(element.Value);
            Assert.AreEqual(element.Value.Length, 3);

            var item1 = element.Value[0] as BSONStringElement;
            Assert.IsNotNull(item1);
            Assert.IsTrue(item1.IsArrayElement);
            Assert.AreEqual(item1.ElementType, BSONElementType.String);
            Assert.AreEqual(item1.Value, "apple");

            var item2 = element.Value[1] as BSONStringElement;
            Assert.IsNotNull(item2);
            Assert.IsTrue(item2.IsArrayElement);
            Assert.AreEqual(item2.ElementType, BSONElementType.String);
            Assert.AreEqual(item2.Value, "orange");

            var item3 = element.Value[2] as BSONStringElement;
            Assert.IsNotNull(item3);
            Assert.AreEqual(item3.ElementType, BSONElementType.String);
            Assert.IsTrue(item3.IsArrayElement);
            Assert.AreEqual(item3.Value, "plum");

            Assert.AreEqual(stream.Position, 57); // ensure whole document readed
              }
        }
예제 #38
0
파일: BSON.cs 프로젝트: itadapter/nfx
        public void ReadStringAndInt32Pair()
        {
            var src = Convert.FromBase64String(@"IgAAAAJuYW1lAAgAAABHYWdhcmluABBiaXJ0aACOBwAAAA==");

              using (var stream = new MemoryStream(src))
              {
            var root = new BSONDocument(stream);

            Assert.AreEqual(root.ByteSize, 34);
            Assert.AreEqual(root.Count, 2);

            var element1 = root["name"] as BSONStringElement;
            Assert.IsNotNull(element1);
            Assert.AreEqual(element1.ElementType, BSONElementType.String);
            Assert.AreEqual(element1.Name, "name");
            Assert.AreEqual(element1.Value, "Gagarin");

            var element2 = root["birth"] as BSONInt32Element;
            Assert.IsNotNull(element2);
            Assert.AreEqual(element2.ElementType, BSONElementType.Int32);
            Assert.AreEqual(element2.Name, "birth");
            Assert.AreEqual(element2.Value, 1934);

            Assert.AreEqual(stream.Position, 34); // ensure whole document readed
              }
        }
예제 #39
0
파일: BSON.cs 프로젝트: itadapter/nfx
        public void ReadSingleTimestamp()
        {
            var src = Convert.FromBase64String(@"FAAAABFzdGFtcAB7AAAAACRTUQA=");

              using (var stream = new MemoryStream(src))
              {
            var root = new BSONDocument(stream);
            var now = new DateTime(635000000000000000, DateTimeKind.Utc);
            var increment = 123;

            Assert.AreEqual(root.ByteSize, 20);
            Assert.AreEqual(root.Count, 1);

            var element = root["stamp"] as BSONTimestampElement;
            Assert.IsNotNull(element);
            Assert.AreEqual(element.Name, "stamp");
            Assert.AreEqual(element.ElementType, BSONElementType.TimeStamp);
            Assert.AreEqual(element.Value.EpochSeconds, now.ToSecondsSinceUnixEpochStart());
            Assert.AreEqual(element.Value.Increment, increment);

            Assert.AreEqual(stream.Position, 20); // ensure whole document readed
              }
        }
예제 #40
0
 public override void DeserializeFromBSON(BSONSerializer serializer, BSONDocument doc, ref object context)
 {
     m_Value = doc.TryGetObjectValueOf(BSON_FLD_VALUE).AsLong();
     base.DeserializeFromBSON(serializer, doc, ref context);
 }
예제 #41
0
        public void Insert_Find_PrimitiveTypesSingleEntry()
        {
            using (var client = new MongoClient("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)));

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

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

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

                all.MoveNext();
                Assert.AreEqual(true, all.EOF);
            }
        }
예제 #42
0
    /// <summary>
    /// Converts BSON document into Row by filling the supplied row instance making necessary type transforms to
    ///  suit Row.Schema field definitions per target name. If the passed row supports IAmorphousData, then
    /// the fields either not found in row, or the fields that could not be type-converted to CLR type will be 
    /// stowed in amorphous data dictionary
    /// </summary>
    public virtual void BSONDocumentToRow(BSONDocument doc, Row row, string targetName, bool useAmorphousData = true, Func<BSONDocument, BSONElement, bool> filter = null)
    {                
      if (doc==null || row==null) throw new BSONException(StringConsts.ARGUMENT_ERROR+"BSONDocumentToRow(doc|row=null)");
         
      var amrow = row as IAmorphousData;

      foreach(var elm in doc)
      {
        if (filter!=null)
          if (!filter(doc, elm)) continue;
           
        // 2015.03.01 Introduced caching
        var fld = MapBSONFieldNameToSchemaFieldDef(row.Schema, targetName, elm.Name);


        if (fld==null)
        {
            if (amrow!=null && useAmorphousData && amrow.AmorphousDataEnabled)
              SetAmorphousFieldAsCLR(amrow, elm, targetName, filter); 
            continue;
        }

        var wasSet = TrySetFieldAsCLR(row, fld, elm, targetName, filter);
        if (!wasSet)//again dump it in amorphous
        {
          if (amrow!=null && useAmorphousData && amrow.AmorphousDataEnabled)
              SetAmorphousFieldAsCLR(amrow, elm, targetName, filter);
        }
      }


      if (amrow!=null && useAmorphousData && amrow.AmorphousDataEnabled)
      {
          amrow.AfterLoad(targetName);
      }
    }
예제 #43
0
        public void TestIterate2()
        {
            var doc = new BSONDocument();

            doc["a"] = "av";
            doc["b"] = BSONDocument.ValueOf(new{ cc = 1 });
            doc["d"] = new BSONOid("51b9f3af98195c4600000000");
            Assert.AreEqual(3, doc.KeysCount);
            //Console.WriteLine(doc.KeysCount);
            //Console.WriteLine(doc.ToDebugDataString());
            //2E-00-00-00					    +4
            //02-61-00-03-00-00-00-61-76-00		+10 (14)
            //03-62-00							+3  (17) "d" =
            //0D-00-00-00						+4  (21) doc len = 13
            //10-63-63-00-01-00-00-00 -00		+9  (30)
            //07-64-00							+3  (33)
            //51-B9-F3-AF-98-19-5C-46-00-00-00-00	 +12 (45)
            //00									+1 (46)
            Assert.AreEqual("2E-00-00-00-" +
                            "02-61-00-03-00-00-00-61-76-00-" +
                            "03-62-00-" +
                            "0D-00-00-00-" +
                            "10-63-63-00-01-00-00-00-00-" +
                            "07-64-00-" +
                            "51-B9-F3-AF-98-19-5C-46-00-00-00-00-" +
                            "00", doc.ToDebugDataString());
            BSONIterator it = new BSONIterator(doc);
            int          c  = 0;

            foreach (var bt in it)
            {
                if (c == 0)
                {
                    Assert.IsTrue(bt == BSONType.STRING);
                }
                if (c == 1)
                {
                    Assert.IsTrue(bt == BSONType.OBJECT);
                }
                if (c == 2)
                {
                    Assert.IsTrue(bt == BSONType.OID);
                }
                ++c;
            }
            bool thrown = false;

            Assert.IsTrue(it.Disposed);
            try {
                it.Next();
            } catch (ObjectDisposedException) {
                thrown = true;
            }
            Assert.IsTrue(thrown);

            c  = 0;
            it = new BSONIterator(doc);
            foreach (var bv in it.Values())
            {
                if (c == 0)
                {
                    Assert.AreEqual("a", bv.Key);
                    Assert.AreEqual("av", bv.Value);
                }
                if (c == 1)
                {
                    Assert.AreEqual("b", bv.Key);
                    BSONDocument sdoc = bv.Value as BSONDocument;
                    Assert.IsNotNull(sdoc);
                    foreach (var bv2 in new BSONIterator(sdoc).Values())
                    {
                        Assert.AreEqual("cc", bv2.Key);
                        Assert.AreEqual(1, bv2.Value);
                        Assert.AreEqual(BSONType.INT, bv2.BSONType);
                    }
                }
                if (c == 2)
                {
                    Assert.AreEqual(BSONType.OID, bv.BSONType);
                    Assert.IsInstanceOf(typeof(BSONOid), bv.Value);
                    var oid = bv.Value as BSONOid;
                    Assert.AreEqual("51b9f3af98195c4600000000", oid.ToString());
                }
                c++;
            }
        }
예제 #44
0
      /// <summary>
      /// Converts row to BSON document suitable for storage in MONGO.DB.
      /// Pass target name (name of particular store/epoch/implementation) to get targeted field metadata.
      /// Note: the supplied row MAY NOT CONTAIN REFERENCE CYCLES - either direct or transitive
      /// </summary>
      public virtual BSONDocumentElement RowToBSONDocumentElement(Row row, string targetName, bool useAmorphousData = true, string name= null)
      {
        if (row==null) return null;

        var amrow = row as IAmorphousData;
        if (amrow!=null && useAmorphousData && amrow.AmorphousDataEnabled)
        {
            amrow.BeforeSave(targetName);
        }

        var result = new BSONDocument();
        foreach(var field in row.Schema)
        {
            var attr = field[targetName];
            if (attr!=null && attr.StoreFlag!=StoreFlag.OnlyStore && attr.StoreFlag!=StoreFlag.LoadAndStore) continue;
            var el = GetFieldAsBSON(row, field, targetName);
            result.Set( el ); 
        }

        if (amrow!=null && useAmorphousData && amrow.AmorphousDataEnabled)
          foreach(var kvp in amrow.AmorphousData)
          {
            result.Set( GetAmorphousFieldAsBSON(kvp, targetName) );
          }

        return name != null ? new BSONDocumentElement(name, result) : new BSONDocumentElement(result);
      } 
예제 #45
0
 public override void SerializeToBSON(BSONSerializer serializer, BSONDocument doc, IBSONSerializable parent, ref object context)
 {
     base.SerializeToBSON(serializer, doc, parent, ref context);
     doc.Add(BSON_FLD_EXCEPTION_TYPE, m_ExceptionType);
 }
예제 #46
0
 public DeleteEntry(BSONDocument query, DeleteLimit limit)
 {
     Query = query;
     Limit = limit;
 }
예제 #47
0
파일: BSON.cs 프로젝트: itadapter/nfx
        public void Templatization_ComplexObjectNoTemplate()
        {
            var qry0 = new BSONDocument(
            "{" +
              "item1: 23," +
              "item2: [1, 'こん好արüвіт', 123.456], " +
              "item3: { item31: false, item32: [true, true, false], item33: {} }," +
              "item4: {" +
            "item41: [1, 2, 3]," +
            "item42: false," +
            "item43: -123.4567," +
            "item44: 'こんこんвапаъü'," +
            "item45: { item451: [2], item452: true, item453: {} }" +
              "} "+
            "}", true);

              Assert.AreEqual(qry0.Count, 4);

              Assert.AreEqual(((BSONInt32Element)qry0["item1"]).Value, 23);

              var item2 = ((BSONArrayElement)qry0["item2"]).Value;
              Assert.AreEqual(item2.Length, 3);
              Assert.AreEqual(((BSONInt32Element)item2[0]).Value, 1);
              Assert.AreEqual(((BSONStringElement)item2[1]).Value, "こん好արüвіт");
              Assert.AreEqual(((BSONDoubleElement)item2[2]).Value, 123.456D);

              var item3 = ((BSONDocumentElement)qry0["item3"]).Value;
              Assert.AreEqual(item3.Count, 3);
              Assert.AreEqual(((BSONBooleanElement)item3["item31"]).Value, false);
              var arr = ((BSONArrayElement)item3["item32"]).Value;
              Assert.AreEqual(arr.Length, 3);
              Assert.AreEqual(((BSONBooleanElement)arr[0]).Value, true);
              Assert.AreEqual(((BSONBooleanElement)arr[1]).Value, true);
              Assert.AreEqual(((BSONBooleanElement)arr[2]).Value, false);
              var item33 = ((BSONDocumentElement)item3["item33"]).Value;
              Assert.AreEqual(item33.Count, 0);

              var item4 = ((BSONDocumentElement)qry0["item4"]).Value;
              Assert.AreEqual(item4.Count, 5);
              var item41 = ((BSONArrayElement)item4["item41"]).Value;
              Assert.AreEqual(item41.Length, 3);
              Assert.AreEqual(((BSONInt32Element)item41[0]).Value, 1);
              Assert.AreEqual(((BSONInt32Element)item41[1]).Value, 2);
              Assert.AreEqual(((BSONInt32Element)item41[2]).Value, 3);
              Assert.AreEqual(((BSONBooleanElement)item4["item42"]).Value, false);
              Assert.AreEqual(((BSONDoubleElement)item4["item43"]).Value, -123.4567D);
              Assert.AreEqual(((BSONStringElement)item4["item44"]).Value, "こんこんвапаъü");

              var item45 = ((BSONDocumentElement)item4["item45"]).Value;
              Assert.AreEqual(item45.Count, 3);
              var item451 = ((BSONArrayElement)item45["item451"]).Value;
              Assert.AreEqual(item451.Length, 1);
              Assert.AreEqual(((BSONInt32Element)item451[0]).Value, 2);
              Assert.AreEqual(((BSONBooleanElement)item45["item452"]).Value, true);

              var item453 =  ((BSONDocumentElement)item45["item453"]).Value;
              Assert.AreEqual(item453.Count, 0);
        }
예제 #48
0
파일: BSON.cs 프로젝트: itadapter/nfx
        public void ReadSingleRegularExpression()
        {
            var src = Convert.FromBase64String(@"NwAAAAtlbWFpbABeWy0uXHddK0AoPzpbYS16XGRdezIsfVwuKStbYS16XXsyLDZ9JABpbXUAAA==");

              using (var stream = new MemoryStream(src))
              {
            var root = new BSONDocument(stream);
            var pattern = @"^[-.\w]+@(?:[a-z\d]{2,}\.)+[a-z]{2,6}$";
            var options = BSONRegularExpressionOptions.I | BSONRegularExpressionOptions.M |BSONRegularExpressionOptions.U;

            Assert.AreEqual(root.ByteSize, 55);
            Assert.AreEqual(root.Count, 1);

            var element = root["email"] as BSONRegularExpressionElement;
            Assert.IsNotNull(element);
            Assert.AreEqual(element.Name, "email");
            Assert.AreEqual(element.ElementType, BSONElementType.RegularExpression);
            Assert.AreEqual(element.Value.Pattern, pattern);
            Assert.AreEqual(element.Value.Options, options);

            Assert.AreEqual(stream.Position, 55); // ensure whole document readed
              }
        }
예제 #49
0
                  private BSONDocument docFromMessage(Message msg)
                  {
                    var doc = new BSONDocument();

                    var rc = new RowConverter();

                    doc.Set(new BSONStringElement("Guid", msg.Guid.ToString("N")));
                    doc.Set(new BSONStringElement("RelatedTo", msg.RelatedTo.ToString("N")));
                    doc.Set(new BSONStringElement("Type", msg.Type.ToString()));
                    doc.Set(new BSONInt32Element("Source", msg.Source));
                    doc.Set(new BSONInt64Element("TimeStamp", msg.TimeStamp.Ticks));
                    doc.Set(new BSONStringElement("Host", msg.Host));
                    doc.Set(new BSONStringElement("From", msg.From));
                    doc.Set(new BSONStringElement("Topic", msg.Topic));
                    doc.Set(new BSONStringElement("Text", msg.Text));
                    doc.Set(new BSONStringElement("Parameters", msg.Parameters));
                    doc.Set(new BSONStringElement("Exception", msg.Exception.ToMessageWithType()));
                    doc.Set(new BSONInt32Element("ThreadID", msg.ThreadID));

                    return doc;
                  }
예제 #50
0
파일: BSON.cs 프로젝트: itadapter/nfx
        public void Templatization_QueryComplexObject()
        {
            var qry0 = new BSONDocument(
            "{" +
              "'$$item1': 23," +
              "item2: [1, '$$item21', 123.456], " +
              "'$$item3': { item31: '$$false', item32: '$$array', item33: {} }," +
              "'$$item4': {" +
            "'$$item41': [1, 2, 3]," +
            "'$$item42': false," +
            "item43: '$$double'," +
            "item44: 'こんこんвапаъü'," +
            "item45: { item451: '$$array2', item452: true, item453: {} }" +
              "} "+
            "}", true,
            new TemplateArg("item1", BSONElementType.String, "item1"),
            new TemplateArg("item21", BSONElementType.String, "こん好արüвіт"),
            new TemplateArg("item3", BSONElementType.String, "item3"),
            new TemplateArg("false", BSONElementType.Boolean, false),
            new TemplateArg("array", BSONElementType.Array,
              new BSONElement[]
              {
            new BSONBooleanElement(true),
            new BSONBooleanElement(true),
            new BSONBooleanElement(false)
              }),
            new TemplateArg("item4", BSONElementType.String, "item4"),
            new TemplateArg("item41", BSONElementType.String, "item41"),
            new TemplateArg("item42", BSONElementType.String, "item42"),
            new TemplateArg("double", BSONElementType.Double, -123.4567),
            new TemplateArg("array2", BSONElementType.Array,
              new BSONElement[]
              {
            new BSONInt64Element(2),
              })
            );

              Assert.AreEqual(qry0.Count, 4);

              Assert.AreEqual(((BSONInt32Element)qry0["item1"]).Value, 23);

              var item2 = ((BSONArrayElement)qry0["item2"]).Value;
              Assert.AreEqual(item2.Length, 3);
              Assert.AreEqual(((BSONInt32Element)item2[0]).Value, 1);
              Assert.AreEqual(((BSONStringElement)item2[1]).Value, "こん好արüвіт");
              Assert.AreEqual(((BSONDoubleElement)item2[2]).Value, 123.456D);

              var item3 = ((BSONDocumentElement)qry0["item3"]).Value;
              Assert.AreEqual(item3.Count, 3);
              Assert.AreEqual(((BSONBooleanElement)item3["item31"]).Value, false);
              var arr = ((BSONArrayElement)item3["item32"]).Value;
              Assert.AreEqual(arr.Length, 3);
              Assert.AreEqual(((BSONBooleanElement)arr[0]).Value, true);
              Assert.AreEqual(((BSONBooleanElement)arr[1]).Value, true);
              Assert.AreEqual(((BSONBooleanElement)arr[2]).Value, false);
              var item33 =  ((BSONDocumentElement)item3["item33"]).Value;
              Assert.AreEqual(item33.Count, 0);

              var item4 = ((BSONDocumentElement)qry0["item4"]).Value;
              Assert.AreEqual(item4.Count, 5);
              var item41 = ((BSONArrayElement)item4["item41"]).Value;
              Assert.AreEqual(item41.Length, 3);
              Assert.AreEqual(((BSONInt32Element)item41[0]).Value, 1);
              Assert.AreEqual(((BSONInt32Element)item41[1]).Value, 2);
              Assert.AreEqual(((BSONInt32Element)item41[2]).Value, 3);
              Assert.AreEqual(((BSONBooleanElement)item4["item42"]).Value, false);
              Assert.AreEqual(((BSONDoubleElement)item4["item43"]).Value, -123.4567D);
              Assert.AreEqual(((BSONStringElement)item4["item44"]).Value, "こんこんвапаъü");

              var item45 = ((BSONDocumentElement)item4["item45"]).Value;
              Assert.AreEqual(item45.Count, 3);
              var item451 = ((BSONArrayElement)item45["item451"]).Value;
              Assert.AreEqual(item451.Length, 1);
              Assert.AreEqual(((BSONInt64Element)item451[0]).Value, 2);
              Assert.AreEqual(((BSONBooleanElement)item45["item452"]).Value, true);

              var item453 =  ((BSONDocumentElement)item45["item453"]).Value;
              Assert.AreEqual(item453.Count, 0);
        }
예제 #51
0
        /// <summary>
        /// Converts BSON document to JSON data map by directly mapping 
        ///  BSON types into corresponding CLR types. The sub-documents get mapped into JSONDataObjects,
        ///   and BSON arrays get mapped into CLR object[]
        /// </summary>
        public virtual JSONDataMap BSONDocumentToJSONMap(BSONDocument doc, Func<BSONDocument, BSONElement, bool> filter = null)
        {
          if (doc==null) return null;

          var result = new JSONDataMap(true);
          foreach(var elm in doc)
          {
             if (filter!=null)
              if (!filter(doc, elm)) continue;

             var clrValue = DirectConvertBSONValue(elm, filter);
             result[elm.Name] = clrValue;
          }

          return result;
        }
예제 #52
0
        internal BSONDocument FindOne(int requestID, Collection collection, Query query, BSONDocument selector)
        {
            EnsureObjectNotDisposed();

            m_BufferStream.Position = 0;
            var total = Protocol.Write_QUERY(m_BufferStream,
                                             requestID,
                                             collection.Database,
                                             collection,
                                             Protocol.QueryFlags.None,
                                             0,
                                             -1, // If the number is negative, then the database will return that number and close the cursor.
                                                 // No futher results for that query can be fetched. If numberToReturn is 1 the server will treat it as -1
                                                 //(closing the cursor automatically).
                                             query,
                                             selector);

            writeSocket(total);

            var got   = readSocket();
            var reply = Protocol.Read_REPLY(got);

            Protocol.CheckReplyDataForErrors(reply);

            var result = reply.Documents != null && reply.Documents.Length > 0 ? reply.Documents[0] : null;

            return(result);
        }
예제 #53
0
          /// <summary>
          /// override to perform the conversion. the data is never null here, and ref cycles a ruled out
          /// </summary>
          protected virtual BSONElement DoConvertCLRtoBSON(string name, object data, Type dataType, string targetName)
          {
            //1 Primitive/direct types
            Func<string, object, BSONElement> func;
            if (m_CLRtoBSON.TryGetValue(dataType, out func)) return func(name, data);

            //2 Enums
            if (dataType.IsEnum)
              return name != null ? new BSONStringElement(name, data.ToString()) : new BSONStringElement(data.ToString());

            //3 Complex Types
            if (data is Row)
              return this.RowToBSONDocumentElement((Row)data, targetName, name: name);

            //IDictionary //must be before IEnumerable
            if (data is IDictionary)
            {
              var dict = (IDictionary)data;
              var result = new BSONDocument();
              foreach( var key in dict.Keys)
              {
                var fldName = key.ToString();
                var el = ConvertCLRtoBSON(fldName, dict[key], targetName);
                result.Set(el);
              }
              return name != null ? new BSONDocumentElement(name, result) : new BSONDocumentElement(result);
            }

            //IEnumerable
            if (data is IEnumerable)
            {
              var list = (IEnumerable)data;
              List<BSONElement> elements = new List<BSONElement>();
              foreach( var obj in list)
              {
                var el = ConvertCLRtoBSON(null, obj, targetName);
                elements.Add(el);
              }
              var result = name != null ? new BSONArrayElement(name, elements.ToArray()) : new BSONArrayElement(elements.ToArray());
              return result;
            }


            throw new BSONException(StringConsts.CLR_BSON_CONVERSION_TYPE_NOT_SUPPORTED_ERROR.Args(dataType.FullName));
          }
예제 #54
0
파일: Protocol.cs 프로젝트: sergey-msu/azos
 public static Int32 Write_RUN_COMMAND(Stream stream, Int32 requestID, Database db, BSONDocument command)
 {
     return(Write_QUERY(stream, requestID, db, null, QueryFlags.None, 0, -1, command, null));
 }
예제 #55
0
파일: BSONTestForm.cs 프로젝트: zhabis/nfx
        /// <summary>
        /// {} (empty document)
        /// </summary>
        public void WriteEmptyDocument(Stream stream)
        {
            var root = new BSONDocument();

            root.WriteAsBSON(stream);
        }
예제 #56
0
파일: BSON.cs 프로젝트: itadapter/nfx
        public void Templatization_ArrayOfUnicodeStringNames()
        {
            var qry0 = new BSONDocument("{ '$$eng': 'eng', '$$rus': 'rus', '$$chi': 'chi', '$$jap': 'jap', '$$gre': 'gre', '$$alb': 'alb', '$$arm': 'arm', '$$vie': 'vie', '$$por': 'por', '$$ukr': 'ukr', '$$ger': 'ger' }", true,
                           new TemplateArg("eng", BSONElementType.String, "hello"),
                           new TemplateArg("rus", BSONElementType.String, "привет"),
                           new TemplateArg("chi", BSONElementType.String, "你好"),
                           new TemplateArg("jap", BSONElementType.String, "こんにちは"),
                           new TemplateArg("gre", BSONElementType.String, "γεια σας"),
                           new TemplateArg("alb", BSONElementType.String, "përshëndetje"),
                           new TemplateArg("arm", BSONElementType.String, "բարեւ Ձեզ"),
                           new TemplateArg("vie", BSONElementType.String, "xin chào"),
                           new TemplateArg("por", BSONElementType.String, "Olá"),
                           new TemplateArg("ukr", BSONElementType.String, "Привіт"),
                           new TemplateArg("ger", BSONElementType.String, "wünsche"));

              Assert.AreEqual(qry0.Count, 11);
              Assert.IsNotNull(qry0["hello"]);
              Assert.IsInstanceOf<BSONStringElement>(qry0["hello"]);
              Assert.AreEqual(((BSONStringElement)qry0["hello"]).Value, "eng");

              Assert.IsNotNull(qry0["привет"]);
              Assert.IsInstanceOf<BSONStringElement>(qry0["привет"]);
              Assert.AreEqual(((BSONStringElement)qry0["привет"]).Value, "rus");

              Assert.IsNotNull(qry0["你好"]);
              Assert.IsInstanceOf<BSONStringElement>(qry0["你好"]);
              Assert.AreEqual(((BSONStringElement)qry0["你好"]).Value, "chi");

              Assert.IsNotNull(qry0["こんにちは"]);
              Assert.IsInstanceOf<BSONStringElement>(qry0["こんにちは"]);
              Assert.AreEqual(((BSONStringElement)qry0["こんにちは"]).Value, "jap");

              Assert.IsNotNull(qry0["γεια σας"]);
              Assert.IsInstanceOf<BSONStringElement>(qry0["γεια σας"]);
              Assert.AreEqual(((BSONStringElement)qry0["γεια σας"]).Value, "gre");

              Assert.IsNotNull(qry0["përshëndetje"]);
              Assert.IsInstanceOf<BSONStringElement>(qry0["përshëndetje"]);
              Assert.AreEqual(((BSONStringElement)qry0["përshëndetje"]).Value, "alb");

              Assert.IsNotNull(qry0["բարեւ Ձեզ"]);
              Assert.IsInstanceOf<BSONStringElement>(qry0["բարեւ Ձեզ"]);
              Assert.AreEqual(((BSONStringElement)qry0["բարեւ Ձեզ"]).Value, "arm");

              Assert.IsNotNull(qry0["xin chào"]);
              Assert.IsInstanceOf<BSONStringElement>(qry0["xin chào"]);
              Assert.AreEqual(((BSONStringElement)qry0["xin chào"]).Value, "vie");

              Assert.IsNotNull(qry0["Olá"]);
              Assert.IsInstanceOf<BSONStringElement>(qry0["Olá"]);
              Assert.AreEqual(((BSONStringElement)qry0["Olá"]).Value, "por");

              Assert.IsNotNull(qry0["Привіт"]);
              Assert.IsInstanceOf<BSONStringElement>(qry0["Привіт"]);
              Assert.AreEqual(((BSONStringElement)qry0["Привіт"]).Value, "ukr");

              Assert.IsNotNull(qry0["wünsche"]);
              Assert.IsInstanceOf<BSONStringElement>(qry0["wünsche"]);
              Assert.AreEqual(((BSONStringElement)qry0["wünsche"]).Value, "ger");
        }
예제 #57
0
파일: BSON.cs 프로젝트: itadapter/nfx
        public void ReadStringInt32DoubleMixedArray()
        {
            var src = Convert.FromBase64String(@"MAAAAARzdHVmZgAkAAAAAjAABgAAAGFwcGxlABAxAAMAAAABMgAfhetRuB4BQAAA");

              using (var stream = new MemoryStream(src))
              {
            var root = new BSONDocument(stream);

            Assert.AreEqual(root.ByteSize, 48);
            Assert.AreEqual(root.Count, 1);

            var element = root["stuff"] as BSONArrayElement;
            Assert.IsNotNull(element);
            Assert.AreEqual(element.Name, "stuff");
            Assert.AreEqual(element.ElementType, BSONElementType.Array);
            Assert.IsNotNull(element.Value);
            Assert.AreEqual(element.Value.Length, 3);

            var item1 = element.Value[0] as BSONStringElement;
            Assert.IsNotNull(item1);
            Assert.IsTrue(item1.IsArrayElement);
            Assert.AreEqual(item1.ElementType, BSONElementType.String);
            Assert.AreEqual(item1.Value, "apple");

            var item2 = element.Value[1] as BSONInt32Element;
            Assert.IsNotNull(item2);
            Assert.IsTrue(item2.IsArrayElement);
            Assert.AreEqual(item2.ElementType, BSONElementType.Int32);
            Assert.AreEqual(item2.Value, 3);

            var item3 = element.Value[2] as BSONDoubleElement;
            Assert.IsNotNull(item3);
            Assert.IsTrue(item3.IsArrayElement);
            Assert.AreEqual(item3.ElementType, BSONElementType.Double);
            Assert.AreEqual(item3.Value, 2.14D);

            Assert.AreEqual(stream.Position, 48); // ensure whole document readed
              }
        }
예제 #58
0
파일: BSON.cs 프로젝트: itadapter/nfx
        public void Templatization_ArrayOfUnicodeStringValues()
        {
            var qry0 = new BSONDocument("{ '$$unicode': [ '$$eng', '$$rus', '$$chi', '$$jap', '$$gre', '$$alb', '$$arm', '$$vie', '$$por', '$$ukr', '$$ger' ] }", true,
                           new TemplateArg("unicode", BSONElementType.String, "strings"),
                           new TemplateArg("eng", BSONElementType.String, "hello"),
                           new TemplateArg("rus", BSONElementType.String, "привет"),
                           new TemplateArg("chi", BSONElementType.String, "你好"),
                           new TemplateArg("jap", BSONElementType.String, "こんにちは"),
                           new TemplateArg("gre", BSONElementType.String, "γεια σας"),
                           new TemplateArg("alb", BSONElementType.String, "përshëndetje"),
                           new TemplateArg("arm", BSONElementType.String, "բարեւ Ձեզ"),
                           new TemplateArg("vie", BSONElementType.String, "xin chào"),
                           new TemplateArg("por", BSONElementType.String, "Olá"),
                           new TemplateArg("ukr", BSONElementType.String, "Привіт"),
                           new TemplateArg("ger", BSONElementType.String, "wünsche"));

              Assert.AreEqual(qry0.Count, 1);
              Assert.IsNotNull(qry0["strings"]);
              Assert.IsInstanceOf<BSONArrayElement>(qry0["strings"]);
              var array = ((BSONArrayElement)qry0["strings"]).Value;
              Assert.IsNotNull(array);
              Assert.AreEqual(array.Length, 11);
              Assert.AreEqual(((BSONStringElement)array[0]).Value, "hello");
              Assert.AreEqual(((BSONStringElement)array[1]).Value, "привет");
              Assert.AreEqual(((BSONStringElement)array[2]).Value, "你好");
              Assert.AreEqual(((BSONStringElement)array[3]).Value, "こんにちは");
              Assert.AreEqual(((BSONStringElement)array[4]).Value, "γεια σας");
              Assert.AreEqual(((BSONStringElement)array[5]).Value, "përshëndetje");
              Assert.AreEqual(((BSONStringElement)array[6]).Value, "բարեւ Ձեզ");
              Assert.AreEqual(((BSONStringElement)array[7]).Value, "xin chào");
              Assert.AreEqual(((BSONStringElement)array[8]).Value, "Olá");
              Assert.AreEqual(((BSONStringElement)array[9]).Value, "Привіт");
              Assert.AreEqual(((BSONStringElement)array[10]).Value, "wünsche");
        }
예제 #59
0
        protected override List <TrendingEntity> DoGetTreding(TrendingQuery query)
        {
            var result = new List <TrendingEntity>();

            IEnumerable <string> collections;

            if (query.EntityType.IsNotNullOrWhiteSpace())
            {
                if (!TrendingHost.HasEntity(query.EntityType))
                {
                    return(result);
                }
                collections = new[] { query.EntityType };
            }
            else
            {
                collections = TrendingHost.AllEntities;
            }

            foreach (var collection in collections)
            {
                var sort        = new BSONDocument().Set(new BSONInt32Element(DBConsts.FIELD_VALUE, -1));
                var qry         = new Query();
                var betweenDate = new BSONDocument();
                betweenDate.Set(new BSONDateTimeElement("$gte", query.StartDate));
                betweenDate.Set(new BSONDateTimeElement("$lte", query.EndDate));
                qry.Set(new BSONDocumentElement("dt", betweenDate));
                if (query.DimensionFilter.IsNotNullOrEmpty())
                {
                    TrendingHost.MapGaugeDimensions(collection, query.DimensionFilter)
                    .ForEach(pair => qry.Set(new BSONStringElement(pair.Key, pair.Value)));
                }

                var find = new Query();
                find.Set(new BSONDocumentElement("$query", qry));
                find.Set(new BSONDocumentElement("$orderby", sort));

                var fetchBy = 1000;
                if (query.FetchCount < fetchBy)
                {
                    fetchBy = query.FetchCount;
                }
                using (var cursor = m_Database[collection].Find(find, query.FetchStart, fetchBy))
                {
                    foreach (var doc in cursor)
                    {
                        if (result.Count >= query.FetchCount)
                        {
                            break;
                        }

                        var doc_dt = doc[DBConsts.FIELD_DATETIME].ObjectValue;

                        var dt   = doc[DBConsts.FIELD_DATETIME].ObjectValue.AsDateTime();
                        var dl   = MapDetalizationToMinutes(DetalizationLevel);
                        var gshr = RowConverter.GDID_BSONtoCLR((BSONBinaryElement)doc[DBConsts.FIELD_G_SHARD]);
                        var gent = RowConverter.GDID_BSONtoCLR((BSONBinaryElement)doc[DBConsts.FIELD_G_ENTITY]);
                        var val  = doc[DBConsts.FIELD_VALUE].ObjectValue.AsULong();

                        result.Add(new TrendingEntity(dt,
                                                      dl,
                                                      query.EntityType,
                                                      gshr,
                                                      gent,
                                                      val
                                                      )
                                   );
                    }
                }
            }
            return(result);
        }
예제 #60
0
파일: BSON.cs 프로젝트: itadapter/nfx
        public void ReadUnicodeStrings()
        {
            var src = Convert.FromBase64String(@"6AAAAAJlbmcABgAAAGhlbGxvAAJydXMADQAAANC/0YDQuNCy0LXRggACY2hpAAcAAADkvaDlpb0AAmphcAAQAAAA44GT44KT44Gr44Gh44GvAAJncmUAEAAAAM6zzrXOuc6xIM+DzrHPggACYWxiAA8AAABww6tyc2jDq25kZXRqZQACYXJtABIAAADVotWh1oDVpdaCINWB1aXVpgACdmllAAoAAAB4aW4gY2jDoG8AAnBvcgAFAAAAT2zDoQACdWtyAA0AAADQn9GA0LjQstGW0YIAAmdlcgAJAAAAd8O8bnNjaGUAAA==");

              using (var stream = new MemoryStream(src))
              {
            var root = new BSONDocument(stream);

            Assert.AreEqual(root.ByteSize, 232);
            Assert.AreEqual(root.Count, 11);

            var element = root["eng"] as BSONStringElement;
            Assert.IsNotNull(element);
            Assert.AreEqual(element.ElementType, BSONElementType.String);
            Assert.AreEqual(element.Name, "eng");
            Assert.AreEqual(element.Value, "hello");

            element = root["rus"] as BSONStringElement;
            Assert.IsNotNull(element);
            Assert.AreEqual(element.ElementType, BSONElementType.String);
            Assert.AreEqual(element.Name, "rus");
            Assert.AreEqual(element.Value, "привет");

            element = root["chi"] as BSONStringElement;
            Assert.IsNotNull(element);
            Assert.AreEqual(element.ElementType, BSONElementType.String);
            Assert.AreEqual(element.Name, "chi");
            Assert.AreEqual(element.Value, "你好");

            element = root["jap"] as BSONStringElement;
            Assert.IsNotNull(element);
            Assert.AreEqual(element.ElementType, BSONElementType.String);
            Assert.AreEqual(element.Name, "jap");
            Assert.AreEqual(element.Value, "こんにちは");

            element = root["gre"] as BSONStringElement;
            Assert.IsNotNull(element);
            Assert.AreEqual(element.ElementType, BSONElementType.String);
            Assert.AreEqual(element.Name, "gre");
            Assert.AreEqual(element.Value, "γεια σας");

            element = root["alb"] as BSONStringElement;
            Assert.IsNotNull(element);
            Assert.AreEqual(element.ElementType, BSONElementType.String);
            Assert.AreEqual(element.Name, "alb");
            Assert.AreEqual(element.Value, "përshëndetje");

            element = root["arm"] as BSONStringElement;
            Assert.IsNotNull(element);
            Assert.AreEqual(element.ElementType, BSONElementType.String);
            Assert.AreEqual(element.Name, "arm");
            Assert.AreEqual(element.Value, "բարեւ Ձեզ");

            element = root["vie"] as BSONStringElement;
            Assert.IsNotNull(element);
            Assert.AreEqual(element.ElementType, BSONElementType.String);
            Assert.AreEqual(element.Name, "vie");
            Assert.AreEqual(element.Value, "xin chào");

            element = root["por"] as BSONStringElement;
            Assert.IsNotNull(element);
            Assert.AreEqual(element.ElementType, BSONElementType.String);
            Assert.AreEqual(element.Name, "por");
            Assert.AreEqual(element.Value, "Olá");

            element = root["ukr"] as BSONStringElement;
            Assert.IsNotNull(element);
            Assert.AreEqual(element.ElementType, BSONElementType.String);
            Assert.AreEqual(element.Name, "ukr");
            Assert.AreEqual(element.Value, "Привіт");

            element = root["ger"] as BSONStringElement;
            Assert.IsNotNull(element);
            Assert.AreEqual(element.ElementType, BSONElementType.String);
            Assert.AreEqual(element.Name, "ger");
            Assert.AreEqual(element.Value, "wünsche");

            Assert.AreEqual(stream.Position, 232); // ensure whole document readed
              }
        }