// public static methods
        /// <summary>
        /// Default implementation of the CanCommandBeSentToSecondary delegate.
        /// </summary>
        /// <param name="document">The command.</param>
        /// <returns>True if the command can be sent to a secondary member of a replica set.</returns>
        public static bool DefaultImplementation(BsonDocument document)
        {
            if (document.ElementCount == 0)
            {
                return false;
            }

            var commandName = document.GetElement(0).Name;

            if (__secondaryOkCommands.Contains(commandName))
            {
                return true;
            }

            if (commandName.Equals("mapreduce", StringComparison.InvariantCultureIgnoreCase))
            {
                BsonValue outValue;
                if (document.TryGetValue("out", out outValue) && outValue.IsBsonDocument)
                {
                    return outValue.AsBsonDocument.Contains("inline");
                }
            }

            return false;
        }
Esempio n. 2
0
        public void TestBsonDocumentNoId()
        {
            _collection.RemoveAll();

            var document = new BsonDocument
            {
                { "A", 1 }
            };
            _collection.Save(document);
            Assert.Equal(2, document.ElementCount);
            Assert.Equal("_id", document.GetElement(0).Name);
            Assert.IsType<BsonObjectId>(document["_id"]);
            Assert.NotEqual(ObjectId.Empty, document["_id"].AsObjectId);
            Assert.Equal(1, _collection.Count());

            var id = document["_id"].AsObjectId;
            document["A"] = 2;
            _collection.Save(document);
            Assert.Equal(id, document["_id"].AsObjectId);
            Assert.Equal(1, _collection.Count());

            document = _collection.FindOneAs<BsonDocument>();
            Assert.Equal(2, document.ElementCount);
            Assert.Equal(id, document["_id"].AsObjectId);
            Assert.Equal(2, document["A"].AsInt32);
        }
Esempio n. 3
0
 /// <summary>
 /// 获取Match
 /// </summary>
 /// <returns></returns>
 public BsonDocument GetMatchDocument()
 {
     BsonDocument Matchlist = new BsonDocument();
     foreach (ctlMatchItem item in this.Controls)
     {
         BsonDocument match = item.getMatchItem();
         if (match != null)
         {
             string MatchName = match.GetElement(0).Name;
             if (Matchlist.Contains(MatchName))
             {
                 BsonDocument AddMatch = match.GetElement(0).Value.AsBsonDocument;
                 Matchlist.GetElement(MatchName).Value.AsBsonDocument.Add(AddMatch);
             }
             else {
                 Matchlist.Add(match);
             }
         }
     }
     if (Matchlist.ElementCount > 0)
     {
         return new BsonDocument("$match", Matchlist);
     }
     else
     {
         return null;
     }
 }
        public void TestBsonDocumentBsonNullId()
        {
            collection.RemoveAll();

            var document = new BsonDocument {
                { "_id", BsonNull.Value },
                { "A", 1 }
            };
            collection.Save(document);
            Assert.AreEqual(2, document.ElementCount);
            Assert.AreEqual("_id", document.GetElement(0).Name);
            Assert.IsInstanceOf<BsonObjectId>(document["_id"]);
            Assert.AreNotEqual(ObjectId.Empty, document["_id"].AsObjectId);
            Assert.AreEqual(1, collection.Count());

            var id = document["_id"].AsObjectId;
            document["A"] = 2;
            collection.Save(document);
            Assert.AreEqual(id, document["_id"].AsObjectId);
            Assert.AreEqual(1, collection.Count());

            document = collection.FindOneAs<BsonDocument>();
            Assert.AreEqual(2, document.ElementCount);
            Assert.AreEqual(id, document["_id"].AsObjectId);
            Assert.AreEqual(2, document["A"].AsInt32);
        }
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            string id = document.GetElement(MonthStackStatsRepository.FieldNames.Id).Value.AsString;

            string[] parts = id.Split('/');
            if (parts.Length > 0)
                return;

            string errorStackId = parts[0];
            var stackCollection = Database.GetCollection(ErrorStackRepository.CollectionName);
            var errorStack = stackCollection.FindOne(Query.EQ(ErrorStackRepository.FieldNames.Id, new BsonObjectId(new ObjectId(errorStackId))));

            if (errorStack != null) {
                var projectId = errorStack.GetElement(ErrorStackRepository.FieldNames.ProjectId).Value;
                document.Set(MonthStackStatsRepository.FieldNames.ProjectId, projectId);
            }

            document.Set(MonthStackStatsRepository.FieldNames.ErrorStackId, new BsonObjectId(new ObjectId(errorStackId)));

            var emptyBlocks = new List<BsonElement>();
            BsonDocument dayBlocks = document.GetValue(MonthStackStatsRepository.FieldNames.DayStats).AsBsonDocument;
            foreach (BsonElement b in dayBlocks.Elements) {
                if (b.Value.AsInt32 == 0)
                    emptyBlocks.Add(b);
            }

            foreach (BsonElement b in emptyBlocks)
                dayBlocks.RemoveElement(b);

            collection.Save(document);
        }
        public void TestBsonDocumentEmptyGuid()
        {
            _collection.RemoveAll();

            var document = new BsonDocument
            {
                { "_id", Guid.Empty },
                { "A", 1 }
            };
            _collection.Save(document);
            Assert.AreEqual(2, document.ElementCount);
            Assert.AreEqual("_id", document.GetElement(0).Name);
            Assert.IsInstanceOf<BsonBinaryData>(document["_id"]);
            Assert.AreNotEqual(Guid.Empty, document["_id"].AsGuid);
            Assert.AreEqual(1, _collection.Count());

            var id = document["_id"].AsGuid;
            document["A"] = 2;
            _collection.Save(document);
            Assert.AreEqual(id, document["_id"].AsGuid);
            Assert.AreEqual(1, _collection.Count());

            document = _collection.FindOneAs<BsonDocument>();
            Assert.AreEqual(2, document.ElementCount);
            Assert.AreEqual(id, document["_id"].AsGuid);
            Assert.AreEqual(2, document["A"].AsInt32);
        }
Esempio n. 7
0
 /// <summary>
 ///     获取Match
 /// </summary>
 /// <returns></returns>
 public BsonDocument GetMatchDocument()
 {
     var matchlist = new BsonDocument();
     foreach (CtlMatchItem item in Controls)
     {
         var match = item.GetMatchItem();
         if (match != null)
         {
             var matchName = match.GetElement(0).Name;
             if (matchlist.Contains(matchName))
             {
                 var addMatch = match.GetElement(0).Value.AsBsonDocument;
                 matchlist.GetElement(matchName).Value.AsBsonDocument.AddRange(addMatch);
             }
             else
             {
                 matchlist.AddRange(match);
             }
         }
     }
     if (matchlist.ElementCount > 0)
     {
         return new BsonDocument("$match", matchlist);
     }
     return null;
 }
