public void FindAndModifyTest1()
        {
            string entryMessage1 = "entry 1";
            AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);

            List<Entry> results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(entryMessage1, results[0].Message);

            var searchQuery = Query.EQ("Message", entryMessage1);

            var update = Update.Set("Message", MONGO_EDITED_TEXT);
            var sortBy = SortBy.Descending("TimeStamp");

            FindAndModifyArgs findAndModifyArgs = new FindAndModifyArgs();
            findAndModifyArgs.Query = searchQuery;
            findAndModifyArgs.SortBy = sortBy;
            findAndModifyArgs.Update = update;
            findAndModifyArgs.Upsert = true;
            findAndModifyArgs.VersionReturned = FindAndModifyDocumentVersion.Modified;

            _AsyncDelegateUpdaterT.FindAndModifyAsync(MONGO_COLLECTION_1_NAME, findAndModifyArgs);
            _updaterAutoResetEvent.WaitOne();

            Assert.IsTrue(_findAndModifyResult.Ok, "FindAndModifyResult from FindAndModify not OK");
            Assert.IsNull(_findAndModifyResult.ErrorMessage);
            Assert.IsNotNull(_findAndModifyResult.ModifiedDocument);

            results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(MONGO_EDITED_TEXT, results[0].Message);/*This field we modified via FindAndModify...*/
        }
        public long GenerateId()
        {
            bool lockTaken = false;
            try
            {
                // Entering single-thread block
                _lock.Enter(ref lockTaken);

                // Incrementing id if it belongs to reserved block
                if (_isIdBlockReserved && ++_idBlockOffset < IdBlockLength)
                {
                    return _idBlockBegin + _idBlockOffset;
                }

                // Reserving new id block as atomic operation
                MongoCollection<SequenceEntity> sequenceCollection = _sequenceRepository.Collection;
                IMongoQuery query = Query.EQ("Name", TrackingUrlSequenceName);
                IMongoSortBy sortBy = SortBy.Null;
                UpdateBuilder update = Update.Inc("Current", IdBlockLength);
                var argument = new FindAndModifyArgs { Query = query, SortBy = sortBy, Update = update, VersionReturned = FindAndModifyDocumentVersion.Modified };
                FindAndModifyResult result = sequenceCollection.FindAndModify(argument);
                BsonDocument sequence = result.ModifiedDocument;

                if (sequence == null)
                {
                    // first block
                    _idBlockBegin = 0;
                    _idBlockOffset = 0;

                    sequenceCollection.Insert(new SequenceEntity { Name = TrackingUrlSequenceName, Current = 0 });
                }
                else
                {
                    _idBlockBegin = sequence.GetValue("Current").AsInt64;
                    _idBlockOffset = 0;
                }

                _isIdBlockReserved = true;

                long newId = _idBlockBegin + _idBlockOffset;
                return newId;
            }
            finally
            {
                if (lockTaken)
                {
                    // Exiting single-thread block
                    _lock.Exit();
                }
            }
        }
        /// <summary>
        /// Returns the object at the beginning of the message queue,
        /// and updates its status to remove it from the queue.
        /// </summary>
        /// <returns>The object at the beginning of the message queue, or <see langword="null"/>.</returns>
        protected override MessageContainer DoDequeueMessage()
        {
            MongoCollection<BsonDocument> collection = this.database.GetCollection(MessagingDatabase.MessageQueue._COLLECTION_NAME);
            FindAndModifyArgs args = new FindAndModifyArgs
                                     {
                Query = Query.EQ(MessagingDatabase.MessageQueue.STATUS, MessageStatus.Queued.ToString("G")),
                Update = Update.Set(MessagingDatabase.MessageQueue.STATUS, MessageStatus.Outgoing.ToString("G"))
            };

            FindAndModifyResult result = collection.FindAndModify(args);
            if (result.ModifiedDocument == null)
            {
                return null;
            }

            return BsonConverter.ConvertToObjectViaJson<MessageContainer>(result.ModifiedDocument);
        }
