Пример #1
0
        public ActionResult GetStatistics()
        {
            var viewModel = new StatsAggregateViewModel
            {
                MostFights   = StatsControllerHelpers.GetStatMostFights(),
                MostWins     = StatsControllerHelpers.GetStatMostWins(),
                MostLosses   = StatsControllerHelpers.GetStatMostLosses(),
                TopRanked    = StatsControllerHelpers.GetStatTopRanked(),
                BottomRanked = StatsControllerHelpers.GetStatBottomRanked()
            };

            var matches     = Dbh.GetCollection <Match>("Matches").FindAll();
            var matchesList = matches.SetSortOrder(SortBy.Ascending("GameOverTime")).ToList();

            viewModel.TotalNumberOfPlayedMatches = matches.Count();

            if (viewModel.TotalNumberOfPlayedMatches == 0)
            {
                return(Json(viewModel, JsonRequestBehavior.AllowGet));
            }

            var players = matches.Select(x => x.BluePlayer1).ToList();

            players.AddRange(matches.Select(x => x.BluePlayer2).ToList());
            players.AddRange(matches.Select(x => x.RedPlayer1).ToList());
            players.AddRange(matches.Select(x => x.RedPlayer2).ToList());

            viewModel.HighestRatingEver = StatsControllerHelpers.GetStatHighestRatingEver(players);
            viewModel.LowestRatingEver  = StatsControllerHelpers.GetStatLowestRatingEver(players);

            var winningStreak = StatsControllerHelpers.GetLongestWinningStreak(matchesList);

            winningStreak.Player           = DbHelper.GetPlayer(winningStreak.Player.Id);
            viewModel.LongestWinningStreak = winningStreak;

            var losingStreak = StatsControllerHelpers.GetLongestLosingStreak(matchesList);

            losingStreak.Player           = DbHelper.GetPlayer(losingStreak.Player.Id);
            viewModel.LongestLosingStreak = losingStreak;
            viewModel.BiggestRatingWin    = StatsControllerHelpers.GetBiggestRatingWin();

            return(Json(viewModel, JsonRequestBehavior.AllowGet));
        }
Пример #2
0
        public string GetNextErrorOccurrenceId(string id)
        {
            Error error = GetByIdCached(id);

            if (error == null)
            {
                return(null);
            }

            var cursor = _collection.FindAs <Error>(
                Query.And(
                    Query.EQ(FieldNames.ErrorStackId, new BsonObjectId(new ObjectId(error.ErrorStackId))),
                    Query.NE(FieldNames.Id, new BsonObjectId(new ObjectId(error.Id))),
                    Query.GTE(FieldNames.OccurrenceDate_UTC, error.OccurrenceDate.Ticks)));

            cursor.SetSortOrder(SortBy.Ascending(FieldNames.OccurrenceDate_UTC));
            cursor.SetLimit(10);
            cursor.SetFields(FieldNames.Id, FieldNames.OccurrenceDate);

            var results = cursor.Select(e => Tuple.Create(e.Id, e.OccurrenceDate)).ToList();

            if (results.Count == 0)
            {
                return(null);
            }

            // make sure we don't have records with the exact same occurrence date
            if (results.All(t => t.Item2 != error.OccurrenceDate))
            {
                return(results.OrderBy(t => t.Item2).ThenBy(t => t.Item1).First().Item1);
            }

            // we have records with the exact same occurrence date, we need to figure out the order of those
            // put our target error into the mix, sort it and return the result after the target
            var unionResults = results.Union(new[] { Tuple.Create(error.Id, error.OccurrenceDate) })
                               .OrderBy(t => t.Item2.Ticks).ThenBy(t => t.Item1)
                               .ToList();

            var index = unionResults.FindIndex(t => t.Item1 == error.Id);

            return(index == unionResults.Count - 1 ? null : unionResults[index + 1].Item1);
        }
Пример #3
0
        private DateTime GetStartDate()
        {
            bool resume = ConfigurationManager.AppSettings.GetBool("Migration:Resume", true);

            if (resume)
            {
                // Return the last queued day so we can reprocess the last day.
                long ticks;
                if (_cache.TryGet("migration-lastqueuedday", out ticks))
                {
                    return(new DateTimeOffset(ticks, TimeSpan.Zero).UtcDateTime.Date);
                }

                // Return the day after the last completed day.
                if (_cache.TryGet("migration-completedday", out ticks))
                {
                    return(new DateTimeOffset(ticks, TimeSpan.Zero).UtcDateTime.Date);
                }

                // Return the date of the last event.
                string id;
                if (_cache.TryGet("migration-errorid", out id) && !String.IsNullOrEmpty(id) && id.Length == 24)
                {
                    var ev = _eventRepository.GetById(id);
                    if (ev != null)
                    {
                        return(ev.Date.UtcDateTime.Date);
                    }
                }
            }

            var errorCollection = GetErrorCollection();
            var firstError      = errorCollection.Find(Query.Null).SetSortOrder(SortBy.Ascending(ErrorFieldNames.OccurrenceDate_UTC)).SetLimit(1).FirstOrDefault();

            if (firstError != null && firstError.OccurrenceDate.UtcDateTime.Date > DateTime.UtcNow.Date.SubtractYears(1))
            {
                return(firstError.OccurrenceDate.UtcDateTime.Date);
            }

            // Can't find the first error so lets default to exactly one year ago.
            return(DateTime.UtcNow.Date.SubtractYears(1));
        }
