Пример #1
0
        public ActionResult Index()
        {
            if (Request[GlobalConst.ASmallCakeCookieName] != null)
            {
                return(RedirectToAction("Index", new {}));
            }
            var db = new ZkDataContext();

            var result = new IndexResult()
            {
                Spotlight    = SpotlightHandler.GetRandom(),
                Top10Players =
                    db.Accounts.Where(x => x.SpringBattlePlayers.Any(y => y.SpringBattle.StartTime > DateTime.UtcNow.AddMonths(-1))).OrderByDescending(
                        x => x.Elo1v1).Take(10)
            };

            result.LobbyStats = AuthServiceClient.GetLobbyStats();
            result.News       = db.News.Where(x => x.Created < DateTime.UtcNow).OrderByDescending(x => x.Created);
            if (Global.Account != null)
            {
                result.Headlines =
                    db.News.Where(
                        x => x.Created <DateTime.UtcNow && x.HeadlineUntil != null && x.HeadlineUntil> DateTime.UtcNow && (Global.Account.LastNewsRead == null || (x.Created > Global.Account.LastNewsRead))).
                    OrderByDescending(x => x.Created);

                if (result.Headlines.Any())
                {
                    db.Accounts.Single(x => x.AccountID == Global.AccountID).LastNewsRead = DateTime.UtcNow;
                    db.SubmitChanges();
                }
            }
            else
            {
                result.Headlines = new List <News>();
            }


            var accessibleThreads = db.ForumThreads.Where(x => x.RestrictedClanID == null || x.RestrictedClanID == Global.ClanID);

            if (!Global.IsAccountAuthorized)
            {
                result.NewThreads = accessibleThreads.OrderByDescending(x => x.LastPost).Take(10).Select(x => new NewThreadEntry()
                {
                    ForumThread = x
                });
            }
            else
            {
                result.NewThreads = (from t in accessibleThreads
                                     let read = t.ForumThreadLastReads.SingleOrDefault(x => x.AccountID == Global.AccountID)
                                                where read == null || t.LastPost > read.LastRead
                                                orderby t.LastPost descending
                                                select new NewThreadEntry {
                    ForumThread = t, WasRead = read != null, WasWritten = read != null && read.LastPosted != null
                }).
                                    Take(10);
            }

            return(View(result));
        }
Пример #2
0
        public async Task <IndexResult> Index(string id, ClassificationModel existing)
        {
            var apiKey = Environment.GetEnvironmentVariable("RIJKSMUSEUM_DATA_API_KEY");
            var collectionApiRequestUrl = $"https://www.rijksmuseum.nl/api/en/collection/{id}?key={apiKey}";
            var collectionResponse      = await HttpClient.GetStringAsync(collectionApiRequestUrl);

            var collectionJson = JObject.Parse(collectionResponse);
            var model          = new ClassificationModel
            {
                Source         = Source,
                PageId         = id,
                SourceLink     = $"https://www.rijksmuseum.nl/en/collection/{id}",
                OriginalArtist = collectionJson["artObject"]["principalMaker"].Value <string>(),
                Date           = collectionJson["artObject"]["dating"]["presentingDate"].Value <string>(),
                Name           = collectionJson["artObject"]["titles"].Values <string>().FirstOrDefault()
            };

            if (string.IsNullOrWhiteSpace(model.Name))
            {
                model.Name = collectionJson["artObject"]["title"].Value <string>();
            }
            var indexResult = new IndexResult
            {
                Model     = model,
                ImageJpeg = await new TileImageStitcher().GetStitchedTileImageJpegBytes(id, Environment.GetEnvironmentVariable("RIJKSMUSEUM_DATA_API_KEY"))
            };

            return(indexResult);
        }
        public async Task <IndexResult> AddData([FromBody] string indexName)
        {
            var addData = new IndexResult();

            if (string.IsNullOrEmpty(indexName))
            {
                addData.Messages = new List <AlertViewModel> {
                    new AlertViewModel("danger", "no indexName defined", "Please provide the index name"),
                };
                return(addData);
            }
            try
            {
                PersonCityData.CreateTestData();
                await _searchProviderIndex.AddDocumentsToIndex(PersonCityData.Data).ConfigureAwait(false);

                addData.Messages = new List <AlertViewModel> {
                    new AlertViewModel("success", "Documented added", "The Azure Search documents were uploaded! The Document Count takes n seconds to update!"),
                };
                var indexStatus = await _searchProviderIndex.GetIndexStatus().ConfigureAwait(false);

                addData.Status.IndexExists   = indexStatus.Exists;
                addData.Status.DocumentCount = indexStatus.DocumentCount;
                return(addData);
            }
            catch (Exception ex)
            {
                addData.Messages = new List <AlertViewModel> {
                    new AlertViewModel("danger", "Error adding documents", ex.Message),
                };
                return(addData);
            }
        }
        public async Task <IndexResult> DeleteIndex([FromBody] string indexName)
        {
            var deleteIndex = new IndexResult();

            if (string.IsNullOrEmpty(indexName))
            {
                deleteIndex.Messages = new List <AlertViewModel> {
                    new AlertViewModel("danger", "no indexName defined", "Please provide the index name"),
                };
                return(deleteIndex);
            }

            try
            {
                await _searchProviderIndex.DeleteIndex(indexName).ConfigureAwait(false);

                deleteIndex.Messages = new List <AlertViewModel> {
                    new AlertViewModel("success", "Index Deleted!", "The Azure Search Index was successfully deleted!"),
                };
                var indexStatus = await _searchProviderIndex.GetIndexStatus().ConfigureAwait(false);

                deleteIndex.Status.IndexExists   = indexStatus.Exists;
                deleteIndex.Status.DocumentCount = indexStatus.DocumentCount;
                return(deleteIndex);
            }
            catch (Exception ex)
            {
                deleteIndex.Messages = new List <AlertViewModel> {
                    new AlertViewModel("danger", "Error deleting index", ex.Message),
                };
                return(deleteIndex);
            }
        }
