public GetStoriesResult GetStoriesByUser(string userId, int pageNo = 0, int pageSize = 0)
        {
            if (pageNo > 0 && pageSize < 1) throw new ArgumentException("Must include Page Size with Page No");
            if (pageSize > 0 && pageNo < 1) throw new ArgumentException("Must include Page No with Page Size");

            using (var session = _store.OpenSession())
            {
                var stats = new RavenQueryStatistics();
                var result = session.Query<Story, StoriesByUser>()
                    .Statistics(out stats)
                    .Where(s => s.EditHistory.Any(eh => eh.UserId == userId));

                var Stories = result.ToList<Story>();

                 if (pageNo > 0)
                {
                    result = result.Skip<Story>(pageSize * (pageNo - 1));
                    result = result.Take<Story>(pageSize);
                }

                return new GetStoriesResult
                {
                    Stories = result.ToList<Story>(),
                    IsStale = stats.IsStale
                };

            }
        }
        protected ActionResult FilteredPagedResult(
            RavenQueryStatistics stats
            , IQueryable<Post> query
            , string slug
            , Func<Post, string> resolveSlug)
        {
            ViewBag.Slug = slug;

            var posts = query.ToList();

             // nothing returned by filter, this means that it does not exists!
             // if posts are empty, but TotalResults contains values
             // it means that we are on page that will not display anything
             if (stats.TotalResults == 0)
             {
                 var suggestions = query.Suggest();

                 if (suggestions.Suggestions.Length > 0)
                 {
                     return View("suggest", suggestions.Suggestions);
                 }

                 return HttpNotFound();
             }

            var resolvedSlug = resolveSlug(posts.FirstOrDefault());
            ViewBag.ResolvedSlug = resolvedSlug;
            return PagedResult(stats.TotalResults, posts);
        }
        public static Negotiator WithEtagAndLastModified(this Negotiator negotiator, RavenQueryStatistics stats)
        {
            var currentEtag = stats.IndexEtag.ToString("N");
            var responseLastModified = stats.IndexTimestamp;

            return negotiator
                .WithHeader("ETag", currentEtag)
                .WithHeader("Last-Modified", responseLastModified.ToString("R"));
        }
 public int GetCustomerCount()
 {
     int count = 0;
     using (var documentStore = new DocumentStore() { Url = STORE_URL })
     {
         documentStore.Initialize();
         using (IDocumentSession session = documentStore.OpenSession(STORE_NAME))
         {
             RavenQueryStatistics stats = new RavenQueryStatistics();
             session.Query<Customer>().Statistics(out stats).ToArray();
             count = stats.TotalResults;
         }
     }
     return count;
 }