Пример #4
0
        /// <summary>
        /// Gets all timeouts that are due by now. Doesn't remove the timeouts or change them or anything,
        /// each individual timeout can be marked as processed by calling <see cref="DueTimeout.MarkAsProcessed"/>
        /// </summary>
        public IEnumerable <DueTimeout> GetDueTimeouts()
        {
            var result = collection.Find(Query.LTE(TimeProperty, RebusTimeMachine.Now()))
                         .SetSortOrder(SortBy.Ascending(TimeProperty));

            return(result
                   .Select(r => new DueMongoTimeout(r[ReplyToProperty].AsString,
                                                    r.Contains(CorrIdProperty)
                                                     ? r[CorrIdProperty].AsString
                                                     : "",
                                                    r[TimeProperty].AsDateTime,
                                                    r.Contains(SagaIdProperty)
                                                     ? r[SagaIdProperty].AsGuid
                                                     : Guid.Empty,
                                                    r.Contains(DataProperty)
                                                     ? r[DataProperty].AsString
                                                     : "",
                                                    collection,
                                                    (ObjectId)r[IdProperty])));
        }
Пример #5
0
        public async Task <Card> GetRandomCardWithDescription(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                throw new ArgumentException("text");
            }

            text = text.Replace("%", ".*");
            text = text.Replace("*", ".*");

            if (!text.EndsWith(".*"))
            {
                text = text + ".*";
            }

            text = ".*" + text;

            var collection = this.mDatabase.GetCollection <Card>(cCardsCollectionName);

            var query = Query.And(
                Query <Card> .Matches(e => e.Desc, new BsonRegularExpression(text, "i")),
                Query.NE("multiverseId", 0));

            var sortBy = SortBy.Ascending("multiverseId");

            Stopwatch watch = new Stopwatch();

            watch.Start();

            int count = (int)collection.Find(query).Count();

            var rand = new Random();
            var r    = rand.Next(count);
            var card = collection.Find(query).SetSortOrder(sortBy).Skip(r).FirstOrDefault();

            watch.Stop();

            this.mLoggingService.Trace("Elapsed time: {0}", watch.Elapsed);

            return(card);
        }
Пример #6
0
        public List <T> GetSortedByPersisted(DateTime _startDateTime, int _rows, Guid?_parentGuid = null)
        {
            IMongoQuery query;

            if (HasParent &&
                _parentGuid != null)
            {
                query = Query.And(Query.EQ("ParentGuid", new BsonString(_parentGuid.Value.ToString())),
                                  Query.GT("PersistedDateTime", new BsonString(_startDateTime.ToString("u"))));
            }
            else
            {
                query = Query.GT("PersistedDateTime", new BsonString(_startDateTime.ToString("u")));
            }


            MongoCursor cursor =
                MongoCollection.Find(query).SetSortOrder(SortBy.Ascending("PersistedDateTime")).SetLimit(_rows);

            return(GetList(cursor));
        }
Пример #7
0
        public IEnumerable <T> FindAll(string sortByKey, bool isAscending)
        {
            IEnumerable <T> results;

            if (sortByKey == "" || sortByKey == null)
            {
                results = FindAll();
            }
            else
            {
                if (isAscending)
                {
                    results = Collection.FindAllAs <T>().SetSortOrder(SortBy.Ascending(sortByKey)).AsEnumerable <T>();
                }
                else
                {
                    results = Collection.FindAllAs <T>().SetSortOrder(SortBy.Descending(sortByKey)).AsEnumerable <T>();
                }
            }
            return(results);
        }
        public List <Transition> GetTransitions(string streamId, int fromVersion, int toVersion)
        {
            var query = Query.And(Query.EQ("_id.StreamId", streamId),
                                  Query.GTE("_id.Version", fromVersion).LTE(toVersion));

            var sort = SortBy.Ascending("_id.Version");

            var docs = _server.Transitions.FindAs <BsonDocument>(query)
                       .SetSortOrder(sort)
                       .ToList();

            // Check that such stream exists
            if (docs.Count < 1)
            {
                throw new ArgumentException(String.Format("There is no stream in store with id {0}", streamId));
            }

            var transitions = docs.Select(_serializer.Deserialize).ToList();

            return(transitions);
        }
        public MongoCursor <SensorReading> GetSensorReadings(Trial trial)
        {
            ObservableCollection <SensorReading> sensor_readings = new ObservableCollection <SensorReading>();
            var query = Query.And(
                Query.EQ("study._id", trial.study._Id),
                Query.EQ("subject._id", trial.subject._Id),
                Query.EQ("session._id", trial.session._Id),
                Query.EQ("trial._id", trial._Id)
                );

            Console.WriteLine("Getting sensor readings");
            return(sensor_readings_collection.Find(query).SetSortOrder(SortBy.Ascending("time")));
            //foreach (SensorReading sr in sensor_readings_collection.Find(query))
            //{
            //    sensor_readings.Add(sr);
            //}
            //ObservableCollection<SensorReading> sensor_readingsSort = new ObservableCollection<SensorReading>(
            //    sensor_readings.OrderBy(s => s.recordnum)
            //    );
            //return sensor_readings;
        }