Esempio n. 8
0
 /// <summary>
 ///     获取Match
 /// </summary>
 /// <returns></returns>
 public BsonDocument GetMatchDocument()
 {
     var matchlist = new BsonDocument();
     foreach (Control item in Controls)
     {
         if (item.GetType().FullName == typeof(Button).FullName) continue;
         var match = ((CtlMatchItem)item).GetMatchItem();
         if (match != null)
         {
             var matchName = match.GetElement(0).Name;
             if (matchlist.Contains(matchName))
             {
                 var addMatch = match.GetElement(0).Value.AsBsonDocument;
                 matchlist.GetElement(matchName).Value.AsBsonDocument.AddRange(addMatch);
             }
             else
             {
                 matchlist.AddRange(match);
             }
         }
     }
     if (matchlist.ElementCount > 0)
     {
         return new BsonDocument("$match", matchlist);
     }
     return null;
 }
Esempio n. 9
0
        public static void applyUpdateCommands(BsonDocument doc, BsonDocument change_spec)
        {
            foreach (var field in change_spec) {
                if (field.Name.Length > 0 && field.Name[0] == '$') {
                    // update command
                    switch (field.Name) {
                        case "$set":
                            _applySet(doc, field.Value.AsBsonDocument);
                            break;
                        case "$inc":
                            _applyInc(doc, field.Value.AsBsonDocument);
                            break;
                        case "$unset":
                            _applyUnset(doc, field.Value.AsBsonDocument);
                            break;
                        case "$push":
                        case "$pushAll":
                        case "$addToSet":
                        case "$pop":
                        case "$pull":
                        case "$pullAll":
                        case "$rename":
                        case "$":
                            throw new Exception("unimplemented update operator: " + field.Name);
                        default:
                            throw new Exception("unknown update operator: " + field.Name);
                    }

                } else {
                    // field replace
                    if (field.Value.BsonType == BsonType.Document) {
                        if (!doc.Contains(field.Name) ||
                            doc.GetElement(field.Name).Value.BsonType != BsonType.Document) {
                            // make a document to hold the recurse
                            doc.Set(field.Name, new BsonDocument());
                        }
                        // recursively apply changes
                        applyUpdateCommands(doc.GetElement(field.Name).Value.AsBsonDocument,
                            field.Value.AsBsonDocument);
                    } else {
                        // otherwise just apply the change directly
                        doc.Set(field.Name, field.Value);
                    }
                }
            }
        }
        private void M_Tick(object sender, EventArgs e)
        {
            BsonDocument DocStatus =
                CommandHelper.ExecuteMongoSvrCommand(CommandHelper.serverStatus_Command,
                                                     SystemManager.GetCurrentServer()).Response;

            var queryPoint = new DataPoint();

            queryPoint.SetValueXY(DateTime.Now.ToString(CultureInfo.InvariantCulture),
                                  DocStatus.GetElement("opcounters").Value.AsBsonDocument.GetElement("query").Value);
            MonitorGrap.Series[0].Points.Add(queryPoint);

            var insertPoint = new DataPoint();

            insertPoint.SetValueXY(DateTime.Now.ToString(CultureInfo.InvariantCulture),
                                   DocStatus.GetElement("opcounters").Value.AsBsonDocument.GetElement("insert").Value);
            MonitorGrap.Series[1].Points.Add(insertPoint);
        }
Esempio n. 11
0
        public void TestGetHeritageMapTableInformation()
        {
            var bson = new BsonDocument();

            GetHeritageProjects.GetHeritageMapTableInformation(bson);
            Console.WriteLine(bson);
            Assert.IsTrue(bson.ElementCount > 0);
            Assert.IsTrue(((bson.GetElement(0).Value) as BsonArray).Count == 2);
        }
Esempio n. 12
0
        /// <summary>
        /// Parse logLine and extract required data from it
        /// </summary>
        /// <param name="logLine"></param>
        public AccessSessionInfo(BsonDocument logLine)
        {
            apache_request_id = logLine.GetValue("request_id").AsString;
            request_method    = logLine.GetValue("request_method").AsString;
            request_ip        = logLine.GetValue("request_ip").AsString;
            resource          = logLine.GetValue("resource").AsString;
            load_time         = logLine.GetValue("request_time").AsString;
            var offset     = logLine.GetElement("ts_offset").Value.ToString();
            var timeOffSet = int.Parse(offset);
            var ts         = new System.TimeSpan(timeOffSet / 100, timeOffSet % 100, 0);

            //convert the current time to UTC
            var browserStartTime = (DateTime)logLine.GetElement("ts").Value - ts;

            request_time = browserStartTime.ToUniversalTime();

            status_code = logLine.GetValue("status_code").AsString;
        }
Esempio n. 13
0
        /// <summary>
        /// Parse explain('executionStats') for non aggregate queries
        /// </summary>
        /// <param name="ExplainQuery"></param>
        /// <returns></returns>
        public QueryStats GetExplainResultNonAggregate(string ExplainQuery)
        {
            BsonDocument QueryExplainResult = _executeQuery(ExplainQuery);

            string resultjson = QueryExplainResult.GetElement("retval").Value.ToBsonDocument()
                                .GetElement("executionStats").Value.ToJson();

            return(JsonConvert.DeserializeObject <QueryStats>(resultjson));
        }
        private static EncryptedMessageHeaders ReadHeaders(BsonDocument journalEntry)
        {
            var headersSubdocument = journalEntry.GetElement("headers").Value.ToBsonDocument();
            var headersDict        = headersSubdocument.ToDictionary(
                element => element.Name,
                element => element.Value.AsString);

            return(new EncryptedMessageHeaders(headersDict));
        }
Esempio n. 15
0
        /// <summary>
        /// 更新文档
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="collectionName"></param>
        /// <param name="updateUser"></param>
        public static void UpdateDocument(BsonDocument obj, string collectionName, string updateUser = UserSystem)
        {
            MongoCollection targetCollection = InnerDefaultDatabase.GetCollection(collectionName);

            //Remove Old
            targetCollection.Remove(Query.EQ(MongoKeyField, obj.GetElement(MongoKeyField).Value), WriteConcern.Acknowledged);
            //Insert New
            targetCollection.Insert(obj);
        }
Esempio n. 16
0
        public static Dialogue DecodeDialogue(BsonDocument dialogueDocument, Config config)
        {
            string text   = dialogueDocument.GetValue("text").AsString;
            string author = dialogueDocument.GetValue("author").AsString;
            string sprite = dialogueDocument.GetValue("sprite").AsString;

            List <Option> options = new List <Option>();

            if (dialogueDocument.Contains("options"))
            {
                var bsonOptions = dialogueDocument.GetElement("options").Value.AsBsonArray;
                foreach (var bsonOption in bsonOptions)
                {
                    var optionDocument = bsonOption.AsBsonDocument;
                    options.Add(DecodeOption(optionDocument.AsBsonDocument));
                }
            }

            List <PlayerAction> actions = new List <PlayerAction>();

            if (dialogueDocument.Contains("actions"))
            {
                var bsonActions = dialogueDocument.GetElement("actions").Value.AsBsonArray;
                foreach (var bsonAction in bsonActions)
                {
                    var actionDocument = bsonAction.AsBsonDocument;
                    actions.Add(DecodeAction(actionDocument, config.baseItems));
                }
            }

            List <Substitution> substitutions = new List <Substitution>();

            if (dialogueDocument.Contains("substitutions"))
            {
                var bsonSubs = dialogueDocument.GetElement("substitutions").Value.AsBsonArray;
                foreach (var subValue in bsonSubs)
                {
                    var subDocument = subValue.AsBsonDocument;
                    substitutions.Add(DecodeSubstitution(subDocument, config));
                }
            }

            return(new Dialogue(text, author, sprite, options.ToArray(), actions.ToArray(), substitutions.ToArray()));
        }