Exemple #4
0
 public static long CreditBlock(long account, long amount)
 {
     try
     {
         MongoCollection accountCollection = DataHelper.Database.GetCollection("finance_account");
         FindAndModifyArgs args = new FindAndModifyArgs();
         args.Query = Query.And(
             Query.EQ("_id", account)
             );
         args.Update = MongoDB.Driver.Builders.Update.Inc("blocked", -amount);
         FindAndModifyResult result = accountCollection.FindAndModify(args);
         return result.ModifiedDocument.GetElement("available_balance").Value.ToInt64();
     }
     catch
     {
         return -1;
     }
 }
        public void FindAndModifyTest5()
        {
            _AsyncDelegateUpdaterT.AsyncFindAndModifyCompleted -= new FindAndModifyCompletedEvent(_updaterAsyncT_AsyncFindAndModifyCompleted);

            string entryMessage1 = "entry 1";
            AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);

            List<Entry> results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(entryMessage1, results[0].Message);

            var searchQuery = Query.EQ("Message", entryMessage1);

            var update = Update.Set("Message", MONGO_EDITED_TEXT);
            var sortBy = SortBy.Descending("TimeStamp");
            IMongoFields fields = Fields.Include("TimeStamp");

            FindAndModifyArgs findAndModifyArgs = new FindAndModifyArgs();
            findAndModifyArgs.Query = searchQuery;
            findAndModifyArgs.SortBy = sortBy;
            findAndModifyArgs.Update = update;
            findAndModifyArgs.Fields = fields;
            findAndModifyArgs.Upsert = true;
            findAndModifyArgs.VersionReturned = FindAndModifyDocumentVersion.Modified;

            _AsyncDelegateUpdaterT.FindAndModifyAsync(MONGO_COLLECTION_1_NAME, findAndModifyArgs);
            Thread.Sleep(2000); // wait 2 seconds to show that event handler will not pick up callback

            Assert.IsNull(_findAndModifyResult);

            results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(MONGO_EDITED_TEXT, results[0].Message);/*This field we modified via FindAndModify...*/
        }
Exemple #6
0
        public string NextKey(string name)
        {
            var collection = database.GetCollection(Collection.COUNTERS);

            FindAndModifyArgs args = new FindAndModifyArgs();
            args.Query = MonQ.Query.EQ("_id", name);
            args.Update = MonQ.Update.Inc(Field.COUNTERVALUE, 1);
            args.Fields = MonQ.Fields.Include(Field.COUNTERVALUE);
            args.Upsert = true;
            args.VersionReturned = FindAndModifyDocumentVersion.Modified;

            FindAndModifyResult result = collection.FindAndModify(args);
            BsonDocument document = result.ModifiedDocument;

            string value = Field.KEYPREFIX + document[Field.COUNTERVALUE].AsInt32.ToString();
            return value;
        }
Exemple #7
0
 public long GetNextSquence(string SequenceName)
 {
     try
     {
         MongoCollection sequenceCollection = Database.GetCollection("counters");
         FindAndModifyArgs args = new FindAndModifyArgs();
         args.Query = Query.EQ("_id", SequenceName);
         args.Update = MongoDB.Driver.Builders.Update.Inc("seq", 1);
         FindAndModifyResult result = sequenceCollection.FindAndModify(args);
         return result.ModifiedDocument.GetElement("seq").Value.ToInt64();
     }
     catch
     {
         dynamic bs = new DynamicObj();
         bs._id = SequenceName;
         bs.seq = 2;
         Insert("counters", bs);
         return 1;
     }
 }
        public void TestFindAndModifyUpsert()
        {
            _collection.RemoveAll();

            var args = new FindAndModifyArgs
            {
                Query = Query.EQ("name", "Tom"),
                Update = Update.Inc("count", 1),
                Upsert = true,
                VersionReturned = FindAndModifyDocumentVersion.Modified
            };
            var result = _collection.FindAndModify(args);

            Assert.AreEqual("Tom", result.ModifiedDocument["name"].AsString);
            Assert.AreEqual(1, result.ModifiedDocument["count"].AsInt32);
        }
 public void TestFindAndModifyWithMaxTime()
 {
     if (_primary.Supports(FeatureId.MaxTime))
     {
         using (var failpoint = new FailPoint(FailPointName.MaxTimeAlwaysTimeout, _server, _primary))
         {
             if (failpoint.IsSupported())
             {
                 failpoint.SetAlwaysOn();
                 var args = new FindAndModifyArgs
                 {
                     Update = Update.Set("x", 1),
                     MaxTime = TimeSpan.FromMilliseconds(1)
                 };
                 Assert.Throws<ExecutionTimeoutException>(() => _collection.FindAndModify(args));
             }
         }
     }
 }