Пример #10
0
        /// <summary>
        ///     This function generates a query, and returns all coincidences where key = value
        /// </summary>
        /// <param name="key">
        ///     The collection's key value in the db
        /// </param>
        /// <param name="value">
        ///     The collection's value in the db
        /// </param>
        /// <author>
        ///     Luis Gonzalo Quijada Romero
        /// </author>
        /// <returns></returns>
        public List <BsonDocument> get(string key, string value)
        {
            var query  = Query.And(Query.EQ(key, value));                                                       //creating the query
            var cursor = collection.FindAs(typeof(BsonDocument), query).SetSortOrder(SortBy.Ascending("user")); //getting the collection's cursor
            List <BsonDocument> documents = new List <BsonDocument>();

            foreach (BsonDocument document in cursor) //putting the docuemnts into a list
            {
                if (isValidDocument(document))        //firts we have to check if this document has a valid structure
                {
                    try
                    {
                        document.Set("_id", document.GetElement("_id").Value.ToString());
                    }
                    catch (Exception e) { }
                }
                documents.Add(document);
            }

            return(documents);
        }
Пример #11
0
        public string GetFirstByLowestScoreFromSet(string key, double fromScore, double toScore)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            if (toScore < fromScore)
            {
                throw new ArgumentException("The `toScore` value must be higher or equal to the `fromScore` value.");
            }

            var set = _database.Set
                      .Find(Query.And(Query <SetDto> .EQ(_ => _.Key, key),
                                      Query.And(Query <SetDto> .GTE(_ => _.Score, fromScore), Query <SetDto> .LTE(_ => _.Score, toScore))))
                      .SetSortOrder(SortBy <SetDto> .Ascending(_ => _.Score))
                      .SetLimit(1)
                      .FirstOrDefault();

            return(set != null ? set.Value : null);
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="pageIndex">总页码</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="rowCounts">总记录数</param>
        /// <param name="expression">条件</param>
        /// <param name="isAsc">是否是正序</param>
        /// <param name="orderFiled">排序的字段</param>
        /// <returns></returns>
        public List <T> Page(int pageIndex, int pageSize, out long rowCounts, Expression <Func <T, bool> > expression = null, bool isAsc = true, params string[] orderFiled)
        {
            MongoCursor <T> mongoCursor;

            //条件选择
            if (expression != null)
            {
                rowCounts   = Collection.Find(Query <T> .Where(expression)).Count();
                mongoCursor = Collection.Find(Query <T> .Where(expression));
            }
            else
            {
                rowCounts   = Collection.FindAll().Count();
                mongoCursor = Collection.FindAll();
            }

            //排序
            if (orderFiled != null && orderFiled.Length > 0)
            {
                //处理主键字段
                for (int i = 0; i < orderFiled.Length; i++)
                {
                    if (orderFiled[i].Equals("id", StringComparison.CurrentCultureIgnoreCase))
                    {
                        orderFiled[i] = "_id";
                    }
                }

                if (isAsc)
                {
                    mongoCursor = mongoCursor.SetSortOrder(SortBy.Ascending(orderFiled));
                }
                else
                {
                    mongoCursor = mongoCursor.SetSortOrder(SortBy.Descending(orderFiled));
                }
            }

            return(mongoCursor.SetSkip((pageIndex - 1) * pageSize).SetLimit(pageSize).ToList());
        }
Пример #13
0
        public ActionResult Index()
        {
            if (Session["cid"] != null)
            {
                List <Table> TableList = this.TableCollection.FindAll().SetSortOrder(SortBy.Ascending("TableID")).ToList <Table>();
                foreach (var item in TableList)
                {
                    if (item.id.Equals(Session["ctableid"]))
                    {
                        ViewBag.cTableID = item.TableID.ToString();
                    }
                }
                ViewBag.CBill = this.BillCollection.FindOneById(ObjectId.Parse(Session["cid"].ToString()));

                return(View());
            }
            else
            {
                ViewBag.cTableID = "0";
                return(View());
            }
        }
Пример #14
0
        public IEnumerable <UserProfile> GetProfiles(int pageIndex, int pageSize, out int pageCount)
        {
            var query = _mongoCollection.FindAll();

            query.SetLimit(pageSize);
            query.SetSkip(pageSize * pageIndex);
            query.SetSortOrder(SortBy.Ascending("_id"));
            pageCount = ((int)query.Count()) / pageSize;
            if (query.Count() % pageSize != 0)
            {
                pageCount += 1;
            }

            var userProfiles = query.Select(a => a).ToList();

            foreach (var userProfile in userProfiles)
            {
                userProfile.UserProfile.MongoUserID = userProfile.UserID.ToString();
            }

            return(userProfiles.Select(a => a.UserProfile).ToList());
        }
        public static string GetEventsForOrganization(string organizationName)
        {
            var entries = historyCollection.FindAs <HistoryEntry>(Query.EQ("OrganizationName", organizationName))
                          .SetSortOrder(SortBy.Ascending("TimeRecorded"));
            StringBuilder sb = new StringBuilder();

            foreach (var item in entries)
            {
                if (string.IsNullOrEmpty(item.ProjectName))
                {
                    sb.AppendFormat("By {1} - {2}, at {3}", item.ProjectName, item.ByUser, item.Informaiton, item.TimeRecorded.ToShortDateString());
                }
                else
                {
                    sb.AppendFormat("In {0}, by {1} - {2}, at {3}", item.ProjectName, item.ByUser, item.Informaiton, item.TimeRecorded.ToShortDateString());
                }
                sb.AppendLine();
                sb.AppendLine(" - ");
            }

            return(sb.ToString());
        }