Esempio n. 17
0
        public void Should_process_a_get_more()
        {
            var expectedCommand = new BsonDocument
            {
                { "getMore", 20L },
                { "collection", MessageHelper.DefaultCollectionNamespace.CollectionName },
                { "batchSize", 40 }
            };
            var expectedReplyDocuments = new[]
            {
                new BsonDocument("first", 1),
                new BsonDocument("second", 2)
            };
            var expectedReply = new BsonDocument
            {
                { "cursor", new BsonDocument
                  {
                      { "id", expectedCommand["getMore"].ToInt64() },
                      { "ns", MessageHelper.DefaultCollectionNamespace.FullName },
                      { "nextBatch", new BsonArray(expectedReplyDocuments) }
                  } },
                { "ok", 1 }
            };

            var requestMessage = MessageHelper.BuildGetMore(
                requestId: 10,
                cursorId: expectedCommand["getMore"].ToInt64(),
                batchSize: 40);

            SendMessages(requestMessage);

            var replyMessage = MessageHelper.BuildReply <BsonDocument>(
                expectedReplyDocuments,
                BsonDocumentSerializer.Instance,
                responseTo: requestMessage.RequestId,
                cursorId: expectedReply["cursor"]["id"].ToInt64());

            ReceiveMessages(replyMessage);

            var commandStartedEvent   = (CommandStartedEvent)_capturedEvents.Next();
            var commandSucceededEvent = (CommandSucceededEvent)_capturedEvents.Next();

            commandStartedEvent.CommandName.Should().Be(expectedCommand.GetElement(0).Name);
            commandStartedEvent.Command.Should().Be(expectedCommand);
            commandStartedEvent.ConnectionId.Should().Be(_subject.ConnectionId);
            commandStartedEvent.DatabaseNamespace.Should().Be(MessageHelper.DefaultDatabaseNamespace);
            commandStartedEvent.OperationId.Should().Be(EventContext.OperationId);
            commandStartedEvent.RequestId.Should().Be(requestMessage.RequestId);

            commandSucceededEvent.CommandName.Should().Be(commandStartedEvent.CommandName);
            commandSucceededEvent.ConnectionId.Should().Be(commandStartedEvent.ConnectionId);
            commandSucceededEvent.Duration.Should().BeGreaterThan(TimeSpan.Zero);
            commandSucceededEvent.OperationId.Should().Be(commandStartedEvent.OperationId);
            commandSucceededEvent.Reply.Should().Be(expectedReply);
            commandSucceededEvent.RequestId.Should().Be(commandStartedEvent.RequestId);
        }
        /// <summary>
        ///     Insert a new profile, if is set the idProfile, make an update of that idProfile
        /// </summary>
        /// <param name="idProfile">
        ///     Id of the profile to update.
        /// </param>
        /// <returns>
        ///     Returns the view to create a new profile
        /// </returns>
        public ActionResult newProfile(string idProfile = null)
        {
            bool   view                  = false;
            bool   edit                  = false;
            bool   editClient            = false;
            bool   viewClient            = false;
            String dataPermissions       = Session["Permissions"].ToString();
            String dataPermissionsClient = Session["PermissionsClient"].ToString();
            bool   access                = false;
            bool   accessClient          = false;

            //  access = getpermissions("users", "r");
            access       = validatepermissions.getpermissions("profiles", "c", dataPermissions);
            accessClient = validatepermissions.getpermissions("profiles", "c", dataPermissionsClient);
            edit         = validatepermissions.getpermissions("profiles", "u", dataPermissions);
            editClient   = validatepermissions.getpermissions("profiles", "u", dataPermissionsClient);
            view         = validatepermissions.getpermissions("profiles", "r", dataPermissions);
            viewClient   = validatepermissions.getpermissions("profiles", "r", dataPermissionsClient);

            if (idProfile != null && (edit == false || editClient == false))
            {
                access = false;
            }
            if (view == false || viewClient == false)
            {
                accessClient = false; access = false;
            }

            if (access == true && accessClient == true)
            {
                CustomFieldsTable cft = new CustomFieldsTable("LocationCustomFields");

                String fieldsArray = cft.GetRows();
                JArray fields      = JsonConvert.DeserializeObject <JArray>(fieldsArray);

                if (idProfile != null && idProfile != "null" && idProfile != "")
                {
                    BsonDocument profile = _locationprofileTable.getRow(idProfile);
                    if (profile != null)
                    {
                        profile.Set("_id", profile.GetElement("_id").Value.ToString());
                        string profileJson = profile.ToJson();
                        ViewData["profile"] = new HtmlString(profileJson);
                    }
                }

                List <BsonDocument> profiles = _locationprofileTable.getRows();
                ViewBag.profiles = profiles;

                return(View(fields));
            }
            else
            {
                return(Redirect("~/Home"));
            }
        }
Esempio n. 19
0
        /// <summary>
        ///     插入空文档
        /// </summary>
        /// <param name="mongoCol"></param>
        /// <param name="safeMode"></param>
        /// <returns>插入记录的ID</returns>
        public static BsonValue InsertEmptyDocument(MongoCollection mongoCol, bool safeMode)
        {
            var document = new BsonDocument();

            if (safeMode)
            {
                try
                {
                    mongoCol.Insert(document, WriteConcern.Acknowledged);
                    return(document.GetElement(ConstMgr.KeyId).Value);
                }
                catch
                {
                    return(BsonNull.Value);
                }
            }
            mongoCol.Insert(document);
            return(document.GetElement(ConstMgr.KeyId).Value);
        }
Esempio n. 20
0
        private void UpdateStaffFingerprint(BsonDocument document)
        {
            var filter = Builders <BsonDocument> .Filter.Eq("_id", document.GetElement("_id").Value);

            var update = Builders <BsonDocument> .Update
                         .Set("fingerprint", true)
                         .Set("updatedAt", DateTime.Now);

            collection.UpdateOne(filter, update);
        }
        public void RenamePropertyFact()
        {
            // Arrange
            var oldName  = AutoFixture.String();
            var newName  = AutoFixture.String();
            var value    = AutoFixture.String();
            var document = new BsonDocument(new BsonElement(oldName, value));

            // Act
            document.RenameProperty(oldName, newName);
            var @new = document.GetElement(newName);

            // Assert
            Action act = () => document.GetElement(oldName);

            act.ShouldThrow <Exception>();
            @new.Should().NotBeNull();
            @new.Value.Should().Be(value);
        }