Exemple #10
0
 public object FindAndModifyAs(Type documentType, IMongoQuery query, IMongoSortBy sortBy, IMongoUpdate update, IMongoFields fields, bool returnNew, bool upsert, out UpdateResult result)
 {
     var args = new FindAndModifyArgs();
     args.Query = query;
     args.SortBy = sortBy;
     args.Update = update;
     args.Fields = fields;
     args.Upsert = upsert;
     args.VersionReturned = returnNew ? FindAndModifyDocumentVersion.Modified : FindAndModifyDocumentVersion.Original;
     var r = _this.FindAndModify(args);
     result = new FindAndModifyUpdateResult(r);
     return r.GetModifiedDocumentAs(documentType);
 }
Exemple #11
0
 internal static dynamic MakeTransacton(dynamic master_trans, dynamic cfg)
 {
     try
     {
         for (int i = 0; i < cfg.transactions.Length; i++)
         {
             dynamic trans = cfg.transactions[i];
             trans._id = master_trans._id + "." + i.ToString().PadLeft(2, '0');
             trans.account = String.Format(trans.account, master_trans.accounts);
             trans.finance_amount = (trans.amount_type == "F") ? (long)trans.amount : (long)Math.Round((decimal)(trans.amount * master_trans.amount / 100));
             MongoCollection accounts = DataHelper._database.GetCollection("finance_account");
             FindAndModifyArgs args = new FindAndModifyArgs();
             if (trans.type == "debit")
             {
                 args.Query = Query.And(
                     Query.EQ("_id", trans.account),
                     Query.GTE("balance", trans.finance_amount));
                 args.Update = Update.Inc("balance", -trans.finance_amount).Inc("debit", trans.finance_amount);
             }
             else
             {
                 args.Query =
                     Query.EQ("_id", trans.account);
                 args.Update = Update.Inc("balance", trans.finance_amount).Inc("credit", trans.finance_amount);
             }
             FindAndModifyResult result = accounts.FindAndModify(args);
             if (!result.Ok)
             {
                 trans.status = "ERROR";
                 DataHelper.Save("finance_transaction_detail", trans);
                 master_trans.status = "ERROR";
                 return master_trans;
             }
             else
             {
                 trans.status = "DONE";
                 DataHelper.Save("finance_transaction_detail", trans);
             }
         }
         master_trans.status = "DONE";
     }
     catch
     {
         master_trans.status = "ERROR";
     }
     return master_trans;
 }
        private FindAndModifyResult FindAndModifyResult(string ObjName)
        {

            var args = new FindAndModifyArgs()
            {
                Query = Query.EQ("document", ObjName),
                SortBy = null,
                Update = Update.Inc("last", (long)1),
                VersionReturned = FindAndModifyDocumentVersion.Modified,
                Upsert = true
            };
            
            FindAndModifyResult result =MongoMapperHelper.Db("Counters", true).GetCollection("Counters").FindAndModify(args);
            return result;
        }
        /// <summary>
        /// Get a non running message from queue
        /// </summary>
        /// <param name="query">query where top level fields do not contain operators. Lower level fields can however. eg: valid {a: {$gt: 1}, "b.c": 3}, invalid {$and: [{...}, {...}]}</param>
        /// <param name="resetRunning">duration before this message is considered abandoned and will be given with another call to Get()</param>
        /// <param name="wait">duration to keep polling before returning null</param>
        /// <param name="poll">duration between poll attempts</param>
        /// <param name="approximateWait">whether to fluctuate the wait time randomly by +-10 percent. This ensures Get() calls seperate in time when multiple Queues are used in loops started at the same time</param>
        /// <returns>message or null</returns>
        /// <exception cref="ArgumentNullException">query is null</exception>
        public Message Get(QueryDocument query, TimeSpan resetRunning, TimeSpan wait, TimeSpan poll, bool approximateWait)
        {
            if (query == null)
                throw new ArgumentNullException ("query");

            //reset stuck messages
            collection.Update(
                new QueryDocument { { "running", true }, { "resetTimestamp", new BsonDocument("$lte", DateTime.UtcNow) } },
                new UpdateDocument("$set", new BsonDocument("running", false)),
                UpdateFlags.Multi
            );

            var builtQuery = new QueryDocument("running", false);
            foreach (var field in query)
                builtQuery.Add("payload." + field.Name, field.Value);

            builtQuery.Add("earliestGet", new BsonDocument("$lte", DateTime.UtcNow));

            var resetTimestamp = DateTime.UtcNow;
            try
            {
                resetTimestamp += resetRunning;
            }
            catch (ArgumentOutOfRangeException)
            {
                resetTimestamp = resetRunning > TimeSpan.Zero ? DateTime.MaxValue : DateTime.MinValue;
            }

            var sort = new SortByDocument { { "priority", 1 }, { "created", 1 } };
            var update = new UpdateDocument("$set", new BsonDocument { { "running", true }, { "resetTimestamp", resetTimestamp } });
            var fields = new FieldsDocument { { "payload", 1 }, { "streams", 1 } };

            var end = DateTime.UtcNow;
            try
            {
                if (approximateWait)
                    //fluctuate randomly by 10 percent
                    wait += TimeSpan.FromMilliseconds(wait.TotalMilliseconds * GetRandomDouble(-0.1, 0.1));

                end += wait;
            }
            catch (Exception e)
            {
                if (!(e is OverflowException) && !(e is ArgumentOutOfRangeException))
                    throw e;//cant cover

                end = wait > TimeSpan.Zero ? DateTime.MaxValue : DateTime.MinValue;
            }

            while (true)
            {
                var findModifyArgs = new FindAndModifyArgs { Query = builtQuery, SortBy = sort, Update = update, Fields = fields, Upsert = false };

                var message = collection.FindAndModify(findModifyArgs).ModifiedDocument;
                if (message != null)
                {
                    var handleStreams = new List<KeyValuePair<BsonValue, Stream>>();
                    var messageStreams = new Dictionary<string, Stream>();
                    foreach (var streamId in message["streams"].AsBsonArray)
                    {
                        var fileInfo = gridfs.FindOneById(streamId);

                        var stream = fileInfo.OpenRead();

                        handleStreams.Add(new KeyValuePair<BsonValue, Stream>(streamId, stream));
                        messageStreams.Add(fileInfo.Name, stream);
                    }

                    var handle = new Handle(message["_id"].AsObjectId, handleStreams);
                    return new Message(handle, message["payload"].AsBsonDocument, messageStreams);
                }

                if (DateTime.UtcNow >= end)
                    return null;

                try
                {
                    Thread.Sleep(poll);
                }
                catch (ArgumentOutOfRangeException)
                {
                    if (poll < TimeSpan.Zero)
                        poll = TimeSpan.Zero;
                    else
                        poll = TimeSpan.FromMilliseconds(int.MaxValue);

                    Thread.Sleep(poll);
                }

                if (DateTime.UtcNow >= end)
                    return null;
            }
        }
        public async void FindAndModifyTest2()
        {
            string entryMessage1 = "entry 1";
            AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);

            List<Entry> results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(entryMessage1, results[0].Message);

            var searchQuery = Query.EQ("Message", entryMessage1);

            var update = Update.Set("Message", MONGO_EDITED_TEXT);
            var sortBy = SortBy.Descending("TimeStamp");

            FindAndModifyArgs findAndModifyArgs = new FindAndModifyArgs();
            findAndModifyArgs.Query = searchQuery;
            findAndModifyArgs.SortBy = sortBy;
            findAndModifyArgs.Update = update;
            findAndModifyArgs.Upsert = false;

            FindAndModifyResult findAndModifyResult = await _asyncUpdaterT.FindAndModifyAsync(MONGO_COLLECTION_1_NAME, findAndModifyArgs);

            Assert.IsTrue(findAndModifyResult.Ok);
            Assert.IsNull(findAndModifyResult.ErrorMessage);
            Assert.IsNotNull(findAndModifyResult.ModifiedDocument);

            findAndModifyArgs = new FindAndModifyArgs();
            findAndModifyArgs.Query = searchQuery;
            findAndModifyArgs.SortBy = sortBy;
            findAndModifyArgs.Update = update;
            findAndModifyArgs.Upsert = false;

            findAndModifyResult = await _asyncUpdaterT.FindAndModifyAsync(MONGO_COLLECTION_1_NAME, findAndModifyArgs);

            Assert.IsTrue(findAndModifyResult.Ok);
            Assert.IsNull(findAndModifyResult.ErrorMessage);
            Assert.IsNull(findAndModifyResult.ModifiedDocument);

            results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(MONGO_EDITED_TEXT, results[0].Message);/*This field we modified via FindAndModify...*/
        }
        public void TestFindAndModifyReplaceWithWriteConcernError()
        {
            RequireServer.Where(clusterTypes: ClusterTypes.ReplicaSet);
            _collection.RemoveAll();
            _collection.Insert(new BsonDocument { { "_id", 1 }, { "x", 1 } });
            var collectionSettings = new MongoCollectionSettings
            {
                WriteConcern = new WriteConcern(9)
            };
            var collection = _database.GetCollection(_collection.Name, collectionSettings);
            var args = new FindAndModifyArgs
            {
                Query = Query.EQ("_id", 1),
                Update = Update.Replace(new BsonDocument { { "_id", 1 }, { "x", 2 } }),
                VersionReturned = FindAndModifyDocumentVersion.Modified
            };

            BsonDocument modifiedDocument;
            if (_server.BuildInfo.Version >= new Version(3, 2, 0))
            {
                Action action = () => collection.FindAndModify(args);

                var exception = action.ShouldThrow<MongoWriteConcernException>().Which;
                var commandResult = exception.Result;
                modifiedDocument = commandResult["value"].AsBsonDocument;
            }
            else
            {
                var result = collection.FindAndModify(args);

                modifiedDocument = result.ModifiedDocument;
            }

            modifiedDocument.Should().Be("{ _id : 1, x : 2 }");
        }
        public async void FindAndModifyTest3()
        {
            string entryMessage1 = "entry 1";
            AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);

            List<Entry> results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(entryMessage1, results[0].Message);

            var searchQuery = Query.EQ("Message", "some message that won't be found by the query");

            var update = Update.Set("Message", MONGO_EDITED_TEXT);
            var sortBy = SortBy.Descending("TimeStamp");

            FindAndModifyArgs findAndModifyArgs = new FindAndModifyArgs();
            findAndModifyArgs.Query = searchQuery;
            findAndModifyArgs.SortBy = sortBy;
            findAndModifyArgs.Update = update;
            findAndModifyArgs.Upsert = true;
            findAndModifyArgs.VersionReturned = FindAndModifyDocumentVersion.Modified;

            FindAndModifyResult findAndModifyResult = await _asyncUpdaterT.FindAndModifyAsync(MONGO_COLLECTION_1_NAME, findAndModifyArgs);

            Assert.IsTrue(findAndModifyResult.Ok);
            Assert.IsNull(findAndModifyResult.ErrorMessage);
            Assert.IsNotNull(findAndModifyResult.ModifiedDocument); /* This should be populated as per the last argument to FindAndModify...*/

            findAndModifyArgs = new FindAndModifyArgs();
            findAndModifyArgs.Query = searchQuery;
            findAndModifyArgs.SortBy = sortBy;
            findAndModifyArgs.Update = update;
            findAndModifyArgs.Upsert = false;

            findAndModifyResult = await _asyncUpdaterT.FindAndModifyAsync(MONGO_COLLECTION_1_NAME, findAndModifyArgs);

            Assert.IsTrue(findAndModifyResult.Ok);
            Assert.IsNull(findAndModifyResult.ErrorMessage);
            Assert.IsNull(findAndModifyResult.ModifiedDocument); /*This should be populated as per the last argument to FindAndModify...*/

            results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(entryMessage1, results[0].Message);
        }
 private Counters IncCounter(string counterName)
 {
     var CountersCollection = mongoDatabase.GetCollection<Counters>(Counters_Col);
     var args = new FindAndModifyArgs() { Query = Query.Null, SortBy = SortBy.Null, Update = Update.Inc(counterName, 1), Upsert = true };
     FindAndModifyResult counterIncResult = CountersCollection.FindAndModify(args);
     Counters updatedCounters = counterIncResult.GetModifiedDocumentAs<Counters>();
     return updatedCounters;
 }
        public void TestFindAndModify()
        {
            _collection.RemoveAll();
            _collection.Insert(new BsonDocument { { "_id", 1 }, { "priority", 1 }, { "inprogress", false }, { "name", "abc" } });
            _collection.Insert(new BsonDocument { { "_id", 2 }, { "priority", 2 }, { "inprogress", false }, { "name", "def" } });


            var started = DateTime.UtcNow;
            started = started.AddTicks(-(started.Ticks % 10000)); // adjust for MongoDB DateTime precision
            var args = new FindAndModifyArgs
            {
                Query = Query.EQ("inprogress", false),
                SortBy = SortBy.Descending("priority"),
                Update = Update.Set("inprogress", true).Set("started", started),
                VersionReturned = FindAndModifyDocumentVersion.Original
            };
            var result = _collection.FindAndModify(args);

            Assert.IsTrue(result.Ok);
            Assert.AreEqual(2, result.ModifiedDocument["_id"].AsInt32);
            Assert.AreEqual(2, result.ModifiedDocument["priority"].AsInt32);
            Assert.AreEqual(false, result.ModifiedDocument["inprogress"].AsBoolean);
            Assert.AreEqual("def", result.ModifiedDocument["name"].AsString);
            Assert.IsFalse(result.ModifiedDocument.Contains("started"));

            started = DateTime.UtcNow;
            started = started.AddTicks(-(started.Ticks % 10000)); // adjust for MongoDB DateTime precision
            args = new FindAndModifyArgs
            {
                Query = Query.EQ("inprogress", false),
                SortBy = SortBy.Descending("priority"),
                Update = Update.Set("inprogress", true).Set("started", started),
                VersionReturned = FindAndModifyDocumentVersion.Modified
            };
            result = _collection.FindAndModify(args);

            Assert.IsTrue(result.Ok);
            Assert.AreEqual(1, result.ModifiedDocument["_id"].AsInt32);
            Assert.AreEqual(1, result.ModifiedDocument["priority"].AsInt32);
            Assert.AreEqual(true, result.ModifiedDocument["inprogress"].AsBoolean);
            Assert.AreEqual("abc", result.ModifiedDocument["name"].AsString);
            Assert.AreEqual(started, result.ModifiedDocument["started"].ToUniversalTime());
        }
        public async void FindAndModifyAsyncTest4()
        {
            string entryMessage1 = "entry 1";
            AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);

            List<Entry> results = new List<Entry>(_collectionReaderT.Read("TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(entryMessage1, results[0].Message);

            var searchQuery = Query.EQ("Message", entryMessage1);

            var update = Update.Set("Message", MONGO_EDITED_TEXT);
            var sortBy = SortBy.Descending("TimeStamp");
            IMongoFields fields = Fields.Include("TimeStamp");

            FindAndModifyArgs findAndModifyArgs = new FindAndModifyArgs();
            findAndModifyArgs.Query = searchQuery;
            findAndModifyArgs.SortBy = sortBy;
            findAndModifyArgs.Update = update;
            findAndModifyArgs.Fields = fields;
            findAndModifyArgs.Upsert = true;
            findAndModifyArgs.VersionReturned = FindAndModifyDocumentVersion.Modified;

            FindAndModifyResult result = await _collectionUpdaterT.FindAndModifyAsync(findAndModifyArgs);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Ok);
            Assert.IsNotNull(result.ModifiedDocument);
            Assert.IsNull(result.ErrorMessage);

            results = new List<Entry>(_collectionReaderT.Read("TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(MONGO_EDITED_TEXT, results[0].Message);/*This field we modified via FindAndModify...*/
        }
        public void TestFindAndModifyNoMatchingDocument()
        {
            _collection.RemoveAll();

            var started = DateTime.UtcNow;
            started = started.AddTicks(-(started.Ticks % 10000)); // adjust for MongoDB DateTime precision
            var args = new FindAndModifyArgs
            {
                Query = Query.EQ("inprogress", false),
                SortBy = SortBy.Descending("priority"),
                Update = Update.Set("inprogress", true).Set("started", started),
                VersionReturned = FindAndModifyDocumentVersion.Original
            };
            var result = _collection.FindAndModify(args);

            Assert.IsTrue(result.Ok);
            Assert.IsNull(result.ErrorMessage);
            Assert.IsNull(result.ModifiedDocument);
            Assert.IsNull(result.GetModifiedDocumentAs<FindAndModifyClass>());
        }
        public void TestFindAndModifyUpdateWithWriteConcernError()
        {
            _collection.RemoveAll();
            _collection.Insert(new BsonDocument { { "_id", 1 }, { "x", 1 } });
            var collectionSettings = new MongoCollectionSettings
            {
                WriteConcern = new WriteConcern(9)
            };
            var collection = _database.GetCollection(_collection.Name, collectionSettings);
            var args = new FindAndModifyArgs
            {
                Query = Query.EQ("x", 1),
                Update = Update.Set("x", 2),
                VersionReturned = FindAndModifyDocumentVersion.Modified
            };

            Action action = () => collection.FindAndModify(args);

            var exception = action.ShouldThrow<MongoWriteConcernException>().Which;
            var commandResult = exception.Result;
            var result = commandResult["value"].AsBsonDocument;
            result.Should().Be("{ _id : 1, x : 2 }");
        }
        public void TestFindAndModifyTyped()
        {
            _collection.RemoveAll();
            var obj = new FindAndModifyClass { Id = ObjectId.GenerateNewId(), Value = 1 };
            _collection.Insert(obj);

            var args = new FindAndModifyArgs
            {
                Query = Query.EQ("_id", obj.Id),
                Update = Update.Inc("Value", 1),
                VersionReturned = FindAndModifyDocumentVersion.Modified
            };
            var result = _collection.FindAndModify(args);
            var rehydrated = result.GetModifiedDocumentAs<FindAndModifyClass>();

            Assert.AreEqual(obj.Id, rehydrated.Id);
            Assert.AreEqual(2, rehydrated.Value);
        }
        /// <summary>
        /// Initializes the Organisation URIs that don't already exist.
        /// </summary>
        /// <param name="uris">The URIs to add to the organisation collection.</param>
        private void InitUris(Dictionary<SystemUriType, string> uris)
        {
            if (uris.Count == 0)
            {
                return;
            }

            this.installLogger.Log(Messages.DB_InitUris);
            MongoCollection<BsonDocument> collection = this.Database.GetCollection(iApplyDb.SystemSettings._COLLECTION_NAME);

            if (collection.Count() == 0)
            {
                throw new NullReferenceException();
            }

            UpdateBuilder builder = new UpdateBuilder();
            foreach (KeyValuePair<SystemUriType, string> uri in uris)
            {
                string name = string.Format("{0}.{1}", iApplyDb.SystemSettings.URIS, uri.Key);
                builder.Set(name, new BsonString(uri.Value));
            }

            FindAndModifyArgs args = new FindAndModifyArgs
                                     {
                                         Update = builder
                                     };

            collection.FindAndModify(args);
            this.installLogger.LogSuccess(Messages.MAIN_StepComplete);
        }