Пример #16
0
        private MongoCursor <BsonDocument> Find(string collectionName, string query, string fields, string sort, int skip, int limit)
        {
            MongoCollection <BsonDocument> collection = Database.GetCollection <BsonDocument>(collectionName);
            MongoCursor <BsonDocument>     cursor     = (string.IsNullOrEmpty(query)) ? collection.FindAll() : collection.Find(new QueryDocument(ParseQuery(query)));

            if (!string.IsNullOrEmpty(fields))
            {
                ParseQuery(fields).ToList().ForEach(item =>
                {
                    if (item.Value == 0)
                    {
                        cursor.SetFields(Fields.Exclude(item.Name));
                    }
                    else
                    {
                        cursor.SetFields(Fields.Include(item.Name));
                    }
                });
            }

            if (!string.IsNullOrEmpty(sort))
            {
                ParseQuery(sort).ToList().ForEach(itemtoSort =>
                {
                    if (itemtoSort.Value > 0)
                    {
                        cursor.SetSortOrder(SortBy.Ascending(itemtoSort.Name));
                    }
                    else
                    {
                        cursor.SetSortOrder(SortBy.Descending(itemtoSort.Name));
                    }
                });
            }

            cursor.SetSkip(skip);
            cursor.SetLimit(limit);
            return(cursor);
        }
Пример #17
0
        public List <Transition> GetTransitions(string streamId, int fromVersion, int toVersion)
        {
            var query = Query.And(Query.EQ("_id.StreamId", streamId),
                                  Query.GTE("_id.Version", fromVersion),
                                  Query.LTE("_id.Version", toVersion));

            var sort = SortBy.Ascending("_id.Version");

            var docs = _transitionServer.Transitions.FindAs <BsonDocument>(query)
                       .SetSortOrder(sort)
                       .ToList();

            // Check that such stream exists
            if (docs.Count < 1)
            {
                return(new List <Transition>());
            }

            var transitions = docs.Select(_serializer.Deserialize).ToList();

            return(transitions);
        }
Пример #18
0
        public List <CardPrice> GetCardsByPriceDecrease(int limit = 10)
        {
            List <CardPrice> prices = new List <CardPrice>();

            var cardPriceCollection = this.mDatabase.GetCollection <CardPrice>(cCardPriceCollectionName);

            var cardQuery = Query.And(
                Query.LT("priceDiffValue", 0),
                Query.NE("priceMid", ""),
                Query.NE("priceLow", ""),
                Query.NE("priceFoil", ""),
                Query.NE("searchName", "swamp"),
                Query.NE("searchName", "mountain"),
                Query.NE("searchName", "plains"),
                Query.NE("searchName", "island"),
                Query.NE("searchName", "forest")
                );

            var sortBy = SortBy.Ascending("priceDiffValue");

            Stopwatch watch = new Stopwatch();

            watch.Start();

            MongoCursor <CardPrice> cursor = cardPriceCollection.FindAs <CardPrice>(cardQuery)
                                             .SetSortOrder(sortBy)
                                             .SetLimit(limit);

            foreach (CardPrice price in cursor)
            {
                prices.Add(price);
            }

            watch.Stop();

            this.mLoggingService.Trace("Elapsed time: {0}", watch.Elapsed);

            return(prices);
        }
Пример #19
0
        private MongoCursor <T> OrderCursor(MongoCursor <T> cursor, IList <string> orderByFieldAsc, IList <string> orderByFieldDesc)
        {
            bool fieldDesc = ((orderByFieldDesc != null) && (orderByFieldDesc.Count > 0));
            bool fieldAsc  = ((orderByFieldAsc != null) && (orderByFieldAsc.Count > 0));

            if ((fieldAsc) && (fieldDesc))
            {
                return(cursor.SetSortOrder(SortBy.Descending(orderByFieldDesc.ToArray()).Ascending(orderByFieldAsc.ToArray())));
            }
            else if (fieldAsc)
            {
                return(cursor.SetSortOrder(SortBy.Ascending(orderByFieldAsc.ToArray())));
            }
            else if (fieldDesc)
            {
                return(cursor.SetSortOrder(SortBy.Descending(orderByFieldDesc.ToArray())));
            }
            else
            {
                return(cursor);
            }
        }