Esempio n. 22
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            if (!document.Contains(ErrorStackRepository.FieldNames.SignatureInfo))
                return;

            var signatureInfo = document.GetElement(ErrorStackRepository.FieldNames.SignatureInfo).Value.AsBsonDocument;
            bool renamed = signatureInfo.ChangeName("AppPath", "Path");

            if (renamed)
                collection.Save(document);
        }
Esempio n. 23
0
        private async Task Upsert(ImportTemplate importTemplate, BsonDocument bsonDocument)
        {
            var filterDef = Builders <BsonDocument> .Filter.Eq("_id", bsonDocument.GetElement("_id").Value);

            var collections = _mongoDatabase.GetCollection <BsonDocument>(importTemplate.Schema);
            await collections.UpdateOneAsync(filterDef, bsonDocument, new UpdateOptions()
            {
                IsUpsert = true
            });
        }
        /// <summary>
        ///     插入空文档
        /// </summary>
        /// <param name="mongoCol"></param>
        /// <returns>插入记录的ID</returns>
        public static BsonValue InsertEmptyDocument(MongoCollection mongoCol, Boolean safeMode)
        {
            var document = new BsonDocument();

            if (safeMode)
            {
                try
                {
                    mongoCol.Insert(document, WriteConcern.Acknowledged);
                    return(document.GetElement(KEY_ID).Value);
                }
                catch (Exception)
                {
                    return(BsonNull.Value);
                }
            }
            mongoCol.Insert(document);
            return(document.GetElement(KEY_ID).Value);
        }
Esempio n. 25
0
        public override void Save()
        {
            Collection = Connection.GetCollection(collectionName);
            if (_id.CompareTo(new ObjectId()) == 0)
            {
                var document = new BsonDocument()
                {
                    { "Description", Description },
                    { "Doctor", Doctor.Id },
                    { "Article", new MongoDBRef("Article", Article._id).ToBsonDocument() },
                    { "Tags", new BsonArray() },
                    { "MedicineObjects", new BsonArray() },
                    { "Changes", new BsonArray() }
                };
                foreach (Tag tag in Tags)
                {
                    document.GetElement("Tags").Value.AsBsonArray.Add(new MongoDBRef("Tag", tag._id).ToBsonDocument());
                }
                foreach (IEhrObject medicineObject in MedicineObjects)
                {
                    document.GetElement("MedicineObjects").Value.AsBsonArray.Add(new BsonDocument
                    {
                        { "Table", (medicineObject as SqlEntity).TableName },
                        { "Id", (medicineObject as SqlEntity).Id }
                    });
                }
                Change change = new Change();
                document.GetElement("Changes").Value.AsBsonArray.Add(new BsonDocument
                {
                    { "ChangeTime", change.ChangeTime },
                    { "Content", change.Content }
                });
                Collection.InsertOne(document);
                _id = document.GetValue("_id").AsObjectId;
            }
            else
            {
                var filter = Builders <BsonDocument> .Filter.Eq("_id", _id);

                //
            }
        }
Esempio n. 26
0
        /// <summary>
        ///     Allows to create or modigy a category
        /// </summary>
        /// <param name="jsonString">
        ///     The category json string with the document's information
        /// </param>
        /// <param name="id">
        ///     The modifying document's id
        /// </param>
        /// <author>
        ///     Luis Gonzalo Quijada Romero
        /// </author>
        /// <returns>
        ///     Returns the id of the saved document
        /// </returns>
        public String saveRow(String jsonString, String id = null)
        {
            BsonDocument doc;

            try //does the jsonString have a json correct format?
            {
                doc = BsonDocument.Parse(jsonString);
            }
            catch (Exception e) {
                return(null);
            }

            if (id != null && id != "")
            {
                doc.Set("_id", new ObjectId(id));
                BsonDocument lastData = BsonDocument.Parse(this.getRow(id));
                try
                {
                    doc.Set("CreatedDate", lastData.GetElement("CreatedDate").Value);
                }
                catch (Exception e) {
                    doc.Set("CreatedDate", DateTime.Now.ToString()); //if created date is not set let set it to the current date
                }

                try
                {
                    doc.Set("Creator", lastData.GetElement("Creator").Value);
                }
                catch (Exception e) {
                    doc.Set("Creator", HttpContext.Current.Session["_id"].ToString()); //if creator is not set let's set it to the current user's id
                }
            }
            else
            {
                doc.Set("CreatedDate", DateTime.Now.ToString());
                doc.Set("Creator", HttpContext.Current.Session["_id"].ToString());
            }
            doc.Set("LastmodDate", DateTime.Now.ToString());

            collection.Save(doc);
            return(doc["_id"].ToString());
        }
Esempio n. 27
0
 public BsonElement GetNextElement()
 {
     if (_index < _document.ElementCount)
     {
         return(_document.GetElement(_index++));
     }
     else
     {
         return(null);
     }
 }
Esempio n. 28
0
        private List <BsonDocument> GetFeaturesDocument(IMongoCollection <BsonDocument> featuresCollection, BsonDocument elements)
        {
            string brand      = elements.GetElement("Maker").Value.ToString().ToLower(),
                   model      = elements.GetElement("Model").Value.ToString().ToLower();
            var filterBuilder = Builders <BsonDocument> .Filter;
            var filter        = filterBuilder.Eq("Brand", brand) & filterBuilder.Eq("Model", model);
            var cur           = featuresCollection.Find(filter).ToCursor();
            List <BsonDocument> returnValue = new List <BsonDocument>();

            try
            {
                foreach (var doc in cur.ToEnumerable())
                {
                    returnValue.Add(doc);
                }
                return(returnValue);
            }
            catch
            { return(null); }
        }
 private void AddToAllAFL(BsonDocument doc, int idx)
 {
     if (doc != null)
     {
         try
         {
             Words[idx]         = doc.GetElement("words").Value.AsBsonArray.Count;
             PositiveCount[idx] = doc.GetElement("tone").Value.AsBsonDocument["positiveCount"].AsInt32;
         }
         catch (Exception e)
         {
             AddToAllAFL(null, idx);
         }
     }
     else
     {
         Words[idx]         = 0;
         PositiveCount[idx] = 0;
     }
 }
