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);
        }
Example #4
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);
        }
Example #5
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> >());
        }