Пример #5
0
        /// <summary>
        /// Go to home page; also updates news read dates
        /// </summary>
        public ActionResult Index()
        {
            // TODO: make two separate pages -- one for logged in users, one for not-logged in users
            // logged in users see their user profile
            // non-logged in users see promotional page

            var db = new ZkDataContext();

            if (!Global.IsAccountAuthorized)
            {
                return(View("Splash"));
            }

            // TODO: randomized backgrounds move here
            var result = new IndexResult
            {
                Spotlight         = SpotlightHandler.GetRandom(),
                Top10Players      = RatingSystems.GetRatingSystem(RatingCategory.MatchMaking).GetTopPlayers(10),
                WikiRecentChanges = MediaWikiRecentChanges.LoadRecentChanges(),
                LobbyStats        = MemCache.GetCached("lobby_stats", GetCurrentLobbyStats, 60 * 2),
                News       = db.News.Where(x => x.Created < DateTime.UtcNow).OrderByDescending(x => x.Created),
                Headlines  = GetHeadlines(db),
                NewThreads = GetNewForumThreads(db)
            };

            return(View("HomeIndex", result));
        }
Пример #6
0
        public JsonResult GetIndexModel()
        {
            var model = new ResultModel <IndexResult>();

            _service.Command <IndexResult>((db, o) =>
            {
                db.CurrentFilterKey = null;//无假删除不需要走过滤器
                IndexResult res     = new IndexResult();
                res.VList           = db.Queryable <VisitorList>()
                                      .JoinTable <UserInfo>((v, u) => v.VisitorId == u.Id)
                                      .OrderBy(v => v.VisitorId).Take(12)
                                      .Where(v => v.Uid == _userInfo.Id)
                                      .Select <UserInfo, V_VisitorList>((v, u) => new V_VisitorList()
                {
                    VisitorId  = v.VisitorId,
                    VisAvatar  = u.Avatar,
                    VisName    = u.NickName,
                    CreateDate = v.CreateDate,
                    Uid        = v.Uid
                }).ToList();
                model.ResultInfo = res;
                //获取所有
                res.PmsListNew = db.Queryable <BBS_PMS>()
                                 .Where(it => it.Msgtoid == _userInfo.Id)
                                 .OrderBy(it => it.Postdatetime, OrderByType.Desc).Take(100).ToList();
            });
            return(Json(model, JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        /// Gets a single document for the supplied key
        /// </summary>
        /// <param name="contentType"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public IndexResult <object> GetDocumentById(Type contentType, string id)
        {
            var directory = GetDirectory(contentType.Name);
            IndexResult <object> indexResult = null;

            try
            {
                using (var indexReader = DirectoryReader.Open(directory))
                {
                    var indexSearcher = new IndexSearcher(indexReader);

                    var query = new TermQuery(new Term(GetKeyName(contentType), id));
                    var hits  = indexSearcher.Search(query, _luceneConfig.BatchSize);

                    var doc            = indexSearcher.Doc(hits.ScoreDocs[0].Doc);
                    var mappedDocument = _mapper.Map(doc, contentType);
                    indexResult = new IndexResult <object>
                    {
                        Hit   = mappedDocument,
                        Score = hits.ScoreDocs[0].Score
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Could not get document for id {0} and content type", id, contentType.Name);
            }

            return(indexResult);
        }
Пример #8
0
        static void TestCase2()
        {
            List <string> docsToIndex      = DocumentsToIndex("./TestCases/2/");
            List <string> queriesToProcess = QueriesToProcess("./TestCases/2/");
            ParseOptions  options          = new ParseOptions();

            // load documents
            foreach (string curr in docsToIndex)
            {
                byte[]         data   = Common.ReadBinaryFile(curr);
                SourceDocument src    = new SourceDocument("test", "test", curr, curr, null, DocType.Json, null, "application/json", data.Length, Common.Md5(data));
                IndexResult    result = _IndexClient.Add(src, data, options, true).Result;
                Console.WriteLine("");
                Console.WriteLine("Add: " + curr);
                Console.WriteLine(Common.SerializeJson(result, true));
            }

            Console.WriteLine("");
            Console.WriteLine("Press ENTER to continue");
            Console.ReadLine();

            // execute queries
            foreach (string curr in queriesToProcess)
            {
                EnumerationQuery  query  = Common.DeserializeJson <EnumerationQuery>(Common.ReadBinaryFile(curr));
                EnumerationResult result = _IndexClient.Enumerate(query);
                Console.WriteLine("");
                Console.WriteLine("Query: " + curr);
                Console.WriteLine(Common.SerializeJson(result, true));
            }
        }
Пример #9
0
        private static void IndexTweet(Tweet tweet, string id, ElasticConnection connection, JsonNetSerializer serializer)
        {
            /*
             * $ curl -XPUT 'http://localhost:9200/twitter/tweet/1?pretty=true' -d '{
             *       "User" : "testUser",
             *       "Message" : "trying out Elastic Search"
             *   }'
             */

            // This is url that will be requested from ES. We can grab it and put to any ES admin console (like ElasticHead) to debug ES behavior.
            string indexCommand = Commands.Index(index: "twitter", type: "tweet", id: id)
                                  .Refresh(true)
                                  .Pretty(); // this will generate: twitter/tweet/1?pretty=true

            // This variable contains JSON of serialized tweet, thus we can check if our object serialized correctly
            // or use it directly in ES admin console.
            string tweetJson = serializer.ToJson(tweet);

            var result = connection.Put(indexCommand, tweetJson);

            // Parse index result.
            IndexResult indexResult = serializer.ToIndexResult(result);


            PrintIndexCommand(result, indexResult, indexCommand, tweetJson);
        }
Пример #10
0
        public IndexResult AddGeneralIndex(GeneralDTO general)
        {
            if (general.GeneralID == null)
            {
                return(new IndexResult());
            }
            if (Exists <EntityDocument>(general.GeneralID.Value, DocumentIndexTypeToken.Entity))
            {
                if (_profile.Initialized)
                {
                    _log.WarnFormat("CANNOT PROCESS '{0}CreatedMessage' FOR ENTITY #{1} - '{2}'. ENTITY HAS ALREADY BEEN ADDED ON PROFILE INITIALIZATION OR ENTITY CREATION !!!", general.EntityTypeName, general.GeneralID.GetValueOrDefault(), general.Name);
                }
                else
                {
                    _log.ErrorFormat("CANNOT PROCESS '{0}CreatedMessage' FOR ENTITY #{1} - '{2}'. ENTITY HAS ALREADY BEEN ADDED !!!", general.EntityTypeName, general.GeneralID.GetValueOrDefault(), general.Name);
                }
                return(new IndexResult());
            }
            IDocumentIndex entityIndex = _documentIndexProvider.GetOrCreateDocumentIndex(_pluginContext.AccountName, DocumentIndexTypeToken.Entity);
            EntityDocument document    = _documentFactory.CreateGeneral(general);
            IndexResult    indexResult = document == null ? new IndexResult() : entityIndex.Index(document, false);

            if (indexResult.DocNumber != -1)
            {
                IDocumentIndex projectContextIndex = _documentIndexProvider.GetOrCreateDocumentIndex(_pluginContext.AccountName, DocumentIndexTypeToken.EntityProject);
                projectContextIndex.Index(indexResult.DocNumber, _documentIdFactory.EncodeProjectId(general.ParentProjectID));
                Maybe <string> maybeEntityTypeName = _entityTypeProvider.GetEntityTypeName(general.EntityTypeID);
                string         entityTypeName      = maybeEntityTypeName.FailIfNothing(() => new ApplicationException("Entity type name was not found {0}".Fmt(general.EntityTypeID)));
                IDocumentIndex entityTypeIndex     = _documentIndexProvider.GetOrCreateDocumentIndex(_pluginContext.AccountName, DocumentIndexTypeToken.EntityType);
                entityTypeIndex.Index(indexResult.DocNumber, entityTypeName);
            }
            _log.Debug(string.Format("Added {0} #{1} - '{2}':{3}", general.EntityTypeName, general.GeneralID.GetValueOrDefault(), general.Name, indexResult.WordsAdded.Any() ? string.Format(" added words - {0};", string.Join(",", indexResult.WordsAdded.Keys)) : " NO WORDS ADDED;"));
            return(indexResult);
        }
Пример #11
0
        private void describe_AddAsync()
        {
            var          userId = Guid.NewGuid();
            const string email  = "*****@*****.**";

            context["when index does not contain email"] = () =>
            {
                before = () => _result = _sut.AddAsync(email, userId).Result;

                it["returns EmailAccepted"] = () => _result.should_be(IndexResult.EmailAccepted);
                it["is idempotent"]         = () =>
                {
                    _result = _sut.AddAsync(email, userId).Result;
                    _result.should_be(IndexResult.EmailAccepted);
                };
            };

            context["email has been associated with another user"] = () =>
            {
                before = () =>
                {
                    _sut.AddAsync(email, userId).Wait();
                    _result = _sut.AddAsync(email, Guid.NewGuid()).Result;
                };

                it["returns EmailRejected"] = () => _result.should_be(IndexResult.EmailRejected);
            };
        }
        /// <summary>
        ///     Go to forum index, or a subforum
        /// </summary>
        public ActionResult Index(IndexResult model)
        {
            var db = new ZkDataContext();

            model = model ?? new IndexResult();

            model.Categories = db.ForumCategories.Where(x => x.ParentForumCategoryID == model.CategoryID).OrderBy(x => x.SortOrder);

            model.CurrentCategory = db.ForumCategories.FirstOrDefault(x => x.ForumCategoryID == model.CategoryID);
            model.Path            = model.CurrentCategory?.GetPath() ?? new List <ForumCategory>();

            var threads = db.ForumThreads.AsQueryable();

            if (model.CategoryID != null)
            {
                threads = threads.Where(x => x.ForumCategoryID == model.CategoryID);
            }
            else
            {
                threads = threads.Where(x => x.ForumCategory.ForumMode != ForumMode.Archive);
            }

            threads = threads.Where(x => x.RestrictedClanID == null || x.RestrictedClanID == Global.ClanID);

            int?filterAccountID = null;

            if (!string.IsNullOrEmpty(model.User))
            {
                filterAccountID =
                    (db.Accounts.FirstOrDefault(x => x.Name == model.User) ?? db.Accounts.FirstOrDefault(x => x.Name.ToLower().Contains(model.User)))?.AccountID;
            }
            if (filterAccountID.HasValue)
            {
                threads = threads.Where(x => x.CreatedAccountID == filterAccountID || x.ForumPosts.Any(y => y.AuthorAccountID == filterAccountID));
            }


            if (model.OnlyUnread && Global.IsAccountAuthorized)
            {
                threads                       = from t in threads
                                     let read = t.ForumThreadLastReads.FirstOrDefault(x => x.AccountID == Global.AccountID)
                                                let readForum = t.ForumCategory.ForumLastReads.FirstOrDefault(x => x.AccountID == Global.AccountID)
                                                                where (read == null || t.LastPost > read.LastRead) && (readForum == null || t.LastPost > readForum.LastRead)
                                                                select t;
            }

            if (!string.IsNullOrEmpty(model.Search))
            {
                var threadList =
                    Global.ForumPostIndexer.FilterPosts(db.ForumPosts, model.Search).Select(x => x.ForumThreadID).Distinct().Take(1000).ToList();
                threads = threads.Where(x => x.Title.Contains(model.Search) || x.WikiKey.Contains(model.Search) || threadList.Contains(x.ForumThreadID));
            }

            model.Threads = threads.OrderByDescending(x => x.ForumCategoryID == model.CategoryID && x.IsPinned).ThenByDescending(x => x.LastPost);

            return(View("ForumIndex", model));
        }
Пример #13
0
 private static void PrintIndexResult(IndexResult indexResult)
 {
     Console.WriteLine("Index Results:");
     Console.WriteLine(" _index: " + indexResult._index);
     Console.WriteLine(" _type: " + indexResult._type);
     Console.WriteLine(" _id: " + indexResult._id);
     Console.WriteLine(" _version: " + indexResult._version);
     Console.WriteLine();
 }
Пример #14
0
        static void UpdateBook1(string newTitle)
        {
            WriteLine("* Updating book 1");
            ITypeUpdate <Book>  updater = client.Update <Book>(1);
            ITypeUpdated <Book> command = updater.Field(x => x.Title, newTitle);
            IndexResult         result  = command.Execute();

            OutputIndexResult(result);
            WriteLine();
        }
Пример #15
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public IndexResult getIndexResult()
        {
            IndexResult indexR = new IndexResult()
            {
                pageIndexTotal = Indexs,
                pageWordsCount = Words
            };

            return(indexR);
        }
Пример #16
0
        static void ReplaceBook1(string newTitle)
        {
            WriteLine("* Replacing book 1");
            Book book = client.Get <Book>(1);

            book.Title = newTitle;
            IndexResult result = client.Index(book, x => x.Refresh = true);

            OutputIndexResult(result);
            WriteLine();
        }
Пример #17
0
        private static void PrintIndexCommand(OperationResult result, IndexResult indexResult, string indexCommand, string data)
        {
            Console.WriteLine("Executed: \r\nPUT {0} \r\n{1} \r\n".F(indexCommand, data));

            Console.WriteLine("Index Results \r\n{0} \r\n".F(result));

            Console.WriteLine("Parsed Index Results");
            Console.WriteLine(" _index: " + indexResult._index);
            Console.WriteLine(" _type: " + indexResult._type);
            Console.WriteLine(" _id: " + indexResult._id);
            Console.WriteLine(" _version: " + indexResult._version);
            Console.WriteLine();
        }
Пример #18
0
        public override void PerformSynchronizationForItem(Guid primaryKey)
        {
            base.ExecuteMethod("PerformSynchronizationForItem", delegate()
            {
                Account domainModel = this.API.Direct.Accounts.GetById(primaryKey);
                if (domainModel != null)
                {
                    Action <Guid, bool, DateTime, string> synchronizationUpdateMethod = this.API.Direct.Accounts.SynchronizationUpdate;
                    if (this.API.Integration.SettingsResolver.IsHydrate())
                    {
                        synchronizationUpdateMethod = this.API.Direct.Accounts.SynchronizationHydrateUpdate;
                    }
                    DateTime syncDate = DateTime.UtcNow;
                    if (domainModel.sync_invalid_utc.HasValue)
                    {
                        syncDate = domainModel.sync_invalid_utc.Value;
                    }
                    try
                    {
                        sdk.Account sdkModel = domainModel.ToSDKModel();

                        this.HydrateSDKModelComputed(domainModel, sdkModel);
                        this.HydrateSDKModel(domainModel, sdkModel);

                        if (domainModel.deleted_utc.HasValue)
                        {
                            this.API.Index.Accounts.DeleteDocument(sdkModel);
                            synchronizationUpdateMethod(domainModel.account_id, true, syncDate, null);
                        }
                        else
                        {
                            IndexResult result = this.API.Index.Accounts.UpdateDocument(sdkModel);
                            if (result.success)
                            {
                                synchronizationUpdateMethod(domainModel.account_id, true, syncDate, result.ToString());
                            }
                            else
                            {
                                throw new Exception(result.ToString());
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        this.IFoundation.LogError(ex, "PerformSynchronizationForItem");
                        HealthReporter.Current.UpdateMetric(HealthTrackType.Each, string.Format(HealthReporter.INDEXER_ERROR_SYNC, this.EntityName), 0, 1);
                        synchronizationUpdateMethod(primaryKey, false, syncDate, CoreUtility.FormatException(ex));
                    }
                }
            });
        }
Пример #19
0
        public ActionResult Index()
        {
            if (base.IsLogin == false)
            {
                return(this.Redirect("~/Ask"));
            }
            IndexResult model = new IndexResult();

            _service.Command <IndexResult, ResultModel <IndexResult> >((db, api) =>
            {
                model = api.Get(Url.Action("GetIndexModel"), null).ResultInfo;
            });
            return(View(model));
        }
Пример #20
0
        private void UpdateSql(WebPage webPage)
        {
            using (var context = new SqlDatabase(SqlConnectionString))
            {
                var dbRecord = context.IndexResults.FirstOrDefault(x => x.Id == webPage.Id);

                if (dbRecord != null)
                {
                    dbRecord.Description = webPage.Description;
                    dbRecord.Host        = webPage.Host;

                    dbRecord.IsActive         = true;
                    dbRecord.Keywords         = webPage.Keywords;
                    dbRecord.LastModifiedDate = webPage.LastModifiedDate;
                    dbRecord.Path             = webPage.Path;
                    dbRecord.TextContent      = webPage.Content;
                    dbRecord.Title            = webPage.Title;
                    dbRecord.Query            = webPage.Query;
                    dbRecord.Category         = webPage.Category;
                    dbRecord.SubCategory      = webPage.SubCategory;
                    dbRecord.Hash             = webPage.Id;

                    context.Entry(dbRecord).State = System.Data.Entity.EntityState.Modified;
                    context.SaveChanges();
                }
                else
                {
                    var index = new IndexResult
                    {
                        Id               = webPage.Id,
                        Description      = webPage.Description,
                        Host             = webPage.Host,
                        IsActive         = true,
                        Keywords         = webPage.Keywords,
                        LastModifiedDate = webPage.LastModifiedDate,
                        Path             = webPage.Path,
                        TextContent      = webPage.Content,
                        Title            = webPage.Title,
                        Url              = webPage.Url,
                        Query            = webPage.Query,
                        Category         = webPage.Category,
                        SubCategory      = webPage.SubCategory,
                        Hash             = webPage.Id
                    };

                    context.IndexResults.Add(index);
                    context.SaveChanges();
                }
            }
        }
		public ActionResult Index(int? categoryID, int? page = null)
		{
			var db = new ZkDataContext();
			var res = new IndexResult();

			res.Categories = db.ForumCategories.Where(x => x.ParentForumCategoryID == categoryID).OrderBy(x => x.SortOrder);

			res.Path = GetCategoryPath(categoryID, db);
			res.CurrentCategory = res.Path.LastOrDefault();

            var threads = db.ForumThreads.Where(x => x.ForumCategoryID == categoryID).OrderByDescending(x => x.IsPinned).ThenByDescending(x => x.LastPost);
            res.Page = page ?? 0;
            res.PageCount = ((threads.Count() - 1) / PageSize) + 1;
            res.Threads = threads.Skip((page ?? 0) * PageSize).Take(PageSize).ToList();

			return View(res);
		}
        /// <summary>
        ///     Go to forum index, or a subforum
        /// </summary>
        public ActionResult Index(IndexResult model) {
            var db = new ZkDataContext();
            model = model ?? new IndexResult();

            model.Categories = db.ForumCategories.Where(x => x.ParentForumCategoryID == model.CategoryID).OrderBy(x => x.SortOrder);

            model.CurrentCategory = db.ForumCategories.FirstOrDefault(x => x.ForumCategoryID == model.CategoryID);
            model.Path = model.CurrentCategory?.GetPath() ?? new List<ForumCategory>();

            var threads = db.ForumThreads.AsQueryable();

            if (model.CategoryID != null) threads = threads.Where(x => x.ForumCategoryID == model.CategoryID);
            else threads = threads.Where(x => x.ForumCategory.ForumMode != ForumMode.Archive);

            threads = threads.Where(x => x.RestrictedClanID == null || x.RestrictedClanID == Global.ClanID);

            int? filterAccountID = null;
            if (!string.IsNullOrEmpty(model.User))
            {
                filterAccountID =
                    (db.Accounts.FirstOrDefault(x => x.Name == model.User) ?? db.Accounts.FirstOrDefault(x => x.Name.ToLower().Contains(model.User)))?.AccountID;
            }
            if (filterAccountID.HasValue) threads = threads.Where(x => x.CreatedAccountID == filterAccountID || x.ForumPosts.Any(y => y.AuthorAccountID == filterAccountID));

            
            if (model.OnlyUnread && Global.IsAccountAuthorized)
            {
                threads = from t in threads
                    let read = t.ForumThreadLastReads.FirstOrDefault(x => x.AccountID == Global.AccountID)
                    let readForum = t.ForumCategory.ForumLastReads.FirstOrDefault(x => x.AccountID == Global.AccountID)
                    where (read == null || t.LastPost > read.LastRead) && (readForum == null || t.LastPost > readForum.LastRead)
                    select t;
            }

            if (!string.IsNullOrEmpty(model.Search))
            {
                var threadList =
                    Global.ForumPostIndexer.FilterPosts(db.ForumPosts, model.Search).Select(x => x.ForumThreadID).Distinct().Take(1000).ToList();
                threads = threads.Where(x => x.Title.Contains(model.Search) || x.WikiKey.Contains(model.Search) || threadList.Contains(x.ForumThreadID));
            }

            model.Threads = threads.OrderByDescending(x => x.ForumCategoryID == model.CategoryID && x.IsPinned).ThenByDescending(x => x.LastPost);

            return View("ForumIndex", model);
        }
Пример #23
0
        static void Main(string[] args)
        {
            string directoryToIndex = @"X:\FilesToIndex";

            long workingSet = Process.GetCurrentProcess().WorkingSet64;

            var indexer = new Indexer(new IndexerOptions {
                ApplyPorterStemming = false, RemoveStopWord = false
            });

            //IndexResult result = indexer.IndexFiles(directoryToIndex);
            //workingSet = Process.GetCurrentProcess().WorkingSet64;
            //Console.WriteLine("Index files without porter stemming or removal of stop words:");
            //Console.WriteLine("Time taken: " + result.TimeTaken);
            //Console.WriteLine("Words indexed: " + result.IndexedWordCount);
            //Console.WriteLine("Memory usage(MB): " + ConvertBytesToMegabytes(workingSet));
            //Console.WriteLine(string.Empty);

            indexer = new Indexer(new IndexerOptions {
                ApplyPorterStemming = true, RemoveStopWord = true
            });
            IndexResult result = indexer.IndexFiles(directoryToIndex);

            workingSet = Process.GetCurrentProcess().WorkingSet64;
            Console.WriteLine("Index files with porter stemming and removal of stop words:");
            Console.WriteLine("Time taken: " + result.TimeTaken);
            Console.WriteLine("Words indexed: " + result.IndexedWordCount);
            Console.WriteLine("Memory usage(MB): " + ConvertBytesToMegabytes(workingSet));

            Searcher searcher = new Searcher();

            while (true)
            {
                Console.WriteLine("Search index:");
                SearchResult searchResult = searcher.SearchIndex(new SearchRequest {
                    Index = indexer.Index, SearchTerm = Console.ReadLine(), MaxResults = 1
                });

                foreach (var r in searchResult.Results)
                {
                    Console.WriteLine("File Name: " + r.Item1 + " Count: " + r.Item2);
                    Console.WriteLine("Time taken to search: " + searchResult.TimeTaken.Milliseconds + "ms");
                }
            }
        }
        /// <summary>
        /// Go to forum index, or a subforum
        /// </summary>
        /// <param name="categoryID">Subforum category ID</param>
        /// <param name="page">Page of subforum (i.e. display older threads)</param>
        public ActionResult Index(int?categoryID, int?page = null)
        {
            var db  = new ZkDataContext();
            var res = new IndexResult();

            res.Categories = db.ForumCategories.Where(x => x.ParentForumCategoryID == categoryID).OrderBy(x => x.SortOrder);

            res.Path            = GetCategoryPath(categoryID, db);
            res.CurrentCategory = res.Path.LastOrDefault();

            var threads = db.ForumThreads.Where(x => x.ForumCategoryID == categoryID).OrderByDescending(x => x.IsPinned).ThenByDescending(x => x.LastPost);

            res.Page      = page ?? 0;
            res.PageCount = ((threads.Count() - 1) / PageSize) + 1;
            res.Threads   = threads.Skip((page ?? 0) * PageSize).Take(PageSize).ToList();

            return(View(res));
        }
Пример #25
0
        public ActionResult Index(int?categoryID, int?page = null)
        {
            var db  = new ZkDataContext();
            var res = new IndexResult();

            res.Categories = db.ForumCategories.Where(x => Equals(x.ParentForumCategoryID, categoryID)).OrderBy(x => x.SortOrder);

            res.Path            = GetCategoryPath(categoryID, db);
            res.CurrentCategory = res.Path.LastOrDefault();

            //if (res.CurrentCategory != null && res.CurrentCategory.IsMissions) res.Threads = db.ForumThreads.Where(x => Equals(x.ForumCategoryID, categoryID) && !Global.IsLimitedMode || x.Missions.ModRapidTag.StartsWith("zk:")).OrderByDescending(x => x.LastPost);
            //else
            var threads = db.ForumThreads.Where(x => Equals(x.ForumCategoryID, categoryID)).OrderByDescending(x => x.IsPinned).ThenByDescending(x => x.LastPost);

            res.Page      = page ?? 0;
            res.PageCount = ((threads.Count() - 1) / PageSize) + 1;
            res.Threads   = threads.Skip((page ?? 0) * PageSize).Take(PageSize).ToList();

            return(View(res));
        }
Пример #26
0
        static void AddDocument()
        {
            string indexName = InputString("Index name:", null, true);

            if (String.IsNullOrEmpty(indexName))
            {
                return;
            }

            string docName = InputString("Document name:", null, true);

            if (String.IsNullOrEmpty(docName))
            {
                return;
            }

            string  sourceUrl  = InputString("Source URL:", null, true);
            DocType docType    = GetDocType();
            string  title      = InputString("Title:", null, true);
            string  tagsStr    = InputString("Tags CSV:", null, true);
            string  sourceFile = InputString("Filename:", "", true);

            byte[] data = null;
            if (!String.IsNullOrEmpty(sourceFile))
            {
                data = File.ReadAllBytes(sourceFile);
            }

            List <string> tags = new List <string>();

            if (!String.IsNullOrEmpty(tagsStr))
            {
                tags = CsvToStringList(tagsStr);
            }
            IndexResult resp = _Sdk.AddDocument(indexName, docName, Guid.NewGuid().ToString(), sourceUrl, title, docType, data, KomodoCommon.CsvToStringList(tagsStr)).Result;

            if (resp != null)
            {
                Console.WriteLine(SerializeJson(resp, true));
            }
        }
Пример #27
0
        private static string GetAccurateReccomend(IndexResult indexResult, double index, double height, double weight)
        {
            var    reccomend = "";
            double mas       = 0;
            var    div       = Math.Pow(height / 100, 2);

            switch (indexResult)
            {
            case IndexResult.Low:
                mas       = (18.51 - index) * div;
                reccomend = "Вам необходимо наборать " + mas.ToString("0.00") + " кг";
                break;

            case IndexResult.High:
                mas       = (index - 25) * div;
                reccomend = "Вам необходимо скинуть " + mas.ToString("0.00") + " кг";
                break;
            }
            ;
            return(reccomend);
        }
Пример #28
0
        private static string GetReccomend(IndexResult indexResult)
        {
            var reccomend = "";

            switch (indexResult)
            {
            case IndexResult.Low:
                reccomend = "Дефицит массы тела";
                break;

            case IndexResult.Norm:
                reccomend = "Вес в норме";
                break;

            default:
                reccomend = "Избыточная масса тела";
                break;
            }
            ;
            return(reccomend);
        }
Пример #29
0
        private static bool ShouldRetryWatch(IndexResult result, List <string> indexNames)
        {
            if (!result.Success) // Return on server returned error
            {
                return(false);
            }

            var indexes = result.Value.Where(index => indexNames.Contains(index.Name)).ToList();

            if (!indexes.Any()) // Didn't recognise any index names to watch
            {
                return(false);
            }

            foreach (var index in indexes)
            {
                Log.DebugFormat("Index '{0}' is '{1}'", index.Name, index.State); // eg "Index 'foo' is 'online'"
            }

            return(indexes.Any(index => index.State != "online"));
        }
Пример #30
0
        static async void AddDoc()
        {
            string indexName  = Common.InputString("Index name  :", null, false);
            string sourceGuid = Common.InputString("Source GUID :", null, false);

            byte[]         data      = BuildData();
            SourceDocument sourceDoc = BuildSourceDocument();
            bool           parse     = Common.InputBoolean("Parse:", true);
            ParseOptions   options   = new ParseOptions();

            IndexResult result = await _Komodo.AddDocument(indexName, sourceDoc, data, options, parse);

            if (result == null)
            {
                Console.WriteLine("(none)");
            }
            else
            {
                Console.WriteLine(Common.SerializeJson(result, true));
            }
        }
Пример #31
0
        private static IndexResult Merge(IndexResult left, IndexResult right)
        {
            if (left.DocNumber != right.DocNumber)
            {
                throw new ApplicationException("Inconsistent index results");
            }
            var wordsAdded = new Dictionary <string, int>(left.WordsAdded);

            foreach (var w in right.WordsAdded)
            {
                wordsAdded.Add(w.Key, w.Value);
            }
            var wordsRemoved = new List <string>(left.WordsRemoved);

            wordsRemoved.AddRange(right.WordsRemoved);
            return(new IndexResult
            {
                DocNumber = left.DocNumber,
                WordsAdded = wordsAdded,
                WordsRemoved = wordsRemoved
            });
        }
Пример #32
0
        static void StoreDocument()
        {
            string indexName = InputString("Index name:", null, true);

            if (String.IsNullOrEmpty(indexName))
            {
                return;
            }

            string  sourceUrl  = InputString("Source URL:", null, true);
            DocType docType    = GetDocType();
            string  title      = InputString("Title:", null, true);
            string  tagsStr    = InputString("Tags CSV:", null, true);
            string  sourceFile = InputString("Filename:", "order1.json", true);

            byte[] data = null;

            if (!String.IsNullOrEmpty(sourceFile))
            {
                data = File.ReadAllBytes(sourceFile);
            }

            List <string> tags = new List <string>();

            if (!String.IsNullOrEmpty(tagsStr))
            {
                tags = CsvToStringList(tagsStr);
            }

            IndexResult resp = _Sdk.StoreDocument(indexName, sourceUrl, title, tags, docType, data).Result;

            if (resp != null)
            {
                Console.WriteLine(SerializeJson(resp, true));
            }
        }
        private static bool ShouldRetryWatch(IndexResult result, List<string> indexNames)
        {
            if (!result.Success) // Return on server returned error
            {
                return false;
            }

            var indexes = result.Value.Where(index => indexNames.Contains(index.Name)).ToList();
            if (!indexes.Any()) // Didn't recognise any index names to watch
            {
                return false;
            }

            foreach (var index in indexes)
            {
                Log.DebugFormat("Index '{0}' is '{1}'", index.Name, index.State); // eg "Index 'foo' is 'online'"
            }

            return indexes.Any(index => index.State != "online");
        }
        /// <summary>
        /// Go to home page; also updates news read dates
        /// </summary>
		public ActionResult Index()
		{
            if (Request[GlobalConst.ASmallCakeCookieName] != null)
            {
                return RedirectToAction("Index", new {});
            }
			var db = new ZkDataContext();

		    var prevMonth = DateTime.UtcNow.AddMonths(-1);
			var result = new IndexResult()
			             {
			             	Spotlight = SpotlightHandler.GetRandom(),
			             	Top10Players =
			             		db.Accounts.Where(x => x.SpringBattlePlayers.Any(y => y.SpringBattle.StartTime > prevMonth)).OrderByDescending(
			             			x => x.Elo1v1).Take(10)
			             };

			result.LobbyStats = GetCachedLobbyStats();
			result.News = db.News.Where(x => x.Created < DateTime.UtcNow).OrderByDescending(x => x.Created);
			if (Global.Account != null) {
				result.Headlines =
					db.News.Where(
						x => x.Created < DateTime.UtcNow && x.HeadlineUntil != null && x.HeadlineUntil > DateTime.UtcNow && (Global.Account.LastNewsRead == null || ( x.Created > Global.Account.LastNewsRead))).
						OrderByDescending(x => x.Created);

				if (result.Headlines.Any()) {
					db.Accounts.Single(x => x.AccountID == Global.AccountID).LastNewsRead = DateTime.UtcNow;
					db.SubmitChanges();
				}
			} else {
				result.Headlines = new List<News>();
			}


			var accessibleThreads = db.ForumThreads.Where(x => x.RestrictedClanID == null || x.RestrictedClanID == Global.ClanID);
			if (!Global.IsAccountAuthorized) result.NewThreads = accessibleThreads.OrderByDescending(x => x.LastPost).Take(10).Select(x => new NewThreadEntry() { ForumThread = x });
			else
			{
				result.NewThreads = (from t in accessibleThreads
				                     let read = t.ForumThreadLastReads.FirstOrDefault(x => x.AccountID == Global.AccountID)
                                     let readForum = t.ForumCategory.ForumLastReads.FirstOrDefault(x=> x.AccountID == Global.AccountID)
				                     where (read == null || t.LastPost > read.LastRead) && (readForum == null || t.LastPost > readForum.LastRead)
				                     orderby t.LastPost descending
				                     select new NewThreadEntry { ForumThread = t, WasRead = read != null, WasWritten = read != null && read.LastPosted != null }).
					Take(10);
			}

			return View(result);
		}
        /// <summary>
        /// Go to home page; also updates news read dates
        /// </summary>
		public ActionResult Index()
		{
            if (Request[GlobalConst.ASmallCakeCookieName] != null)
            {
                return RedirectToAction("Index", new {});
            }
			var db = new ZkDataContext();

		    
            var result = new IndexResult()
			             {
			             	Spotlight = SpotlightHandler.GetRandom(),
			             	Top10Players = MemCache.GetCached("top10",
			             	    () =>
			             	    {
                                     var ladderTimeout = DateTime.UtcNow.AddDays(-GlobalConst.LadderActivityDays);
                                     return db.Accounts.Where(x => x.SpringBattlePlayers.Any(y => y.SpringBattle.StartTime > ladderTimeout && y.SpringBattle.PlayerCount == 2 && y.SpringBattle.HasBots == false && y.EloChange != null && !y.IsSpectator))
                                             .OrderByDescending(x => x.Elo1v1)
                                             .Take(10)
                                             .ToList();

                                 },60*10)
			             };

			result.LobbyStats =  MemCache.GetCached("lobby_stats", GetCurrentLobbyStats, 60*2);

			result.News = db.News.Where(x => x.Created < DateTime.UtcNow).OrderByDescending(x => x.Created);
			if (Global.Account != null) {
				result.Headlines =
					db.News.Where(
						x => x.Created < DateTime.UtcNow && x.HeadlineUntil != null && x.HeadlineUntil > DateTime.UtcNow && (Global.Account.LastNewsRead == null || ( x.Created > Global.Account.LastNewsRead))).
						OrderByDescending(x => x.Created);

				if (result.Headlines.Any()) {
					db.Accounts.Single(x => x.AccountID == Global.AccountID).LastNewsRead = DateTime.UtcNow;
				    db.SaveChanges();
				}
			} else {
				result.Headlines = new List<News>();
			}


			var accessibleThreads = db.ForumThreads.Where(x => x.RestrictedClanID == null || x.RestrictedClanID == Global.ClanID);
            accessibleThreads = accessibleThreads.Where(x => x.ForumCategory.ForumMode != ForumMode.Archive);
			if (!Global.IsAccountAuthorized) result.NewThreads = accessibleThreads.OrderByDescending(x => x.LastPost).Take(10).Select(x => new NewThreadEntry() { ForumThread = x });
			else
			{
				result.NewThreads = (from t in accessibleThreads
				                     let read = t.ForumThreadLastReads.FirstOrDefault(x => x.AccountID == Global.AccountID)
                                     let readForum = t.ForumCategory.ForumLastReads.FirstOrDefault(x=> x.AccountID == Global.AccountID)
				                     where (read == null || t.LastPost > read.LastRead) && (readForum == null || t.LastPost > readForum.LastRead)
				                     orderby t.LastPost descending
				                     select new NewThreadEntry { ForumThread = t, WasRead = read != null, WasWritten = read != null && read.LastPosted != null }).
					Take(10);
			}

			return View("HomeIndex",result);
		}
        /// <summary>
        /// Go to home page; also updates news read dates
        /// </summary>
		public ActionResult Index()
		{
			var db = new ZkDataContext();

		    
            var result = new IndexResult()
			             {
			             	Spotlight = SpotlightHandler.GetRandom(),
			             	Top10Players = Global.LadderCalculator.GetLadder().Top50Accounts.Take(10).ToList()
			             };

			result.LobbyStats =  MemCache.GetCached("lobby_stats", GetCurrentLobbyStats, 60*2);

			result.News = db.News.Where(x => x.Created < DateTime.UtcNow).OrderByDescending(x => x.Created);
			if (Global.Account != null) {
				result.Headlines =
					db.News.Where(
						x => x.Created < DateTime.UtcNow && x.HeadlineUntil != null && x.HeadlineUntil > DateTime.UtcNow && (Global.Account.LastNewsRead == null || ( x.Created > Global.Account.LastNewsRead))).
						OrderByDescending(x => x.Created);

				if (result.Headlines.Any()) {
					db.Accounts.Single(x => x.AccountID == Global.AccountID).LastNewsRead = DateTime.UtcNow;
				    db.SaveChanges();
				}
			} else {
				result.Headlines = new List<News>();
			}


			var accessibleThreads = db.ForumThreads.Where(x => x.RestrictedClanID == null || x.RestrictedClanID == Global.ClanID);
            accessibleThreads = accessibleThreads.Where(x => x.ForumCategory.ForumMode != ForumMode.Archive);
			if (!Global.IsAccountAuthorized) result.NewThreads = accessibleThreads.OrderByDescending(x => x.LastPost).Take(10).Select(x => new NewThreadEntry() { ForumThread = x });
			else
			{
				result.NewThreads = (from t in accessibleThreads
				                     let read = t.ForumThreadLastReads.FirstOrDefault(x => x.AccountID == Global.AccountID)
                                     let readForum = t.ForumCategory.ForumLastReads.FirstOrDefault(x=> x.AccountID == Global.AccountID)
				                     where (read == null || t.LastPost > read.LastRead) && (readForum == null || t.LastPost > readForum.LastRead)
				                     orderby t.LastPost descending
				                     select new NewThreadEntry { ForumThread = t, WasRead = read != null, WasWritten = read != null && read.LastPosted != null }).
					Take(10);
			}

			return View("HomeIndex",result);
		}