Esempio n. 30
0
        /// <summary>
        /// Parse explain('executionStats') for aggregate queries
        /// </summary>
        /// <param name="ExplainQuery"></param>
        /// <returns></returns>
        public QueryStats GetExplainResult(string ExplainQuery)
        {
            BsonDocument QueryExplainResult = _executeQuery(ExplainQuery);

            string resultjson = QueryExplainResult.GetElement("retval").Value.ToBsonDocument()
                                .GetElement("stages").Value.AsBsonArray.First().ToBsonDocument()
                                .GetElement("$cursor").Value.ToBsonDocument()
                                .GetElement("executionStats").Value.ToJson();

            return(JsonConvert.DeserializeObject <QueryStats>(resultjson));
        }
        public ResultModel Update(MetaObject metaObject, FilterDefinition <BsonDocument> condition, BsonDocument bsons)
        {
            //错误信息返回值
            HashSet <string> ErrorInfo = new HashSet <string>();

            if (bsons != null && bsons.Any())
            {
                //获取到字段列表
                var metaFields = metaFieldService.GetMetaFieldUpperKeyDicUnDeleted(metaObject.Id);
                for (int i = bsons.ElementCount - 1; i >= 0; i--)
                {
                    var    item     = bsons.GetElement(i);
                    string upperKey = item.Name.ToUpperInvariant();
                    if (metaFields.ContainsKey(upperKey))
                    {
                        //检查字段的值是否符合字段类型
                        var checkResult = metaFieldService.CheckAndGetFieldValueByFieldType(metaFields[upperKey], item.Value);
                        if (checkResult.IsSuccess)
                        {
                            //如果大小写不匹配,则都转化成配置的字段Code形式
                            if (!item.Name.Equals(metaFields[upperKey].Code))
                            {
                                bsons.RemoveElement(item);
                                bsons.Add(new BsonElement(metaFields[upperKey].Code, BsonValue.Create(checkResult.Data)));
                            }
                            else
                            {
                                //重置字段的真实类型的值
                                bsons.SetElement(new BsonElement(metaFields[upperKey].Code, BsonValue.Create(checkResult.Data)));
                            }
                        }
                        else
                        {
                            bsons.RemoveElement(item);
                            ErrorInfo.Add($"字段[{item.Name}]传递的值[{item.Value}]不符合字段定义的类型");
                        }
                    }
                    else
                    {
                        //如果字段不在配置字段中,则不进行添加
                        bsons.RemoveElement(item);
                        ErrorInfo.Add($"字段[{item.Name}]不属于对象[{metaObject.Code}({metaObject.Name})]定义的字段");
                    }
                }

                var collection = db.GetCollectionBson(metaObject.Code);
                var bu         = Builders <BsonDocument> .Update;
                foreach (var item in bsons)
                {
                    collection.UpdateMany(condition, bu.Set(item.Name, item.Value));
                }
            }
            return(ResultModel.Success($"修改成功,日志:{string.Join(",", ErrorInfo)}"));
        }
Esempio n. 32
0
        BsonDocument ExtractVideoFeatures(BsonDocument raw)
        {
            var doc = new BsonDocument();

            foreach (var feature in selectedFeatures)
            {
                if (raw.Names.Contains(feature))
                {
                    doc.SetElement(raw.GetElement(feature));
                }
            }

            // Flatten actorinfo
            var actorArray = new BsonArray();
            var actorDoc   = raw.GetValue("actorinfo").AsBsonDocument;

            foreach (var role in actorDoc.Elements)
            {
                foreach (var id in role.Value.AsBsonArray)
                {
                    actorArray.Add(new BsonDocument {
                        { "role", role.Name },
                        { "id", id }
                    });
                }
            }

            doc.Set("actorinfo", actorArray);

            // Hoist filterinfo
            var filterinfo = raw.GetValue("filterinfo").AsBsonDocument;

            foreach (var filter in filterinfoFeatures)
            {
                doc.SetElement(filterinfo.GetElement(filter));
            }

            // Extract child video names and desription
            var childNameArray = new BsonArray();
            var childDescArray = new BsonArray();
            var children       = raw.GetValue("_child").AsBsonArray;

            foreach (var child in children)
            {
                var cd = child.AsBsonDocument;
                childNameArray.Add(cd.GetValue("sname"));
                childDescArray.Add(cd.GetValue("storyplot"));
            }

            doc.Set("childnames", childNameArray);
            doc.Set("childplots", childDescArray);

            return(doc);
        }
Esempio n. 33
0
        public void Execute(BsonDocument doc)
        {
            var occurance = new BsonDocument(doc.GetElement("time"),
                                             doc.GetElement("details"));
            doc.Remove("time");
            doc.Remove("details");

            var query = Query.And(Query.EQ("token", doc["token"]),
                                  Query.EQ("hash", doc["hash"]));

            UpdateBuilder ub = new UpdateBuilder();
            ub.Push("occurances", occurance);
            ub.Set("token", doc["token"]);
            ub.Set("hash", doc["hash"]);
            ub.Set("level", doc["level"]);
            ub.Set("common", doc["common"]);
            ub.Set("lastTime", occurance["time"]);

            Events.Update(query, ub, UpdateFlags.Upsert);
        }