Пример #20
0
        public CardPrice GetCardPrice(string name, string setCode)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("name");
            }

            if (string.IsNullOrEmpty(setCode))
            {
                throw new ArgumentException("setCode");
            }

            string searchName = this.mSearchUtility.GetRegexSearchValue(name);

            this.mLoggingService.Debug("Getting price for '{0}' [{1}] using search name '{2}'...",
                                       name,
                                       setCode,
                                       searchName);

            var cardPriceCollection = this.mDatabase.GetCollection <CardPrice>(cCardPriceCollectionName);

            var query = Query.And(
                Query <CardPrice> .Matches(e => e.SearchName, new BsonRegularExpression(searchName, "i")),
                Query <CardPrice> .Matches(e => e.SetCode, setCode));

            var sortBy = SortBy.Ascending("lastUpdated");

            Stopwatch watch = new Stopwatch();

            watch.Start();

            var card = cardPriceCollection.FindAs <CardPrice>(query).SetSortOrder(sortBy).SetLimit(1);

            watch.Stop();

            this.mLoggingService.Trace("Elapsed time: {0}", watch.Elapsed);

            return(card.FirstOrDefault());
        }
        /// <summary>
        /// Retrieves the next waiting Message from the Queue based
        /// on a provided queueName
        /// </summary>
        /// <param name="queueName">Name of the queue</param>
        /// <returns>
        /// item or null.
        /// Null can be returned when there are no items
        /// or when there is an error. To check for error check
        /// </returns>
        public override QueueMessageItem GetNextQueueMessage(string queueName = null)
        {
            SetError();

            List <IMongoQuery> queries = new List <IMongoQuery>();

            if (queueName != null)
            {
                queries.Add(Query.EQ("QueueName", queueName));
            }

            queries.Add(Query.EQ("Started", BsonNull.Value));

            var query  = Query.And(queries);
            var sort   = SortBy.Ascending("Submitted");
            var update = Update.Set("Started", DateTime.UtcNow).Set("Status", "Started");

            var result = Collection.FindAndModify(query, sort, update, true);

            if (!result.Ok)
            {
                SetError(result.ErrorMessage);
                return(null);
            }

            var item = result.GetModifiedDocumentAs <QueueMessageItem>();

            item.__IsNew = false;
            item.Started = DateTime.UtcNow;
            item.Status  = "Started";

            // load up Properties from XmlProperties field
            GetProperties("XmlProperties", Item);

            Item = item;

            return(Item);
        }
Пример #22
0
 /// <summary>
 /// 查找并排序分页
 /// (其中排序的参数有多个)
 /// </summary>
 /// <param name="queryObject"></param>
 /// <param name="sorts">排序的参数,key为field,value代表是否递增:true,递增;false,递减;前面的优先级高</param>
 /// <param name="pageIndex">页面号</param>
 /// <param name="pageSize">每页显示数量</param>
 /// <returns></returns>
 public IEnumerable <T> Find(QueryObject <T> queryObject, List <KeyValuePair <string, bool> > sorts, int pageIndex, int pageSize)
 {
     if (queryObject.Query == null)
     {
         FindAll(sorts, pageIndex, pageSize);
     }
     if ((sorts.Count() == 0 || sorts == null) && (pageIndex == 0 || pageSize == 0))
     {
         return(Find(queryObject));
     }
     else if ((sorts.Count() == 0 || sorts == null) && (pageIndex != 0 && pageSize != 0))
     {
         return(Find(queryObject, pageIndex, pageSize));
     }
     else if ((sorts.Count() > 0 && sorts != null) && (pageIndex == 0 || pageSize == 0))
     {
         return(Find(queryObject, sorts));
     }
     else
     {
         IEnumerable <T> results;
         var             query  = (IMongoQuery)(queryObject.Query);
         var             source = Collection.FindAs <T>(query);
         for (int i = 0; i < sorts.Count(); i++)
         {
             if (sorts[i].Value)
             {
                 source = source.SetSortOrder(SortBy.Ascending(sorts[i].Key));
             }
             else
             {
                 source = source.SetSortOrder(SortBy.Descending(sorts[i].Key));
             }
         }
         results = source.SetSkip((pageIndex - 1) * pageSize).SetLimit(pageSize);
         return(results);
     }
 }
Пример #23
0
        private TickQuoteTw getLatest(string iceId)
        {
            // if not exist, return null

            iceId = iceId.Replace(".", "_");

            var sortAscending  = SortBy.Ascending("datetime");
            var sortDescending = SortBy.Descending("datetime");

            //TickQuoteTw minDocument = MongoUtility.Instance.getCollection(symbolGroup, iceId).FindAllAs<TickQuoteTw>().SetSortOrder(sortAscending).SetLimit(1).First();
            TickQuoteTw maxDocument;

            try
            {
                maxDocument = MongoUtility.Instance.getCollection(symbolGroup, iceId).FindAllAs <TickQuoteTw>().SetSortOrder(sortDescending).SetLimit(1).First();
            }
            catch (System.InvalidOperationException e)
            {
                maxDocument = null;
                logger.Info("getLatest : data not exist : " + iceId);
            }
            return(maxDocument);
        }
        public void ShouldPageQueryWithExplicitAcsendingOrder()
        {
            var connection = GetUserQuery().ToConnection(
                user => SortBy.Ascending(user.Id),
                (userId, after) => userId > after,
                user => new ExposedUser
            {
                Login     = user.Login,
                Email     = user.Email,
                FirstName = user.FirstName,
                Name      = user.FirstName + user.LastName
            },
                new Request
            {
                First = 2,
                After = ConnectionQuerySettings.Default.CursorFormatter.Format(1)
            });

            Assert.AreEqual(2, connection.Edges.Count, "Count of edges is wrong");
            Assert.AreEqual(6, connection.TotalCount, "TotalCount is wrong");
            Assert.IsTrue(connection.PageInfo.HasNextPage, "HasNextPage is wrong");
            Assert.IsTrue(connection.PageInfo.HasPreviousPage, "HasPreviousPage is wrong");
        }