示例#5
0
 public void GetUserData()
 {
     try
     {
         using (var session = DocumentStore.OpenSession())
         {
             RavenQueryStatistics statistics = new RavenQueryStatistics();
             var response = session.Advanced.LuceneQuery<User>("UserMapReduceIndex").Where("Username: "******"Rabbi102").WaitForNonStaleResultsAsOfLastWrite().Statistics(out statistics).ToList();
         }
     }
     catch (Exception x)
     {
         Console.WriteLine(x);
     }
 }
        private Task<QueryResult> GetQueryResults(int start, int pageSize)
        {
            IndexQuery templateQuery;
            string indexName;

            lock (_lockObject)
            {
                templateQuery = TemplateQuery;
                indexName = _indexName;
            }

            if (templateQuery == null || string.IsNullOrEmpty(indexName))
                return TaskEx.FromResult(new QueryResult());

            var query = templateQuery.Clone();
            query.Start = start;
            query.PageSize = pageSize;

			var queryStartTime = SystemTime.UtcNow.Ticks;
            var queryEndtime = DateTime.MinValue.Ticks;

            return ApplicationModel.DatabaseCommands
                .QueryAsync(indexName,
                            query,
                            new string[] { }, MetadataOnly)
                            .ContinueWith(task =>
                                              {
												  queryEndtime = SystemTime.UtcNow.Ticks;

                                                  var queryTime = new TimeSpan(queryEndtime - queryStartTime);

                                                  RavenQueryStatistics statistics;
                                                  if (!task.IsFaulted)
                                                  {
                                                      statistics = new RavenQueryStatistics
                                                                       {
                                                                           IndexEtag = task.Result.IndexEtag,
                                                                           IndexName = task.Result.IndexName,
                                                                           IndexTimestamp =
                                                                               task.Result.IndexTimestamp,
                                                                           IsStale = task.Result.IsStale,
                                                                           SkippedResults =
                                                                               task.Result.SkippedResults,
																		   Timestamp = SystemTime.UtcNow,
                                                                           TotalResults = task.Result.TotalResults
                                                                       };
                                                  }
                                                  else
                                                  {
													  statistics = new RavenQueryStatistics() { Timestamp = SystemTime.UtcNow };
                                                  }

                                                  OnQueryStatisticsUpdated(new QueryStatisticsUpdatedEventArgs()
                                                                               {
                                                                                   QueryTime = queryTime,
                                                                                   Statistics = statistics
                                                                               });

                                                  if (task.IsFaulted)
                                                  {
                                                      OnQueryError(new QueryErrorEventArgs() { Exception = task.Exception});
                                                  }

                                                  return task.Result;
                                              }, TaskContinuationOptions.ExecuteSynchronously);
        }
 private bool CheckEtag(RavenQueryStatistics stats, out string responseETagHeader)
 {
     string requestETagHeader = Request.Headers["If-None-Match"] ?? string.Empty;
     responseETagHeader = stats.Timestamp.ToString("o") + EtagInitValue;
     return requestETagHeader == responseETagHeader;
 }
        public static Negotiator WithPagingLinks(this Negotiator negotiator, RavenQueryStatistics stats, Request request)
        {
            decimal maxResultsPerPage = 50;

            if (request.Query.per_page.HasValue)
            {
                maxResultsPerPage = request.Query.per_page;
            }

            if (maxResultsPerPage < 1)
            {
                maxResultsPerPage = 50;
            }

            var page = 1;

            if (request.Query.page.HasValue)
            {
                page = request.Query.page;
            }

            if (page < 1)
            {
                page = 1;
            }

            // No need to add a Link header if no paging
            if (stats.TotalResults <= maxResultsPerPage)
            {
                return negotiator;
            }

            var links = new List<string>();
            var lastPage = (int) Math.Ceiling(stats.TotalResults/maxResultsPerPage);

            // No need to add a Link header if page does not exist!
            if (page > lastPage)
            {
                return negotiator;
            }

            var queryParts = HttpUtility.ParseQueryString(request.Url.Query);
            var url = request.Url.Clone();
            var query = new StringBuilder();

            query.Append("?");
            foreach (var key in queryParts.AllKeys.Where(key => key != "page"))
            {
                query.AppendFormat("{0}={1}&", key, queryParts[key]);
            }

            var queryParams = query.ToString();

            if (page != 1)
            {
                AddLink(links, 1, "first", queryParams, url);
            }

            if (page > 1)
            {
                AddLink(links, page - 1, "prev", queryParams, url);
            }

            if (page != lastPage)
            {
                AddLink(links, lastPage, "last", queryParams, url);
            }

            if (page < lastPage)
            {
                AddLink(links, page + 1, "next", queryParams, url);
            }

            return negotiator.WithHeader("Link", String.Join(", ", links));
        }
 public static Negotiator WithTotalCount(this Negotiator negotiator, RavenQueryStatistics stats)
 {
     return negotiator.WithHeader("Total-Count", stats.TotalResults.ToString(CultureInfo.InvariantCulture));
 }
 public static Negotiator WithPagingLinksAndTotalCount(this Negotiator negotiator, RavenQueryStatistics stats,
     Request request)
 {
     return negotiator.WithTotalCount(stats)
         .WithPagingLinks(stats, request);
 }
 public static Negotiator WithRavenQueryStats(this Negotiator negotiator, RavenQueryStatistics stats)
 {
     return negotiator
         .WithHeader("QueryTimeMs", stats.DurationMilliseconds.ToString(CultureInfo.InvariantCulture))
         .WithHeader("IsStale", stats.IsStale.ToString());
 }
        public static Negotiator WithEtagAndLastModified(this Negotiator negotiator, RavenQueryStatistics stats)
        {
            var etag = stats.IndexEtag;
            var responseLastModified = stats.IndexTimestamp;

            return WithEtagAndLastModified(negotiator, etag, responseLastModified);
        }