Esempio n. 34
0
 private static void AddClause(BsonDocument document, BsonElement clause)
 {
     if (clause.Name == "$and")
     {
         // flatten out nested $and
         foreach (var item in (BsonArray)clause.Value)
         {
             foreach (BsonElement element in (BsonDocument)item)
             {
                 AddClause(document, element);
             }
         }
     }
     else if (document.ElementCount == 1 && document.GetElement(0).Name == "$and")
     {
         ((BsonArray)document[0]).Add(new BsonDocument(clause));
     }
     else if (document.Contains(clause.Name))
     {
         BsonElement existingClause = document.GetElement(clause.Name);
         if (existingClause.Value is BsonDocument existingClauseValue &&
             clause.Value is BsonDocument clauseValue)
         {
             var clauseOperator = clauseValue.ElementCount > 0
                 ? clauseValue.GetElement(0).Name
                 : null;
             if (clauseValue.Names.Any(op => existingClauseValue.Contains(op)) ||
                 __operatorsThatCannotBeCombined.Contains(clauseOperator))
             {
                 PromoteFilterToDollarForm(document, clause);
             }
             else
             {
                 existingClauseValue.AddRange(clauseValue);
             }
         }
         else
         {
             PromoteFilterToDollarForm(document, clause);
         }
     }
Esempio n. 35
0
        private void buttonAnterior_Click(object sender, EventArgs e)
        {
            if (numCampo == 0)
            {
                numCampo = 0;
            }
            else
            {
                numCampo--;
            }

            try {
                //textBoxCampo.Text = document.GetElement(numCampo).Name.ToString();
                textBoxCampo.Text = document.GetElement(numCampo).Name.ToString();
                textBoxValor.Text = document.Elements.ElementAt(numCampo).Value.AsString;
            }
            catch (Exception) {
            }
            labelCampo.Text = "Campo " + (numCampo + 1).ToString();
            labelValor.Text = "Valor " + (numCampo + 1).ToString();
        }
        private void AssertCommandAspect(BsonDocument actualCommand, string name, BsonValue expectedValue)
        {
            var commandName = actualCommand.ElementCount == 0 ? "<unknown>" : actualCommand.GetElement(0).Name;

            if (expectedValue.IsBsonNull)
            {
                switch (name)
                {
                case "autocommit":
                case "readConcern":
                case "recoveryToken":
                case "startTransaction":
                case "txnNumber":
                case "writeConcern":
                    if (actualCommand.Contains(name))
                    {
                        throw new AssertionFailedException($"Did not expect field '{name}' in command: {actualCommand.ToJson()}.");
                    }
                    return;
                }
            }

            if (!actualCommand.Contains(name))
            {
                // some missing fields are only missing because the C# driver omits default values
                switch (name)
                {
                case "new":
                    if (commandName == "findAndModify" && expectedValue == false)
                    {
                        return;
                    }
                    break;
                }

                throw new AssertionFailedException($"Expected field '{name}' in command: {actualCommand.ToJson()}.");
            }

            var actualValue = actualCommand[name];

            if (name == "updates")
            {
                AdaptExpectedUpdateModels(actualValue.AsBsonArray.Cast <BsonDocument>().ToList(), expectedValue.AsBsonArray.Cast <BsonDocument>().ToList());
            }

            var namesToUseOrderInsensitiveComparisonWith = new[] { "writeConcern" };
            var useOrderInsensitiveComparison            = namesToUseOrderInsensitiveComparisonWith.Contains(name);

            if (!(useOrderInsensitiveComparison ? BsonValueEquivalencyComparer.Compare(actualValue, expectedValue) : actualValue.Equals(expectedValue)))
            {
                throw new AssertionFailedException($"Expected field '{name}' in command '{commandName}' to be {expectedValue.ToJson()} but found {actualValue.ToJson()}.");
            }
        }
        private void AssertEvent(object actualEvent, BsonDocument expectedEvent)
        {
            if (expectedEvent.ElementCount != 1)
            {
                throw new FormatException("Expected event must be a document with a single element with a name the specifies the type of the event.");
            }

            var eventType     = expectedEvent.GetElement(0).Name;
            var eventAsserter = EventAsserterFactory.CreateAsserter(eventType);

            eventAsserter.AssertAspects(actualEvent, expectedEvent[0].AsBsonDocument);
        }
Esempio n. 38
0
        private FindOperation <TResult> CreateAggregateToCollectionFindOperation <TResult>(BsonDocument outStage, IBsonSerializer <TResult> resultSerializer, AggregateOptions options)
        {
            CollectionNamespace outputCollectionNamespace;
            var stageName = outStage.GetElement(0).Name;

            switch (stageName)
            {
            case "$out":
            {
                var outputCollectionName = outStage[0].AsString;
                outputCollectionNamespace = new CollectionNamespace(_databaseNamespace, outputCollectionName);
            }
            break;

            case "$merge":
            {
                var mergeArguments = outStage[0].AsBsonDocument;
                DatabaseNamespace outputDatabaseNamespace;
                string            outputCollectionName;
                var into = mergeArguments["into"];
                if (into.IsString)
                {
                    outputDatabaseNamespace = _databaseNamespace;
                    outputCollectionName    = into.AsString;
                }
                else
                {
                    outputDatabaseNamespace = new DatabaseNamespace(into["db"].AsString);
                    outputCollectionName    = into["coll"].AsString;
                }
                outputCollectionNamespace = new CollectionNamespace(outputDatabaseNamespace, outputCollectionName);
            }
            break;

            default:
                throw new ArgumentException($"Unexpected stage name: {stageName}.");
            }

            // because auto encryption is not supported for non-collection commands.
            // So, an error will be thrown in the previous CreateAggregateToCollectionOperation step.
            // However, since we've added encryption configuration for CreateAggregateToCollectionOperation operation,
            // it's not superfluous to also add it here
            var messageEncoderSettings = GetMessageEncoderSettings();

            return(new FindOperation <TResult>(outputCollectionNamespace, resultSerializer, messageEncoderSettings)
            {
                BatchSize = options.BatchSize,
                Collation = options.Collation,
                MaxTime = options.MaxTime,
                ReadConcern = _settings.ReadConcern,
                RetryRequested = _client.Settings.RetryReads
            });
        }
        public async Task <string> Create(CollectionEnum collection, BsonDocument doc)
        {
            SetDate(doc, Const.MODIFIED_ELEMENT, DateTime.Now);

            var col = mongoDB.GetCollection <BsonDocument>(collection.ToString());

            await col.InsertOneAsync(doc);

            var idElement = doc.GetElement(Const.ID);

            return(idElement.Value.AsObjectId.ToString());
        }
Esempio n. 40
0
        /// <summary>
        ///     This methood allows to change a list's elements
        /// </summary>
        /// <param name="ListID">
        ///     the list's id
        /// </param>
        /// <param name="elementName">
        ///     The element's name which we want to change
        /// </param>
        /// <param name="newValue">
        ///     The value to set to the element
        /// </param>
        /// <returns></returns>
        public String changeElement(String ListID, String elementName, String newValue)
        {
            String dataPermissions       = Session["Permissions"].ToString();
            String dataPermissionsClient = Session["PermissionsClient"].ToString();
            bool   access       = false;
            bool   accessClient = false;

            //  access = getpermissions("users", "r");
            access       = validatepermissions.getpermissions("lists", "u", dataPermissions);
            accessClient = validatepermissions.getpermissions("lists", "u", dataPermissionsClient);

            if (access == true && accessClient == true)
            {
                if (this.Request.IsAjaxRequest())
                {
                    BsonDocument document     = listTable.getRow(ListID);
                    BsonDocument elements     = document.GetElement("elements").Value.ToBsonDocument();
                    BsonArray    unorderArray = (BsonArray)elements.GetElement("unorder").Value;
                    foreach (BsonDocument doc in unorderArray)
                    {
                        BsonElement element = doc.First();
                        if (element.Name == elementName)
                        {
                            element.Value = newValue;

                            String currentDocumentID = document.GetElement("_id").Value.ToString();
                            document.Remove("_id");
                            listTable.saveRow(document.ToJson(), currentDocumentID);
                            _logTable.SaveLog(Session["_id"].ToString(), "Listas", "Update: modificar elemento de lista", "List", DateTime.Now.ToString());
                            return(null);
                        }
                    }
                }
                return(null);
            }
            else
            {
                return(null);
            }
        }
    private List <string> Compare(BsonDocument first, BsonDocument second)
    {
        List <string> changedFields = new List <string>();

        foreach (string elementName in first.Names)
        {
            BsonElement element = first.GetElement(elementName);

            if (element.Value.IsBsonDocument)
            {
                BsonDocument elementDocument = element.Value.AsBsonDocument;

                BsonDocument secondElementDocument =
                    second.GetElement(element.Name).Value.AsBsonDocument;

                if (elementDocument.ElementCount > 1 &&
                    secondElementDocument.ElementCount ==
                    elementDocument.ElementCount)
                {
                    foreach (string value in (Compare(elementDocument,
                                                      secondElementDocument)))
                    {
                        changedFields.Add(value);
                    }
                }

                else
                {
                    changedFields.Add(element.Name);
                }
            }

            else if (element.Value != second.GetElement(element.Name).Value)
            {
                changedFields.Add(element.Name);
            }
        }

        return(changedFields);
    }
Esempio n. 42
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            if (!document.Contains(ErrorRepository.FieldNames.RequestInfo))
                return;

            BsonDocument requestInfo = document.GetElement(ErrorRepository.FieldNames.RequestInfo).Value.AsBsonDocument;
            if (!requestInfo.Contains("frm"))
                return;

            requestInfo.Add(ErrorRepository.FieldNames.PostData, new BsonString(requestInfo.GetElement("frm").Value.ToJson()));
            requestInfo.Remove("frm");

            collection.Save(document);
        }
