示例#1
0
        /// <summary>
        /// Returns the role by their role id
        /// </summary>
        /// <param name="roleId">The id of the role to retrieve</param>
        /// <returns>the role found or null</returns>
        public bool DeleteCart(ObjectId id, string clientIP)
        {
            var db = (from c in Carts.AsQueryable() where c.ClientIP == clientIP select c).First();
            FindAndModifyResult spotResult = Carts.FindAndRemove(Query.EQ("_id", db.CartID), SortBy.Ascending("_id"));

            return(spotResult.Ok);
        }
示例#2
0
        public async void FindAndModifyAsyncTest1()
        {
            string entryMessage1 = "entry 1";

            AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);

            List <Entry> results = new List <Entry>(_reader.Read <Entry>(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;

            FindAndModifyResult result = await _databaseUpdater.FindAndModifyAsync <Entry>(MONGO_COLLECTION_1_NAME, findAndModifyArgs);

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

            results = new List <Entry>(_reader.Read <Entry>(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...*/
        }
示例#3
0
        // <summary>
        /// Deletes the spot with the specified id
        /// </summary>
        /// <param name="spotId">Id of the spot to delete</param>
        /// <returns>Result of the operation, true if was ok</returns>
        public bool Delete(ObjectId id)
        {
            Spot spot = Spots.FindOneById(id);
            FindAndModifyResult spotResult = Spots.FindAndRemove(Query.EQ("_id", id), SortBy.Ascending("_id"));

            return(spotResult.Ok);
        }
示例#4
0
        // <summary>
        /// Deletes the role with the specified id
        /// </summary>
        /// <param name="roleId">Id of the role to delete</param>
        /// <returns>Result of the operation, true if was ok</returns>
        public bool Delete(ObjectId id)
        {
            Parcel parcel = Parcels.FindOneById(id);
            FindAndModifyResult parcelResult = Parcels.FindAndRemove(Query.EQ("_id", id), SortBy.Ascending("_id"));

            return(parcelResult.Ok);
        }
示例#5
0
        public async void FindAndRemoveAsyncTest()
        {
            string entryMessage1 = "entry 1";

            AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);

            List <Entry> results = new List <Entry>(_reader.Read <Entry>(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.Null;
            FindAndRemoveArgs findAndRemoveArgs = new FindAndRemoveArgs();

            findAndRemoveArgs.Query  = searchQuery;
            findAndRemoveArgs.SortBy = sortBy;

            FindAndModifyResult result = await _databaseUpdater.FindAndRemoveAsync <Entry>(MONGO_COLLECTION_1_NAME, findAndRemoveArgs);

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

            results = new List <Entry>(_reader.Read <Entry>(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(0, results.Count());/*we deleted the entry via FindAndRemove...*/
        }
示例#6
0
        public bool Delete(ObjectId id)
        {
            Phase phase = Phases.FindOneById(id);

            FindAndModifyResult phaseResult = Phases.FindAndRemove(Query.EQ("_id", id), SortBy.Ascending("_id"));

            return(phaseResult.Ok);
        }
示例#7
0
        // <summary>
        /// Deletes the role with the specified id
        /// </summary>
        /// <param name="roleId">Id of the role to delete</param>
        /// <returns>Result of the operation, true if was ok</returns>
        public bool Delete(ObjectId roleId)
        {
            Role role = Roles.FindOneById(roleId);

            FindAndModifyResult userRoleResult = UserRoles.FindAndRemove(Query.EQ("Role", role.Name), SortBy.Ascending("_id"));
            FindAndModifyResult roleResult     = Roles.FindAndRemove(Query.EQ("_id", roleId), SortBy.Ascending("_id"));

            return(roleResult.Ok && userRoleResult.Ok);
        }
示例#8
0
        /// <summary>
        /// Deletes the user with the specified id
        /// </summary>
        /// <param name="userId">User to be deleted id</param>
        /// <returns>Result of the operation, true if was ok</returns>
        public bool Delete(ObjectId userId)
        {
            User user = Users.FindOneById(userId);

            FindAndModifyResult userRoleResult = UserRoles.FindAndRemove(Query.EQ("Username", user.Username), SortBy.Ascending("_id"));
            FindAndModifyResult result         = Users.FindAndRemove(Query.EQ("_id", userId), SortBy.Ascending("_id"));

            return(result.Ok && userRoleResult.Ok);
        }
示例#9
0
        public bool UpdateSubsription(Subscription subscription)
        {
            var query  = Query.And(Query.EQ("Email", subscription.EmailId));
            var update = MongoDB.Driver.Builders.Update.Set("Allow", subscription.Allow);
            var sortBy = SortBy.Descending("Email");
            FindAndModifyResult result = emailCollection.FindAndModify(query, sortBy, update, true);

            return(result.Ok);
        }
示例#10
0
        public bool Update(Metric2 Metric)
        {
            var query  = Query.And(Query.EQ("Name", Metric.Name), Query.EQ("Identifier", Metric.Identifier));
            var update = MongoDB.Driver.Builders.Update.Inc("Count", 1).Inc("Total", Metric.Total);
            var sortBy = SortBy.Descending("Name");
            FindAndModifyResult result = collection2.FindAndModify(query, sortBy, update, true);

            return(result.Ok);
        }
        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();
                }
            }
        }
        private Counters IncCounter(string counterName)
        {
            var CountersCollection = mongoDatabase.GetCollection <Counters>(Counters_Col);
            var incId = Update.Inc(counterName, 1);
            var query = Query.Null;
            FindAndModifyResult counterIncResult = CountersCollection.FindAndModify(query, SortBy.Null, incId, true);
            Counters            updatedCounters  = counterIncResult.GetModifiedDocumentAs <Counters>();

            return(updatedCounters);
        }
        public TimeoutsBatch GetTimeoutsBatch()
        {
            var retval = new TimeoutsBatch {
                DueTimeouts = new List <TimeoutData>()
            };

            MongoCollection <TimeoutData> collection = _mongoDatabase.GetCollection <TimeoutData>(TimeoutsCollectionName);

            DateTime utcNow = DateTime.UtcNow;

            // Find all the due timeouts and put a lock on each one to prevent multiple threads/processes getting hold of the same data.
            bool doQuery = true;

            while (doQuery)
            {
                var args = new FindAndModifyArgs
                {
                    Query           = Query.And(Query.EQ("Locked", false), Query.LTE("Time", utcNow)),
                    Update          = Update <TimeoutData> .Set(c => c.Locked, true),
                    Upsert          = false,
                    VersionReturned = FindAndModifyDocumentVersion.Original
                };
                FindAndModifyResult result = collection.FindAndModify(args);

                if (result.ModifiedDocument == null)
                {
                    doQuery = false;
                }
                else
                {
                    retval.DueTimeouts.Add(result.GetModifiedDocumentAs <TimeoutData>());
                }
            }

            // Get next query time
            var nextQueryTime       = DateTime.MaxValue;
            var upcomingTimeoutsRes = collection.Find(Query.GT("Time", utcNow));

            foreach (TimeoutData upcomingTimeout in upcomingTimeoutsRes)
            {
                if (upcomingTimeout.Time < nextQueryTime)
                {
                    nextQueryTime = upcomingTimeout.Time;
                }
            }

            if (nextQueryTime == DateTime.MaxValue)
            {
                nextQueryTime = utcNow.AddMinutes(1);
            }

            retval.NextQueryTime = nextQueryTime;

            return(retval);
        }
        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);
        }
示例#15
0
文件: MongoLog.cs 项目: 24/source_04
 public void LogResult(FindAndModifyResult result)
 {
     if (_writeToFile == null)
     {
         return;
     }
     _writeToFile.Write(" result {0}", result.Ok ? "ok" : "");
     if (result.ErrorMessage != null)
     {
         _writeToFile.Write(" error \"{0}\"", result.ErrorMessage);
     }
     _writeToFile.WriteLine();
     _writeToFile.WriteLine("document");
     _writeToFile.WriteLine(result.ModifiedDocument.zToJson());
 }
示例#16
0
        private static MongoCollection <BsonDocument> UpdateCapital(MongoDatabase mongoDatabase, string oldName, string newName)
        {
            MongoCollection <BsonDocument> capitals = mongoDatabase.GetCollection <BsonDocument>("Capital");
            FindAndModifyArgs args = new FindAndModifyArgs()
            {
                Query           = Query.EQ("State", oldName),
                Update          = Update.Set("State", newName),
                Upsert          = false,
                SortBy          = null,
                VersionReturned = FindAndModifyDocumentVersion.Original,
            };
            FindAndModifyResult res = capitals.FindAndModify(args);

            return(capitals);
        }
        public async void FindAndModifyAsyncTest3()
        {
            string entryMessage1 = "entry 1";

            AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);

            List <Entry> results = new List <Entry>(_collectionReader.Read <Entry>("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 result = await _collectionUpdater.FindAndModifyAsync <Entry>(findAndModifyArgs);

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

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

            result = await _collectionUpdater.FindAndModifyAsync <Entry>(findAndModifyArgs);

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

            results = new List <Entry>(_collectionReader.Read <Entry>("TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(entryMessage1, results[0].Message);
        }
示例#18
0
        public long Next()
        {
            var query  = Query.EQ("_id", BsonValue.Create(CounterName));
            var sort   = SortBy.Ascending("_id");
            var update = MDBUpdate.Inc("Count", 1);
            FindAndModifyResult result = Collection.FindAndModify(query, sort, update, true);

            if (result.ModifiedDocument == null)
            {
                AddInitialEntry();
                result = Collection.FindAndModify(query, sort, update, true);
            }
            if (result.ModifiedDocument == null)
            {
                throw new InvalidOperationException(string.Format("Failed to update counter '{0}'.", CounterName));
            }
            return(result.ModifiedDocument.GetValue("Count").ToInt64());
        }
示例#19
0
        public string Next(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 = document[Field.COUNTERVALUE].AsInt32.ToString();

            return(value);
        }
示例#20
0
        public override BsonValue GetNewId()
        {
            MongoCollection collection = GetCollection();
            // on utilise FindAndModify pour
            FindAndModifyResult result = collection.zFindAndModify(new QueryDocument {
                { "_id", 0 }
            }, new UpdateDocument {
                { "$inc", new BsonDocument {
                      { "LastId", 1 }
                  } }
            }, upsert: true);
            // ATTENTION result.ModifiedDocument est le document avant update donc il faut faire + 1
            // si result.ModifiedDocument est null le document _id 0 n'existait pas, il est créé (upsert: true) après update on a { _id: 0, LastId: 1 }
            int id = 1;

            if (result.ModifiedDocument != null)
            {
                id = result.ModifiedDocument["LastId"].AsInt32 + 1;
            }
            return(BsonValue.Create(id));
        }
示例#21
0
        public MongoPersistenceEngine(MongoDatabase store, IDocumentSerializer serializer)
        {
            if (store == null)
            {
                throw new ArgumentNullException("store");
            }

            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }

            _store      = store;
            _serializer = serializer;

            _commitSettings = new MongoCollectionSettings {
                AssignIdOnInsert = false, WriteConcern = WriteConcern.Acknowledged
            };

            _snapshotSettings = new MongoCollectionSettings {
                AssignIdOnInsert = false, WriteConcern = WriteConcern.Unacknowledged
            };

            _streamSettings = new MongoCollectionSettings {
                AssignIdOnInsert = false, WriteConcern = WriteConcern.Unacknowledged
            };

            _countersSettings = new MongoCollectionSettings {
                AssignIdOnInsert = false, WriteConcern = WriteConcern.Acknowledged
            };

            _getNextCheckpointNumber = () => TryMongo(() =>
            {
                IMongoQuery query          = Query.And(Query.EQ("_id", "CheckpointNumber"));
                IMongoUpdate update        = Update.Inc("seq", 1);
                FindAndModifyResult result = Counters.FindAndModify(query, null, update, true);
                return(result.ModifiedDocument["seq"].ToInt32());
            });
        }
        protected void CallbackFindAndModify(IAsyncResult asyncRes)
        {
            FindAndModifyResult result    = null;
            Exception           exception = null;

            try
            {
                try
                {
                    AsyncResult ares = (AsyncResult)asyncRes;
                    var         delg = (dynamic)ares.AsyncDelegate;
                    result = delg.EndInvoke(asyncRes);
                }
                catch (Exception ex)
                {
                    // if an exception is caught here the dynamic binding of the "result" variable is unresolved thus causing a
                    // RuntimeTypeBindingException to be raised. The problem is that in this scenario - complicated to determine which
                    // sort of action originally invoked the async call -- making notification of the error problematic...
                    exception = ex;
                }
                finally
                {
                    if (AsyncFindAndModifyCompleted != null)
                    {
                        AsyncFindAndModifyCompleted(result);
                    }
                }
            }
            catch (RuntimeBinderException ex)
            {
                // TODO: add ex handling!
                if (AsyncFindAndModifyCompleted != null)
                {
                    AsyncFindAndModifyCompleted(result);
                }
            }
        }
示例#23
0
        public void UpdateJobByIDAndRemove()
        {
            string   dt  = DateTime.Now.ToString();
            ObjectId oid = ObjectId.GenerateNewId();

            Job job = new Job
            {
                _id = oid
                ,
                ScriptFileName = "scriptname.bteq"
                ,
                ProjectName = "TestRun"
                ,
                LastModified = DateTime.Now.AddHours(-1).ToString()
            };

            MongoDatabase         localDB = MongoSrvr.GetDatabase("PMG");
            MongoCollection <Job> jobCol  = localDB.GetCollection <Job>("Test");
            WriteConcernResult    res     = jobCol.Insert <Job>(job);

            Assert.IsTrue(res.Ok);

            IMongoQuery  query  = Query.EQ("_id", oid);
            IMongoSortBy sortBy = SortBy.Null;
            IMongoUpdate update = Update.Set("LastModified", dt);

            MongoCollection     jobsColl = localDB.GetCollection("Test");
            FindAndModifyResult result   = jobsColl.FindAndModify(query, sortBy, update, true);
            Job modJob = result.GetModifiedDocumentAs <Job>();

            Assert.AreEqual(modJob.LastModified, dt);

            //cleanup
            res = jobCol.Remove(Query.EQ("_id", oid), RemoveFlags.Single, WriteConcern.Acknowledged);
            Assert.IsTrue(res.Ok);
        }
示例#24
0
 protected void _updaterAsyncT_AsyncFindAndModifyCompleted(FindAndModifyResult result)
 {
     _findAndModifyResult = result;
     _updaterAutoResetEvent.Set();
 }
示例#25
0
        public static string UpdateOneProduct(string oldProduct, string newProduct, string option)
        {
            string connectstring1 = "mongodb://*****:*****@ds149433.mlab.com:49433/corevisesdb";

            MongoClient client = new MongoClient(connectstring1);
            MongoServer ms     = client.GetServer();

            MongoDatabase     db         = ms.GetDatabase("corevisesdb");
            var               collection = db.GetCollection <product>("producto");
            FindAndModifyArgs args;
            string            result = "Hubo un error al actualizar el producto";

            switch (option)
            {
            case "name":
                args = new FindAndModifyArgs()
                {
                    Query  = Query.EQ("code", oldProduct),
                    Update = Update.Set("name", newProduct),

                    Upsert          = false,
                    SortBy          = null,
                    VersionReturned = FindAndModifyDocumentVersion.Original,
                };
                FindAndModifyResult res = collection.FindAndModify(args);
                result = "el nombre se actualizo";
                break;

            case "img":

                args = new FindAndModifyArgs()
                {
                    Query  = Query.EQ("code", oldProduct),
                    Update = Update.Set("img", newProduct),

                    Upsert          = false,
                    SortBy          = null,
                    VersionReturned = FindAndModifyDocumentVersion.Original,
                };
                result = "la imagen se actualizo";

                break;

            case "price":

                args = new FindAndModifyArgs()
                {
                    Query  = Query.EQ("code", oldProduct),
                    Update = Update.Set("price", newProduct),

                    Upsert          = false,
                    SortBy          = null,
                    VersionReturned = FindAndModifyDocumentVersion.Original,
                };
                result = "el precio se actualizo";

                break;

            case "stock":

                args = new FindAndModifyArgs()
                {
                    Query  = Query.EQ("code", oldProduct),
                    Update = Update.Set("stock", newProduct),

                    Upsert          = false,
                    SortBy          = null,
                    VersionReturned = FindAndModifyDocumentVersion.Original,
                };
                result = "stock se actualizo";

                break;

            default:
                Console.WriteLine("Default case");
                break;
            }



            //obtenemos la coleccion en la que vamos a almacenar el objeto

            return(result);
        }
示例#26
0
 public FindAndModifyUpdateResult(FindAndModifyResult result)
 {
     Result = result;
 }
示例#27
0
        /// <summary>
        /// Find existing instance of ProcessManager
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="mapper"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public IPersistanceData <T> FindData <T>(IProcessManagerPropertyMapper mapper, Message message) where T : class, IProcessManagerData
        {
            if (message is StartProcessManagerMessage)
            {
                return(null);
            }

            var mapping = mapper.Mappings.FirstOrDefault(m => m.MessageType == message.GetType()) ??
                          mapper.Mappings.First(m => m.MessageType == typeof(Message));

            var collectionName             = typeof(T).Name;
            MongoCollection <T> collection = _mongoDatabase.GetCollection <T>(collectionName);

            object msgPropValue = mapping.MessageProp.Invoke(message);

            if (null == msgPropValue)
            {
                throw new ArgumentException("Message property expression evaluates to null");
            }

            //Left
            ParameterExpression pe   = Expression.Parameter(typeof(MyMongoData <T>), "t");
            Expression          left = Expression.Property(pe, typeof(MyMongoData <T>).GetTypeInfo().GetProperty("Data"));

            foreach (var prop in mapping.PropertiesHierarchy.Reverse())
            {
                left = Expression.Property(left, left.Type, prop.Key);
            }

            //Right
            Expression right = Expression.Constant(msgPropValue, msgPropValue.GetType());

            Expression expression;

            try
            {
                expression = Expression.Equal(left, right);
            }
            catch (InvalidOperationException ex)
            {
                throw new Exception("Mapped incompatible types of ProcessManager Data and Message properties.", ex);
            }

            var         lambda = Expression.Lambda <Func <MyMongoData <T>, bool> >(expression, pe);
            IMongoQuery query  = Query <MyMongoData <T> > .Where(lambda);


            // check if data is locked
            FindAndModifyResult result = collection.FindAndModify(new FindAndModifyArgs
            {
                Query = Query.And(
                    Query.Or(
                        Query.EQ("Locked", false),
                        Query.LTE("LockTimeout", DateTime.UtcNow)
                        ),
                    query
                    ),
                Update = Update.Combine(
                    Update.Set("Locked", true),
                    Update.Set("LockTimeout", DateTime.UtcNow.AddSeconds(30))
                    )
            });

            if (result.ModifiedDocument == null)
            {
                // spin until lock is released
                while (true)
                {
                    result = collection.FindAndModify(new FindAndModifyArgs
                    {
                        Query = Query.And(
                            Query.Or(
                                Query.EQ("Locked", false),
                                Query.LTE("LockTimeout", DateTime.UtcNow)
                                ),
                            query
                            ),
                        Update = Update.Combine(
                            Update.Set("Locked", true),
                            Update.Set("LockTimeout", DateTime.UtcNow.AddSeconds(30))
                            )
                    });

                    // Found unlocked data
                    if (result.ModifiedDocument != null)
                    {
                        break;
                    }

                    Thread.Sleep(100);
                }
            }

            return(result.GetModifiedDocumentAs <MyMongoData <T> >());
        }
示例#28
0
        // <summary>
        /// Deletes the user/role association with the specified id
        /// </summary>
        /// <param name="userRoleId">Id of the user/role to delete</param>
        /// <returns>Result of the operation, true if was ok</returns>
        public bool Delete(ObjectId userRoleId)
        {
            FindAndModifyResult result = UserRoles.FindAndRemove(Query.EQ("_id", userRoleId), SortBy.Ascending("_id"));

            return(result.Ok);
        }
示例#29
0
 public FindAndModifyUpdateResult(FindAndModifyResult result)
 {
     Result = result;
 }
示例#30
0
        /// <summary>
        /// Internal utility for obtaining blocks of unique OIDs for insertion
        /// Call CatalogDatasetEntry.GetNextOID() to get OIDs if writing a dataloader
        /// </summary>
        /// <param name="Name">Name of the Dataset</param>
        /// <param name="count">the size of the block requested</param>
        /// <returns>A FIFO block of OIDs</returns>
        internal Queue <int> GetOIDSet(string Name, int count = OIDCHECKOUT)
        {
            IMongoQuery query = Query.EQ("Name", BsonValue.Create(Name));

            int currCount      = 0;
            int oidCheckOutTry = 0;

            // we are going to try and get and update the shared OID resource
            // this is a necessary choke point, but the implementation can be improved
            // particularly for multi-client high volume inserts
            // we repeat try a few times and then fail for good - can't get a lock on
            // the oid set
            for (; oidCheckOutTry < OIDCHECKOUTTRYLIMIT; oidCheckOutTry++)
            {
                try
                {
                    BsonDocument doc = m_Conn[GDB_ITEMS].FindOne(query);
                    if (default(BsonDocument) == doc)
                    {
                        throw new COMException("missing metadata doc " + Name);
                    }

                    try
                    {
                        var next_oid = doc.GetElement("NEXT_OID");
                        currCount = esriBsonUtilities.BsonToInt(next_oid);
                    }
                    catch (Exception)
                    {
                        currCount = 0;
                    }

                    // include prev corr oid as condition
                    IMongoQuery query2   = Query.EQ("NEXT_OID", BsonValue.Create(currCount));
                    int         newCount = currCount + count;
                    query = Query.And(new IMongoQuery[2] {
                        query, query2
                    });

                    // atomic find and update - fails if the NEXT_OID has been updated by another client
                    FindAndModifyResult res = m_Conn[GDB_ITEMS].FindAndModify(query, null, Update.Set("NEXT_OID", BsonValue.Create(newCount)), true, false);

                    // if it's been updated out from under us
                    if (default(FindAndModifyResult) == res)
                    {
                        System.Threading.Thread.Sleep(SLEEPTIME_OIDCHECKOUT);
                        continue;
                    }
                    break;
                }
                catch (Exception) // if it's been updated out from under us
                {
                    System.Threading.Thread.Sleep(SLEEPTIME_OIDCHECKOUT);
                    continue;
                }
            }

            // we failed to get a block of new oids
            if (oidCheckOutTry == OIDCHECKOUTTRYLIMIT)
            {
                throw new COMException("Could not secure OIDs");
            }

            Queue <int> retVal = new Queue <int>(count);

            for (int i = currCount; i < (currCount + count); i++)
            {
                retVal.Enqueue(i);
            }

            return(retVal);
        }
示例#31
0
        public bool Delete(ObjectId id)
        {
            FindAndModifyResult phaseResult = Sponsors.FindAndRemove(Query.EQ("_id", id), SortBy.Ascending("_id"));

            return(phaseResult.Ok);
        }