示例#13
0
 public List<Branch> LoadBranchData()
 {
     var collection = new List<Branch>();
     using (var session = DocumentStore.OpenSession())
     {                
         RavenQueryStatistics statistics = new RavenQueryStatistics();
         collection.AddRange(session.Advanced.LuceneQuery<Branch>("BranchMapReduceIndex").WaitForNonStaleResultsAsOfLastWrite().Statistics(out statistics));
         if (statistics.TotalResults > 128)
         {
             int toTake = statistics.TotalResults - 128;
             int taken = 128;
             int maxRecord = 1024;
             int i = 0;
             while (toTake > 0 && i < 29)
             {
                 collection.AddRange(session.Advanced.LuceneQuery<Branch>("BranchMapReduceIndex").WaitForNonStaleResultsAsOfLastWrite().Statistics(out statistics).Skip(taken).Take(toTake > maxRecord ? maxRecord : toTake));
                 toTake -= maxRecord;
                 taken += maxRecord;
                 i++;
             }
         }
     }
     return collection;
 }
示例#14
0
 public List<User> GetAllUserData(ref int totalUsers, int pageIndex = 0, int maxRecords = 128)
 {
     try
     {
         using (var session = DocumentStore.OpenSession())
         {
             RavenQueryStatistics statistics = new RavenQueryStatistics();
             var response = session.Advanced.LuceneQuery<User>("UserMapReduceIndex").WaitForNonStaleResultsAsOfLastWrite().Statistics(out statistics).Skip(pageIndex * maxRecords).Take(maxRecords).ToList<User>();
             session.Dispose();
             return response;
         }
     }
     catch (Exception x)
     {
         Console.WriteLine(x);
     }
     return null;
 }
        public void CanPerformDynamicQueryUsingClientLinqQueryWithNestedCollection()
        {
            var blogOne = new Blog
            {
                Title    = "one",
                Category = "Ravens",
                Tags     = new[] {
                    new BlogTag()
                    {
                        Name = "Birds"
                    }
                }
            };
            var blogTwo = new Blog
            {
                Title    = "two",
                Category = "Rhinos",
                Tags     = new[] {
                    new BlogTag()
                    {
                        Name = "Mammals"
                    }
                }
            };
            var blogThree = new Blog
            {
                Title    = "three",
                Category = "Rhinos",
                Tags     = new[] {
                    new BlogTag()
                    {
                        Name = "Mammals"
                    }
                }
            };

            using (var store = GetDocumentStore())
            {
                using (var s = store.OpenSession())
                {
                    s.Store(blogOne);
                    s.Store(blogTwo);
                    s.Store(blogThree);
                    s.SaveChanges();
                }

                using (var s = store.OpenSession())
                {
                    var stats   = new Raven.Client.RavenQueryStatistics();
                    var results = s.Query <Blog>()
                                  .Statistics(out stats)
                                  .Customize(x => x.WaitForNonStaleResultsAsOfNow(TimeSpan.FromSeconds(5)))
                                  .Where(x => x.Tags.Any(y => y.Name == "Birds"))
                                  .ToArray();

                    Assert.Equal(1, results.Length);
                    Assert.Equal("one", results[0].Title);
                    Assert.Equal("Ravens", results[0].Category);
                }
            }
        }