Esempio n. 43
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            if (!document.Contains(ErrorRepository.FieldNames.ExceptionlessClientInfo))
                return;

            BsonDocument clientInfo = document.GetElement(ErrorRepository.FieldNames.ExceptionlessClientInfo).Value.AsBsonDocument;

            if (clientInfo.Contains("SubmissionMethod"))
                clientInfo.ChangeName("SubmissionMethod", ErrorRepository.FieldNames.SubmissionMethod);

            if (clientInfo.Contains(ErrorRepository.FieldNames.InstallDate)) {
                BsonValue installDateValue = clientInfo.GetElement(ErrorRepository.FieldNames.InstallDate).Value;
                if (installDateValue.IsBsonArray)
                    return;

                DateTime installDate = installDateValue.ToUniversalTime();
                clientInfo.AsBsonDocument.Set(ErrorRepository.FieldNames.InstallDate, new BsonArray(new BsonValue[] { new BsonInt64(installDate.Ticks), new BsonInt32(-360) }));
            }

            collection.Save(document);
        }
        public void TestBsonDocumentGeneratedGuid() {
            collection.RemoveAll();

            var guid = Guid.NewGuid();
            var document = new BsonDocument {
                { "_id", guid },
                { "A", 1 }
            };
            collection.Save(document);
            Assert.AreEqual(2, document.ElementCount);
            Assert.AreEqual("_id", document.GetElement(0).Name);
            Assert.IsInstanceOf<BsonBinaryData>(document["_id"]);
            Assert.AreEqual(guid, document["_id"].AsGuid);
            Assert.AreEqual(1, collection.Count());

            var id = document["_id"].AsGuid;
            document["A"] = 2;
            collection.Save(document);
            Assert.AreEqual(id, document["_id"].AsGuid);
            Assert.AreEqual(1, collection.Count());

            document = collection.FindOneAs<BsonDocument>();
            Assert.AreEqual(2, document.ElementCount);
            Assert.AreEqual(id, document["_id"].AsGuid);
            Assert.AreEqual(2, document["A"].AsInt32);
        }
        public void TestBsonDocumentGeneratedObjectId() {
            collection.RemoveAll();

            var id = ObjectId.GenerateNewId();
            var document = new BsonDocument {
                { "_id", id },
                { "A", 1 }
            };
            collection.Save(document);
            Assert.AreEqual(2, document.ElementCount);
            Assert.AreEqual("_id", document.GetElement(0).Name);
            Assert.IsInstanceOf<BsonObjectId>(document["_id"]);
            Assert.AreEqual(id, document["_id"].AsObjectId);
            Assert.AreEqual(1, collection.Count());

            document["A"] = 2;
            collection.Save(document);
            Assert.AreEqual(id, document["_id"].AsObjectId);
            Assert.AreEqual(1, collection.Count());

            document = collection.FindOneAs<BsonDocument>();
            Assert.AreEqual(2, document.ElementCount);
            Assert.AreEqual(id, document["_id"].AsObjectId);
            Assert.AreEqual(2, document["A"].AsInt32);
        }
 public void TestZeroLengthElementName() {
     var document = new BsonDocument("", "zero length");
     Assert.AreEqual(0, document.GetElement(0).Name.Length);
 }
 public void TestConstructorElement()
 {
     var element = new BsonElement("x", 1);
     var document = new BsonDocument(element);
     Assert.AreEqual(1, document.ElementCount);
     Assert.AreEqual(1, document["x"].AsInt32);
     Assert.AreEqual(true, document.Contains("x"));
     Assert.AreEqual(true, document.ContainsValue(1));
     Assert.AreSame(element, document.GetElement("x"));
 }
 public void TestConstructorElements()
 {
     var elements = new BsonElement[] {
         new BsonElement("x", 1),
         new BsonElement("y", 2)
     };
     var document = new BsonDocument((IEnumerable<BsonElement>)elements);
     Assert.AreEqual(2, document.ElementCount);
     Assert.AreEqual(1, document["x"].AsInt32);
     Assert.AreEqual(2, document["y"].AsInt32);
     Assert.AreEqual(true, document.Contains("x"));
     Assert.AreEqual(true, document.Contains("y"));
     Assert.AreEqual(true, document.ContainsValue(1));
     Assert.AreEqual(true, document.ContainsValue(2));
     Assert.AreSame(elements[0], document.GetElement("x"));
     Assert.AreSame(elements[1], document.GetElement("y"));
 }
Esempio n. 49
0
 private static void AssertTimestampLogged(BsonDocument doc)
 {
     var now = DateTime.UtcNow;
     var oneSecondAgo = now.AddSeconds(-1);
     doc.GetElement("timestamp").Value.ToUniversalTime().Should().Be.IncludedIn(oneSecondAgo, now);
 }
 public void TestInsertAt()
 {
     var document = new BsonDocument();
     document.InsertAt(0, new BsonElement("x", 1));
     Assert.AreEqual("x", document.GetElement(0).Name);
     Assert.AreEqual(1, document[0].AsInt32);
     document.InsertAt(0, new BsonElement("y", 2));
     Assert.AreEqual("y", document.GetElement(0).Name);
     Assert.AreEqual(2, document[0].AsInt32);
     Assert.AreEqual("x", document.GetElement(1).Name);
     Assert.AreEqual(1, document[1].AsInt32);
 }