Пример #25
0
        public async Task <Card> GetCard(int multiverseId)
        {
            this.mLoggingService.Trace("Getting card by id '{0}'...", multiverseId);

            var collection = this.mDatabase.GetCollection <Card>(cCardsCollectionName);

            var query = Query <Card> .EQ(e => e.MultiverseId, multiverseId);

            var sortBy = SortBy.Ascending("searchName");

            Stopwatch watch = new Stopwatch();

            watch.Start();

            var cardResult = collection.FindAs <Card>(query).SetSortOrder(sortBy).SetLimit(1);

            watch.Stop();

            this.mLoggingService.Trace("Elapsed time: {0}", watch.Elapsed);

            var card = cardResult.FirstOrDefault();

            if (card == null)
            {
                this.mLoggingService.Warning("No card found using '{0}'.", multiverseId);
            }
            else
            {
                this.mLoggingService.Trace("Card found using '{0}': {1} [{2}]",
                                           multiverseId,
                                           card.Name,
                                           card.SetName);
            }

            return(card);
        }
Пример #26
0
        public JsonResult ListResultBillinginfo(int?_id, string code, string customer_id, string customer_name, string provider, string service, string status, int?page, int?page_size)
        {
            IMongoQuery query = null;

            if (_id != null)
            {
                query = (query == null) ? Query.EQ("_id", _id) : Query.And(
                    query,
                    Query.EQ("_id", _id)
                    );
            }
            if (!String.IsNullOrEmpty(code))
            {
                query = (query == null) ? Query.EQ("code", code) : Query.And(
                    query,
                    Query.EQ("code", code)
                    );
            }
            if (!String.IsNullOrEmpty(customer_id))
            {
                query = (query == null) ? Query.EQ("customer_id", customer_id) : Query.And(
                    query,
                    Query.EQ("customer_id", customer_id)
                    );
            }
            if (!String.IsNullOrEmpty(customer_name))
            {
                query = (query == null) ? Query.EQ("customer_name", customer_name) : Query.And(
                    query,
                    Query.EQ("customer_name", customer_name)
                    );
            }
            if (!String.IsNullOrEmpty(provider))
            {
                query = (query == null) ? Query.EQ("provider.name", provider) : Query.And(
                    query,
                    Query.EQ("provider.name", provider)
                    );
            }
            if (!String.IsNullOrEmpty(service))
            {
                query = (query == null) ? Query.EQ("service", service) : Query.And(
                    query,
                    Query.EQ("service", service)
                    );
            }
            if (!String.IsNullOrEmpty(status))
            {
                query = (query == null) ? Query.EQ("status", status) : Query.And(
                    query,
                    Query.EQ("status", status)
                    );
            }

            if (page == null)
            {
                page = 1;
            }
            if (page_size == null)
            {
                page_size = 25;
            }
            long total_page = 0;
            var  _list      = Helper.DataHelper.ListPagging("billing_info",
                                                            query,
                                                            SortBy.Ascending("_id"),
                                                            (int)page_size,
                                                            (int)page,
                                                            out total_page
                                                            );
            var list_accounts = (from e in _list select e).Select(p => new
            {
                _id           = p._id,
                code          = p.code,
                customer_id   = p.customer_id,
                customer_name = p.customer_name,
                provider      = p.provider.code,
                service       = p.service.code,
                status        = p.status
            }).ToArray();

            return(Json(new { total = total_page, list = list_accounts }, JsonRequestBehavior.AllowGet));
        }
Пример #27
0
        public void ReplayMatches()
        {
            var currentUser = (User)Session["User"];

            if (currentUser != null && Settings.AdminAccounts.Contains(currentUser.Email))
            {
                var allMatches = Dbh.GetCollection <Match>("Matches").FindAll().SetSortOrder(SortBy.Ascending("GameOverTime"));
                var allPlayers = Dbh.GetCollection <Player>("Players").FindAll();

                var copyMatches = Dbh.GetCollection <Match>("CopyMatches");
                var copyPlayers = Dbh.GetCollection <Player>("CopyPlayers");

                // Empty the Copies
                copyMatches.RemoveAll();
                copyPlayers.RemoveAll();

                // Reset all Players
                foreach (var player in allPlayers)
                {
                    player.Lost   = 0;
                    player.Won    = 0;
                    player.Played = 0;
                    player.Rating = 1000;

                    copyPlayers.Save(player);
                }

                /////////////////////////////////////////////////////////////////////////////////////////////////////////
                // replay each match in chronological order
                /////////////////////////////////////////////////////////////////////////////////////////////////////////
                foreach (var match in allMatches)
                {
                    // Update players from the match with players from the Db.
                    match.RedPlayer1 = copyPlayers.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.RedPlayer1.Id)));

                    if (match.CountRedPlayers() == 2)
                    {
                        match.RedPlayer2 = copyPlayers.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.RedPlayer2.Id)));
                    }

                    match.BluePlayer1 = copyPlayers.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.BluePlayer1.Id)));

                    if (match.CountBluePlayers() == 2)
                    {
                        match.BluePlayer2 = copyPlayers.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.BluePlayer2.Id)));
                    }

                    // Determine the winners and the losers
                    var winners = new Team();
                    var losers  = new Team();

                    if (match.RedScore > match.BlueScore)
                    {
                        winners.Players.Add(match.RedPlayer1);
                        winners.Players.Add(match.RedPlayer2);
                        losers.Players.Add(match.BluePlayer1);
                        losers.Players.Add(match.BluePlayer2);
                    }
                    else
                    {
                        winners.Players.Add(match.BluePlayer1);
                        winners.Players.Add(match.BluePlayer2);
                        losers.Players.Add(match.RedPlayer1);
                        losers.Players.Add(match.RedPlayer2);
                    }

                    // Get the rating modifier
                    match.DistributedRating = Rating.GetRatingModifier(winners.GetTeamRating(), losers.GetTeamRating());

                    // Propagate the rating and stats to the team members of both teams
                    foreach (var member in winners.Players.Where(member => member.Id != null))
                    {
                        member.Rating += match.DistributedRating;
                        member.Won++;
                        member.Played++;
                        copyPlayers.Save(member);
                    }

                    foreach (var member in losers.Players.Where(member => member.Id != null))
                    {
                        member.Rating -= match.DistributedRating;
                        member.Lost++;
                        member.Played++;
                        copyPlayers.Save(member);
                    }

                    // Save the data to Db
                    copyMatches.Save(match);
                }

                // Copy data into Production tables
                var matches = Dbh.GetCollection <Match>("Matches");
                var players = Dbh.GetCollection <Match>("Players");
                matches.RemoveAll();
                players.RemoveAll();

                foreach (var player in copyPlayers.FindAll())
                {
                    players.Save(player);
                }

                foreach (var match in copyMatches.FindAll())
                {
                    matches.Save(match);
                }
            }
        }