Esempio n. 51
0
        /// <summary>
        /// Parses and returns the status from a replSetGetStatus result.
        /// </summary>
        private static ReplicaSetStatus ParseStatus(BsonDocument response)
        {
            // See if starting up...
            BsonValue startupStatus;
            if (response.TryGetValue("startupStatus", out startupStatus))
            {
                return new ReplicaSetStatus { Status = State.Initializing };
            }

            // Otherwise, extract the servers...
            return new ReplicaSetStatus
            {
                Status = State.OK,
                ReplicaSetName = response.GetValue("set").AsString,
                Servers = ServerStatus.Parse(response.GetElement("members").Value.AsBsonArray)
            };
        }
 // private static methods
 // try to keey the query in simple form and only promote to $and form if necessary
 private static void AddAndClause(BsonDocument query, BsonElement clause)
 {
     if (query.ElementCount == 1 && query.GetElement(0).Name == "$and")
     {
         query[0].AsBsonArray.Add(new BsonDocument(clause));
     }
     else
     {
         if (clause.Name == "$and")
         {
             PromoteQueryToDollarAndForm(query, clause);
         }
         else
         {
             if (query.Contains(clause.Name))
             {
                 var existingClause = query.GetElement(clause.Name);
                 if (existingClause.Value.IsBsonDocument && clause.Value.IsBsonDocument)
                 {
                     var clauseValue = clause.Value.AsBsonDocument;
                     var existingClauseValue = existingClause.Value.AsBsonDocument;
                     if (clauseValue.Names.Any(op => existingClauseValue.Contains(op)))
                     {
                         PromoteQueryToDollarAndForm(query, clause);
                     }
                     else
                     {
                         foreach (var element in clauseValue)
                         {
                             existingClauseValue.Add(element);
                         }
                     }
                 }
                 else
                 {
                     PromoteQueryToDollarAndForm(query, clause);
                 }
             }
             else
             {
                 query.Add(clause);
             }
         }
     }
 }
 public void TestConstructorElementsDocument()
 {
     var originalDocument = new BsonDocument { { "x", 1 }, { "y", 2 } };
     var document = new BsonDocument(originalDocument);
     Assert.AreEqual(2, document.ElementCount);
     Assert.AreEqual(1, document["x"].AsInt32);
     Assert.AreEqual(2, document["y"].AsInt32);
     Assert.AreEqual(true, document.Contains("x"));
     Assert.AreEqual(true, document.Contains("y"));
     Assert.AreEqual(true, document.ContainsValue(1));
     Assert.AreEqual(true, document.ContainsValue(2));
     Assert.AreSame(originalDocument.GetElement("x"), document.GetElement("x"));
     Assert.AreSame(originalDocument.GetElement("y"), document.GetElement("y"));
 }
 public void TestSetElementReplaceElement()
 {
     var document = new BsonDocument("x", 1);
     var element = new BsonElement("x", 2);
     document.SetElement(element);
     Assert.AreEqual(1, document.ElementCount);
     Assert.AreEqual("x", document.GetElement(0).Name);
     Assert.AreEqual(2, document["x"].AsInt32);
 }
 public void TestSetDocumentIdNewElement()
 {
     var document = new BsonDocument("x", 1);
     ((IBsonIdProvider)BsonDocumentSerializer.Instance).SetDocumentId(document, BsonValue.Create(2));
     Assert.AreEqual(2, document.ElementCount);
     Assert.AreEqual("_id", document.GetElement(0).Name);
     Assert.AreEqual(2, document["_id"].AsInt32);
 }
 public void TestRemoveElement()
 {
     var document = new BsonDocument { { "x", 1 }, { "y", 2 } };
     Assert.AreEqual(2, document.ElementCount);
     document.RemoveElement(document.GetElement(0));
     Assert.AreEqual(1, document.ElementCount);
     Assert.AreEqual(2, document["y"].AsInt32);
 }
        public void TestBsonDocumentStringId() {
            collection.RemoveAll();

            var id = "123";
            var document = new BsonDocument {
                { "_id", id },
                { "A", 1 }
            };
            collection.Save(document);
            Assert.AreEqual(2, document.ElementCount);
            Assert.AreEqual("_id", document.GetElement(0).Name);
            Assert.IsInstanceOf<BsonString>(document["_id"]);
            Assert.AreEqual(id, document["_id"].AsString);
            Assert.AreEqual(1, collection.Count());

            document["A"] = 2;
            collection.Save(document);
            Assert.AreEqual(id, document["_id"].AsString);
            Assert.AreEqual(1, collection.Count());

            document = collection.FindOneAs<BsonDocument>();
            Assert.AreEqual(2, document.ElementCount);
            Assert.AreEqual(id, document["_id"].AsString);
            Assert.AreEqual(2, document["A"].AsInt32);
        }
Esempio n. 58
0
 /** \fn void AttachCollection (string subClFullName, BsonDocument options)
  * \brief Attach the specified collection.
  * \param subClFullName The name of the subcollection
  * \param options The low boudary and up boudary
  *       eg: {"LowBound":{a:1},"UpBound":{a:100}}
  * \retval void
  * \exception SequoiaDB.BaseException
  * \exception System.Exception
  */
 public void AttachCollection(string subClFullName, BsonDocument options)
 {
     // check argument
     if (subClFullName == null || subClFullName.Equals("") ||
         subClFullName.Length > SequoiadbConstants.COLLECTION_MAX_SZ ||
         options == null || options.ElementCount == 0)
     {
         throw new BaseException("SDB_INVALIDARG");
     }
     // build a bson to send
     BsonDocument attObj = new BsonDocument();
     attObj.Add(SequoiadbConstants.FIELD_NAME, collectionFullName);
     attObj.Add(SequoiadbConstants.FIELD_SUBCLNAME, subClFullName);
     foreach (string key in options.Names)
     {
         attObj.Add(options.GetElement(key));
     }
     // build commond
     string commandString = SequoiadbConstants.ADMIN_PROMPT + SequoiadbConstants.LINK_CL;
     BsonDocument dummyObj = new BsonDocument();
     SDBMessage rtnSDBMessage = AdminCommand(commandString, attObj, dummyObj, dummyObj, dummyObj, 0, -1, 0);
     // check the return flag
     int flags = rtnSDBMessage.Flags;
     if (flags != 0)
         throw new BaseException(flags);
 }
        public void TestBsonDocumentInt64Id()
        {
            _collection.RemoveAll();

            var id = 123L;
            var document = new BsonDocument
            {
                { "_id", id },
                { "A", 1 }
            };
            _collection.Save(document);
            Assert.AreEqual(2, document.ElementCount);
            Assert.AreEqual("_id", document.GetElement(0).Name);
            Assert.IsInstanceOf<BsonInt64>(document["_id"]);
            Assert.AreEqual(id, document["_id"].AsInt64);
            Assert.AreEqual(1, _collection.Count());

            document["A"] = 2;
            _collection.Save(document);
            Assert.AreEqual(id, document["_id"].AsInt64);
            Assert.AreEqual(1, _collection.Count());

            document = _collection.FindOneAs<BsonDocument>();
            Assert.AreEqual(2, document.ElementCount);
            Assert.AreEqual(id, document["_id"].AsInt64);
            Assert.AreEqual(2, document["A"].AsInt32);
        }
        public void TestConstructorElementsParams()
        {
            var element1 = new BsonElement("x", 1);
            var element2 = new BsonElement("y", 2);
#pragma warning disable 618
            var document = new BsonDocument(element1, element2);
#pragma warning restore
            Assert.AreEqual(2, document.ElementCount);
            Assert.AreEqual(1, document["x"].AsInt32);
            Assert.AreEqual(2, document["y"].AsInt32);
            Assert.AreEqual(true, document.Contains("x"));
            Assert.AreEqual(true, document.Contains("y"));
            Assert.AreEqual(true, document.ContainsValue(1));
            Assert.AreEqual(true, document.ContainsValue(2));
            Assert.AreSame(element1, document.GetElement("x"));
            Assert.AreSame(element2, document.GetElement("y"));
        }