Пример #28
0
        public String GetRowsReports(string id, string type = null)
        {
            var orderfield = "name";



            try
            {
                List <BsonDocument> documents = new List <BsonDocument>();
                if (id != null)
                {
                    IMongoQuery query;
                    if (type != null)
                    {
                        query = Query.And(Query.EQ("UserId", id), Query.EQ("CategoryReport", type));
                    }
                    else
                    {
                        query = Query.And(Query.EQ("UserId", id));
                    }
                    var cursor = collection.FindAs(typeof(BsonDocument), query).SetSortOrder(SortBy.Ascending(orderfield));


                    foreach (BsonDocument document in cursor)
                    {
                        document.Set("_id", document.GetElement("_id").Value.ToString());
                        try
                        {
                            document.Set("CreatedTimeStamp", document.GetElement("CreatedTimeStamp").Value.ToString());
                        }
                        catch (Exception ex)
                        {
                        }
                        documents.Add(document);
                    }
                }


                return(documents.ToJson());
            }
            catch (Exception e)
            {
                //    System.Windows.Forms.MessageBox.Show(e.ToString());
                return(null);
            }
        }
Пример #29
0
        public IEnumerable <EventData> Load(string aggregateRootId, long firstSeq = 0)
        {
            // aggregation framework is extremely slow - don't use it (for this)
            //var args = new AggregateArgs
            //{
            //    Pipeline = new[]
            //    {
            //        new BsonDocument {{"$unwind", "$Events"}},
            //        new BsonDocument
            //        {
            //            {
            //                "$match", new BsonDocument
            //                {
            //                    {"Events.AggregateRootId", aggregateRootId},
            //                    {"Events.SequenceNumber", new BsonDocument {{"$gte", firstSeq}}},
            //                }
            //            }
            //        },
            //        new BsonDocument {{"$sort", new BsonDocument {{"Events.SequenceNumber", 1}}}}
            //    }
            //};

            //return _eventBatches.Aggregate(args)
            //    .Select(result =>
            //    {
            //        var bsonValue = result["Events"];
            //        var asBsonDocument = bsonValue.AsBsonDocument;
            //        return BsonSerializer.Deserialize<MongoEvent>(asBsonDocument);
            //    })
            //    .Select(MongoEventToEvent);

            var lowerSequenceNumber = firstSeq;

            while (true)
            {
                var eventCriteria = Query.And(Query.EQ("AggregateRootId", aggregateRootId),
                                              Query.GTE("SequenceNumber", lowerSequenceNumber));

                var criteria = Query.ElemMatch("Events", eventCriteria);

                var lowerSequenceNumberInQuery = lowerSequenceNumber;
                var eventBatch = _eventBatches.Find(criteria)
                                 .SetSortOrder(SortBy.Ascending(GlobalSeqNoDocPath))
                                 .SetLimit(1000)
                                 .SelectMany(b => b.Events
                                             .Where(e => e.AggregateRootId == aggregateRootId)
                                             .OrderBy(e => e.SequenceNumber))
                                 .Where(e => e.SequenceNumber >= lowerSequenceNumberInQuery)
                                 .Select(MongoEventToEvent);

                var hadEvents = false;
                var maxSequenceNumberInBatch = -1L;

                foreach (var e in eventBatch)
                {
                    hadEvents = true;
                    yield return(e);

                    maxSequenceNumberInBatch = e.GetSequenceNumber();
                }

                if (!hadEvents)
                {
                    break;
                }

                lowerSequenceNumber = maxSequenceNumberInBatch + 1;
            }
        }
Пример #30
0
        protected override async Task <JobResult> RunInternalAsync(CancellationToken token)
        {
            OutputPublicIp();
            QueueEntry <EventMigrationBatch> queueEntry = null;

            try {
                queueEntry = _queue.Dequeue();
            } catch (Exception ex) {
                if (!(ex is TimeoutException))
                {
                    Log.Error().Exception(ex).Message("Error trying to dequeue message: {0}", ex.Message).Write();
                    return(JobResult.FromException(ex));
                }
            }

            if (queueEntry == null)
            {
                return(JobResult.Success);
            }

            Log.Info().Message("Processing event migration jobs for date range: {0}-{1}", new DateTimeOffset(queueEntry.Value.StartTicks, TimeSpan.Zero).ToString("O"), new DateTimeOffset(queueEntry.Value.EndTicks, TimeSpan.Zero).ToString("O")).Write();

            int total     = 0;
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            var errorCollection = GetErrorCollection();
            var knownStackIds   = new List <string>();

            var serializerSettings = new JsonSerializerSettings {
                MissingMemberHandling = MissingMemberHandling.Ignore
            };

            serializerSettings.AddModelConverters();

            var query  = Query.And(Query.GTE(ErrorFieldNames.OccurrenceDate_UTC, queueEntry.Value.StartTicks), Query.LT(ErrorFieldNames.OccurrenceDate_UTC, queueEntry.Value.EndTicks));
            var errors = errorCollection.Find(query).SetSortOrder(SortBy.Ascending(ErrorFieldNames.OccurrenceDate_UTC)).SetLimit(_batchSize).ToList();

            while (errors.Count > 0)
            {
                Log.Info().Message("Migrating events {0}-{1} {2:N0} total {3:N0}/s...", errors.First().Id, errors.Last().Id, total, total > 0 ? total / stopwatch.Elapsed.TotalSeconds : 0).Write();

                var upgradedErrors = JArray.FromObject(errors);
                var ctx            = new EventUpgraderContext(upgradedErrors, new Version(1, 5), true);
                _eventUpgraderPluginManager.Upgrade(ctx);

                var upgradedEvents = upgradedErrors.FromJson <PersistentEvent>(serializerSettings);

                var stackIdsToCheck = upgradedEvents.Where(e => !knownStackIds.Contains(e.StackId)).Select(e => e.StackId).Distinct().ToArray();
                if (stackIdsToCheck.Length > 0)
                {
                    knownStackIds.AddRange(_eventRepository.ExistsByStackIds(stackIdsToCheck));
                }

                upgradedEvents.ForEach(e => {
                    if (e.Date.UtcDateTime > DateTimeOffset.UtcNow.AddHours(1))
                    {
                        e.Date = DateTimeOffset.Now;
                    }

                    e.CreatedUtc = e.Date.ToUniversalTime().DateTime;

                    if (!knownStackIds.Contains(e.StackId))
                    {
                        // We haven't processed this stack id yet in this run. Check to see if this stack has already been imported..
                        e.IsFirstOccurrence = true;
                        knownStackIds.Add(e.StackId);
                    }

                    var request = e.GetRequestInfo();
                    if (request != null)
                    {
                        e.AddRequestInfo(request.ApplyDataExclusions(RequestInfoPlugin.DefaultExclusions, RequestInfoPlugin.MAX_VALUE_LENGTH));
                    }

                    foreach (var ip in GetIpAddresses(e, request))
                    {
                        var location = _geoIpResolver.ResolveIp(ip);
                        if (location == null || !location.IsValid())
                        {
                            continue;
                        }

                        e.Geo = location.ToString();
                        break;
                    }

                    if (e.Type == Event.KnownTypes.NotFound && request != null)
                    {
                        if (String.IsNullOrWhiteSpace(e.Source))
                        {
                            e.Message = null;
                            e.Source  = request.GetFullPath(includeHttpMethod: true, includeHost: false, includeQueryString: false);
                        }

                        return;
                    }

                    var error = e.GetError();
                    if (error == null)
                    {
                        Debugger.Break();
                        Log.Error().Project(e.ProjectId).Message("Unable to get parse error model: {0}", e.Id).Write();
                        return;
                    }

                    var stackingTarget = error.GetStackingTarget();
                    if (stackingTarget != null && stackingTarget.Method != null && !String.IsNullOrEmpty(stackingTarget.Method.GetDeclaringTypeFullName()))
                    {
                        e.Source = stackingTarget.Method.GetDeclaringTypeFullName().Truncate(2000);
                    }

                    var signature = new ErrorSignature(error);
                    if (signature.SignatureInfo.Count <= 0)
                    {
                        return;
                    }

                    var targetInfo = new SettingsDictionary(signature.SignatureInfo);
                    if (stackingTarget != null && stackingTarget.Error != null && !targetInfo.ContainsKey("Message"))
                    {
                        targetInfo["Message"] = error.GetStackingTarget().Error.Message;
                    }

                    error.Data[Error.KnownDataKeys.TargetInfo] = targetInfo;
                });

                try {
                    _eventRepository.Add(upgradedEvents, sendNotification: false);
                } catch (Exception) {
                    foreach (var persistentEvent in upgradedEvents)
                    {
                        try {
                            _eventRepository.Add(persistentEvent, sendNotification: false);
                        } catch (Exception ex) {
                            //Debugger.Break();
                            Log.Error().Exception(ex).Message("An error occurred while migrating event '{0}': {1}", persistentEvent.Id, ex.Message).Write();
                        }
                    }
                }

                total += upgradedEvents.Count;
                var lastId = upgradedEvents.Last().Id;
                _cache.Set("migration-errorid", lastId);
                errors = errorCollection.Find(Query.And(Query.GT(ErrorFieldNames.Id, ObjectId.Parse(lastId)), Query.LT(ErrorFieldNames.OccurrenceDate_UTC, queueEntry.Value.EndTicks)))
                         .SetSortOrder(SortBy.Ascending(ErrorFieldNames.OccurrenceDate_UTC))
                         .SetLimit(_batchSize).ToList();
            }

            _cache.Set("migration-completedday", queueEntry.Value.EndTicks);
            queueEntry.Complete();

            return(JobResult.Success);
        }