public void CountersInSelectClauseShouldAffectQueryEtag_CollectionQuery() { using (var store = GetDocumentStore()) { using (var session = store.OpenSession()) { session.Store(new User(), "users/1"); session.CountersFor("users/1").Increment("Downloads", 100); session.SaveChanges(); } using (var session = store.OpenSession()) { var counterValue = session.Query <User>().Select(u => RavenQuery.Counter(u, "Downloads")).First(); Assert.Equal(100, counterValue); } using (var session = store.OpenSession()) { session.CountersFor("users/1").Increment("Downloads", 50); session.SaveChanges(); } using (var session = store.OpenSession()) { // should not be served from cache var counterValue = session.Query <User>().Select(u => RavenQuery.Counter(u, "Downloads")).First(); Assert.Equal(150, counterValue); } } }
public void CountersInSelectClauseShouldAffectQueryEtag_JsProjection_StaticIndexQuery() { using (var store = GetDocumentStore()) { new UsersByName().Execute(store); using (var session = store.OpenSession()) { session.Store(new User { Name = "ayende" }, "users/1"); session.CountersFor("users/1").Increment("Downloads", 100); session.SaveChanges(); } WaitForIndexing(store); using (var session = store.OpenSession()) { var query = session.Query <User, UsersByName>() .Where(u => u.Name == "ayende") .Select(u => new { Name = u.Name + " " + u.LastName, // creates JS projection Counter = RavenQuery.Counter(u, "Downloads") }) .First(); Assert.Equal(100, query.Counter); } using (var session = store.OpenSession()) { session.CountersFor("users/1").Increment("Downloads", 50); session.SaveChanges(); } using (var session = store.OpenSession()) { // should not be served from cache var query = session.Query <User, UsersByName>() .Where(u => u.Name == "ayende") .Select(u => new { Name = u.Name + " " + u.LastName, // creates JS projection Counter = RavenQuery.Counter(u, "Downloads") }) .First(); Assert.Equal(150, query.Counter); } } }
public void Can_Use_RQL_Reserved_Words_As_Field_To_Fetch_And_Select_Counter() { using (var store = GetDocumentStore()) { using (var session = store.OpenSession()) { for (var i = 0; i < 10; i++) { var user = new User { FirstName = "Test", Group = i % 4 }; session.Store(user); session.CountersFor(user).Increment("likes", 100 * i); } session.SaveChanges(); } using (var session = store.OpenSession()) { var query = session.Query <User>() .Select(user => new { user.FirstName, user.Group, Likes = RavenQuery.Counter(user, "likes") }); Assert.Equal("from 'Users' as __alias0 " + "select __alias0.FirstName, " + "__alias0.'Group', " + "counter(__alias0, likes) as Likes" , query.ToString()); var results = query.ToList(); Assert.Equal(10, results.Count); for (var index = 0; index < results.Count; index++) { Assert.Equal("Test", results[index].FirstName); Assert.InRange(results[index].Group, 0, 3); Assert.Equal(index * 100, results[index].Likes); } } } }
public void CountersInSelectClauseShouldAffectQueryEtag_StaticIndexQuery() { using (var store = GetDocumentStore()) { new UsersByName().Execute(store); using (var session = store.OpenSession()) { session.Store(new User { Name = "ayende" }, "users/1"); session.CountersFor("users/1").Increment("Downloads", 100); session.SaveChanges(); } Indexes.WaitForIndexing(store); using (var session = store.OpenSession()) { var counterValue = session.Query <User, UsersByName>() .Where(u => u.Name == "ayende") .Select(u => RavenQuery.Counter(u, "Downloads")) .First(); Assert.Equal(100, counterValue); } using (var session = store.OpenSession()) { session.CountersFor("users/1").Increment("Downloads", 50); session.SaveChanges(); } using (var session = store.OpenSession()) { // should not be served from cache var counterValue = session.Query <User, UsersByName>() .Where(u => u.Name == "ayende") .Select(u => RavenQuery.Counter(u, "Downloads")) .First(); Assert.Equal(150, counterValue); } } }
public void CountersInSelectClauseShouldAffectQueryEtag_JsProjection_CollectionQuery() { using (var store = GetDocumentStore()) { using (var session = store.OpenSession()) { session.Store(new User(), "users/1"); session.CountersFor("users/1").Increment("Downloads", 100); session.SaveChanges(); } using (var session = store.OpenSession()) { var query = session.Query <User>().Select(u => new { Name = u.Name + " " + u.LastName, // creates JS projection Counter = RavenQuery.Counter(u, "Downloads") }).First(); Assert.Equal(100, query.Counter); } using (var session = store.OpenSession()) { session.CountersFor("users/1").Increment("Downloads", 50); session.SaveChanges(); } using (var session = store.OpenSession()) { // should not be served from cache var query = session.Query <User>().Select(u => new { Name = u.Name + " " + u.LastName, // creates JS projection Counter = RavenQuery.Counter(u, "Downloads") }).First(); Assert.Equal(150, query.Counter); } } }
public void DoStuff() { using (var store = GetDocumentStore()) { using (var session = store.OpenSession()) { session.Store(new Address { City = "Kiryat Shmona" }, "addresses/1"); User entity = new User { Name = "foobar", AddressId = "addresses/1" }; session.Store(entity); session.SaveChanges(); session.CountersFor(entity).Increment("Modifications"); session.SaveChanges(); } var subsId = store.Subscriptions.Create <User>(new Raven.Client.Documents.Subscriptions.SubscriptionCreationOptions <User>() { Projection = x => new { Foo = RavenQuery.Counter(x, "Modifications"), x.AddressId } }); var subsWorker = store.Subscriptions.GetSubscriptionWorker(new Raven.Client.Documents.Subscriptions.SubscriptionWorkerOptions(subsId) { CloseWhenNoDocsLeft = true }); subsWorker.Run(x => { Console.WriteLine(x.Items[0].RawResult["Foo"].ToString()); }).Wait(); } }
public async Task SubscriptionsWorksWithCounter() { using (var store = GetDocumentStore()) { using (var session = store.OpenSession()) { User entity = new User { Name = "foobar" }; session.Store(entity); session.CountersFor(entity).Increment("Modifications"); session.SaveChanges(); } var subsId = store.Subscriptions.Create <User>(new Raven.Client.Documents.Subscriptions.SubscriptionCreationOptions <User>() { Projection = x => new { Foo = RavenQuery.Counter(x, "Modifications"), x.AddressId } }); var modificationsValue = 0; var subsWorker = store.Subscriptions.GetSubscriptionWorker(new Raven.Client.Documents.Subscriptions.SubscriptionWorkerOptions(subsId) { CloseWhenNoDocsLeft = true }); await Assert.ThrowsAsync <SubscriptionClosedException>(async() => await subsWorker.Run(x => { modificationsValue = Int32.Parse(x.Items[0].RawResult["Foo"].ToString()); })); Assert.Equal(modificationsValue, 1); } }
static void Main(string[] args) { var docStore = new DocumentStore { Urls = new[] { "http://localhost:8080" }, Database = "products" }; docStore.Initialize(); #region counters_region_CountersFor_with_document_load // Use CountersFor by passing it a document object // 1. Open a session using (var session = docStore.OpenSession()) { // 2. Use the session to load a document. var document = session.Load <Product>("products/1-C"); // 3. Create an instance of `CountersFor` // Pass the document object returned from session.Load as a param. var documentCounters = session.CountersFor(document); // 4. Use `CountersFor` methods to manage the product document's Counters documentCounters.Delete("ProductLikes"); // Delete the "ProductLikes" Counter documentCounters.Increment("ProductModified", 15); // Add 15 to Counter "ProductModified" var counter = documentCounters.Get("DaysLeftForSale"); // Get value of "DaysLeftForSale" // 5. Save the changes to the session session.SaveChanges(); } #endregion #region counters_region_CountersFor_without_document_load // Use CountersFor without loading a document // 1. Open a session using (var session = docStore.OpenSession()) { // 2. pass an explicit document ID to the CountersFor constructor var documentCounters = session.CountersFor("products/1-C"); // 3. Use `CountersFor` methods to manage the product document's Counters documentCounters.Delete("ProductLikes"); // Delete the "ProductLikes" Counter documentCounters.Increment("ProductModified", 15); // Add 15 to Counter "ProductModified" var counter = documentCounters.Get("DaysLeftForSale"); // Get "DaysLeftForSale"'s value // 4. Save changes to the session session.SaveChanges(); } #endregion // remove a counter from a document #region counters_region_Delete // 1. Open a session using (var session = docStore.OpenSession()) { // 2. pass CountersFor's constructor a document ID var documentCounters = session.CountersFor("products/1-C"); // 3. Delete the "ProductLikes" Counter documentCounters.Delete("ProductLikes"); // 4. Save changes to the session session.SaveChanges(); } #endregion // Increment a counter's value #region counters_region_Increment // 1. Open a session using (var session = docStore.OpenSession()) { // 2. pass CountersFor's constructor a document ID var documentCounters = session.CountersFor("products/1-C"); // 3. Use `CountersFor.Increment` documentCounters.Increment("ProductLikes"); // Increase "ProductLikes" by 1, or create it with a value of 1 documentCounters.Increment("ProductDislikes", 1); // Increase "ProductDislikes" by 1, or create it with a value of 1 documentCounters.Increment("ProductPageViews", 15); // Increase "ProductPageViews" by 15, or create it with a value of 15 documentCounters.Increment("DaysLeftForSale", -10); // Decrease "DaysLeftForSale" by 10, or create it with a value of -10 // 4. Save changes to the session session.SaveChanges(); } #endregion // get a counter's value by the counter's name #region counters_region_Get // 1. Open a session using (var session = docStore.OpenSession()) { // 2. pass CountersFor's constructor a document ID var documentCounters = session.CountersFor("products/1-C"); // 3. Use `CountersFor.Get` to retrieve a Counter's value var DaysLeft = documentCounters.Get("DaysLeftForSale"); Console.WriteLine("Days Left For Sale: " + DaysLeft); } #endregion // GetAll #region counters_region_GetAll // 1. Open a session using (var session = docStore.OpenSession()) { // 2. pass CountersFor's constructor a document ID var documentCounters = session.CountersFor("products/1-C"); // 3. Use GetAll to retrieve all of the document's Counters' names and values. var counters = documentCounters.GetAll(); // list counters' names and values foreach (var counter in counters) { Console.WriteLine("counter name: " + counter.Key + ", counter value: " + counter.Value); } } #endregion // playing with GettAll /* * using (var session = docStore.OpenSession()) * { * * // load all objects of a specific database * Console.WriteLine("list all documents in a collection"); * var documentsList = session.Advanced.LoadStartingWith<Product>("products/"); * foreach (var someRecord in documentsList) * { * var documentID = someRecord.Id; * //Console.WriteLine(); * Console.WriteLine("\ndocument ID: " + documentID); * * var document = session.Load<Product>(documentID); // load a document * var documentCounters = session.CountersFor(document); // get the counters for this document * * //list all counters currently attached to a certain object * Console.WriteLine("all counters for this document: "); * var documentCountersArray = documentCounters.GetAll().ToArray(); // gett all counters attached to this document * foreach (var counter in documentCountersArray) * { * Console.WriteLine("counter key: " + counter.Key + ", counter value: " + counter.Value); * } * } * * Console.ReadKey(); * } */ //playing with batch operations /* * using (var session = docStore.OpenSession()) * { * // GetCountersOperation * var getthem = new GetCountersOperation("products/1-C", "c2"); * var resgettem = docStore.Operations.Send(getthem); * Console.WriteLine("tararam2 results " + resgettem?.Counters[0]?.TotalValue); * * * // batch * var docsies = * new List<DocumentCountersOperation>() * { * new DocumentCountersOperation * { * DocumentId = "products/1-C", * Operations = new List<CounterOperation> * { * new CounterOperation {CounterName = "c1", Type = CounterOperationType.Delete }, * new CounterOperation {CounterName = "c2", Type = CounterOperationType.Increment, Delta = -100 }, * new CounterOperation {CounterName = "c3", Type = CounterOperationType.Get }, * } * }, * new DocumentCountersOperation * { * DocumentId = "Users/3", * Operations = new List<CounterOperation> * { * new CounterOperation {CounterName = "u1", Type = CounterOperationType.Delete }, * new CounterOperation {CounterName = "u2", Type = CounterOperationType.Increment, Delta = 0100 }, * new CounterOperation {CounterName = "u3", Type = CounterOperationType.Get }, * } * } * }; * * var counterBatchObject = new CounterBatch(); * counterBatchObject.Documents = docsies; * counterBatchObject.ReplyWithAllNodesValues = true; * * var counterBatchOperationObject = new CounterBatchOperation(counterBatchObject); * * var res = docStore.Operations.Send(counterBatchOperationObject); * foreach (var detail in res.Counters) * { * Console.WriteLine($"name = " + * $"{detail.CounterName}, value = {detail.TotalValue}"); * * Console.WriteLine("values per node: "); * foreach (var nodeValue in detail.CounterValues) * { * Console.WriteLine($"{nodeValue.Key[0]}:{nodeValue.Value}"); * } * * * } * * * Console.ReadKey(); * } */ //Query a collection for documents with a Counter named "ProductLikes" #region counters_region_query using (var session = docStore.OpenSession()) { //Select documents from the "Products" collection, with a Counter named `ProductLikes`. //Querying upon Counter values (e.g. using "Where") is not possible. //In this example the documents that contain the Counter are NOT returned, only Counter values. var query = session.Query <Product>() .Select(product => RavenQuery.Counter(product, "ProductLikes")); var queryResults = query.ToList(); //Show ProductLikes's value, or NULL for documents with no such Counter. foreach (var counterValue in queryResults) { Console.WriteLine("ProductLikes: " + counterValue); } } #endregion //Query a collection for documents with a Counter named "ProductLikes" using (var session = docStore.OpenSession()) { #region counters_region_load_include1 //include single Counters var productPage = session.Load <Product>("products/1-C", includeBuilder => includeBuilder.IncludeCounter("ProductLikes") .IncludeCounter("ProductDislikes") .IncludeCounter("ProductDownloads")); #endregion } using (var session = docStore.OpenSession()) { #region counters_region_load_include2 //include multiple Counters //note that you can combine the inclusion of Counters and documents. var productPage = session.Load <Product>("orders/1-A", includeBuilder => includeBuilder.IncludeDocuments("products/1-C") .IncludeCounters(new[] { "ProductLikes", "ProductDislikes" })); #endregion } using (var session = docStore.OpenSession()) { #region counters_region_query_include_single_Counter //include a single Counter var query = session.Query <Product>() .Include(includeBuilder => includeBuilder.IncludeCounter("ProductLikes")); #endregion } using (var session = docStore.OpenSession()) { #region counters_region_query_include_multiple_Counters //include multiple Counters var query = session.Query <Product>() .Include(includeBuilder => includeBuilder.IncludeCounters(new[] { "ProductLikes", "ProductDownloads" })); #endregion } using (var session = docStore.OpenSession()) { #region counters_region_rawqueries_counter //Various RQL expressions sent to the server using counter() //Returned Counter value is accumulated var rawquery1 = session.Advanced .RawQuery <CounterResult>("from users as u select counter(u, \"ProductLikes\")") .ToList(); var rawquery2 = session.Advanced .RawQuery <CounterResult>("from users select counter(\"ProductLikes\") as ProductLikesCount") .ToList(); var rawquery3 = session.Advanced .RawQuery <CounterResult>("from products where ProductLikes > 500 select ProductSection, counter(\"ProductLikes\")") .ToList(); #endregion #region counters_region_rawqueries_counterRaw //An RQL expression sent to the server using counterRaw() //Returned Counter value is distributed var query = session.Advanced .RawQuery <CounterResultRaw>("from users as u select counterRaw(u, \"downloads\")") .ToList(); #endregion } }
public void CanUseSpacesInCounterAndCompareExchangeNames() { using (var store = GetDocumentStore()) { using (var session = store.OpenSession()) { var company = new Company { Name = "HR" }; session.Store(company, "companies/1"); session.CountersFor(company).Increment("Total Likes", 11); session.SaveChanges(); } using (var session = store.OpenSession(new SessionOptions { TransactionMode = TransactionMode.ClusterWide })) { session.Advanced.ClusterTransaction.CreateCompareExchangeValue("Total Uses", 55); session.SaveChanges(); } using (var session = store.OpenSession()) { Assert.Equal(11, session.CountersFor("companies/1").Get("Total Likes")); } using (var session = store.OpenSession(new SessionOptions { TransactionMode = TransactionMode.ClusterWide })) { Assert.Equal(55, session.Advanced.ClusterTransaction.GetCompareExchangeValue <int>("Total Uses").Value); } using (var session = store.OpenSession()) { var query = session.Query <Company>() .Select(x => new { TotalUses = RavenQuery.CmpXchg <int>("Total Uses") }); var queryAsString = query.ToString(); Assert.Contains("cmpxchg(\"Total Uses\")", queryAsString); var result = query.First(); Assert.Equal(55, result.TotalUses); } using (var session = store.OpenSession()) { var query = session.Query <Company>() .Select(x => new { Name = x.Name + " " + x.Name, TotalLikes = RavenQuery.Counter(x, "Total Likes") }); var queryAsString = query.ToString(); Assert.Contains("counter(x, \"Total Likes\")", queryAsString); var result = query.First(); Assert.Equal(11, result.TotalLikes); } using (var session = store.OpenSession()) { var query = session.Query <Company>() .Select(x => new { TotalLikes = RavenQuery.Counter(x, "Total Likes") }); var queryAsString = query.ToString(); Assert.Contains("counter(x, 'Total Likes')", queryAsString); var result = query.First(); Assert.Equal(11, result.TotalLikes); } } }
static void Main(string[] args) { var docStore = new DocumentStore { Urls = new[] { "http://localhost:8080" }, Database = "products" }; docStore.Initialize(); #region timeseries_region_TimeSeriesFor_with_document_load // Use TimeSeriesFor by passing it a document object // 1. Open a session using (var session = docStore.OpenSession()) { // 2. Use the session to load a document. var document = session.Load <Product>("products/1-C"); // 3. Create an instance of `CountersFor` // Pass the document object returned from session.Load as a param. var documentCounters = session.CountersFor(document); // 4. Use `CountersFor` methods to manage the product document's Counters documentCounters.Delete("ProductLikes"); // Delete the "ProductLikes" Counter documentCounters.Increment("ProductModified", 15); // Add 15 to Counter "ProductModified" var counter = documentCounters.Get("DaysLeftForSale"); // Get value of "DaysLeftForSale" // 5. Save the changes to the session session.SaveChanges(); } #endregion #region timeseries_region_TimeSeriesFor_without_document_load // Use TimeSeriesFor without loading a document // 1. Open a session using (var session = docStore.OpenSession()) { // 2. pass an explicit document ID to the CountersFor constructor var documentCounters = session.CountersFor("products/1-C"); // 3. Use `CountersFor` methods to manage the product document's Counters documentCounters.Delete("ProductLikes"); // Delete the "ProductLikes" Counter documentCounters.Increment("ProductModified", 15); // Add 15 to Counter "ProductModified" var counter = documentCounters.Get("DaysLeftForSale"); // Get "DaysLeftForSale"'s value // 4. Save changes to the session session.SaveChanges(); } #endregion // remove a counter from a document #region counters_region_Delete // 1. Open a session using (var session = docStore.OpenSession()) { // 2. pass CountersFor's constructor a document ID var documentCounters = session.CountersFor("products/1-C"); // 3. Delete the "ProductLikes" Counter documentCounters.Delete("ProductLikes"); // 4. Save changes to the session session.SaveChanges(); } #endregion // Increment a counter's value #region counters_region_Increment // 1. Open a session using (var session = docStore.OpenSession()) { // 2. pass CountersFor's constructor a document ID var documentCounters = session.CountersFor("products/1-C"); // 3. Use `CountersFor.Increment` documentCounters.Increment("ProductLikes"); // Increase "ProductLikes" by 1, or create it with a value of 1 documentCounters.Increment("ProductDislikes", 1); // Increase "ProductDislikes" by 1, or create it with a value of 1 documentCounters.Increment("ProductPageViews", 15); // Increase "ProductPageViews" by 15, or create it with a value of 15 documentCounters.Increment("DaysLeftForSale", -10); // Decrease "DaysLeftForSale" by 10, or create it with a value of -10 // 4. Save changes to the session session.SaveChanges(); } #endregion // get a counter's value by the counter's name #region counters_region_Get // 1. Open a session using (var session = docStore.OpenSession()) { // 2. pass CountersFor's constructor a document ID var documentCounters = session.CountersFor("products/1-C"); // 3. Use `CountersFor.Get` to retrieve a Counter's value var DaysLeft = documentCounters.Get("DaysLeftForSale"); Console.WriteLine("Days Left For Sale: " + DaysLeft); } #endregion // GetAll #region counters_region_GetAll // 1. Open a session using (var session = docStore.OpenSession()) { // 2. pass CountersFor's constructor a document ID var documentCounters = session.CountersFor("products/1-C"); // 3. Use GetAll to retrieve all of the document's Counters' names and values. var counters = documentCounters.GetAll(); // list counters' names and values foreach (var counter in counters) { Console.WriteLine("counter name: " + counter.Key + ", counter value: " + counter.Value); } } #endregion //Query a collection for documents with a Counter named "ProductLikes" #region counters_region_query using (var session = docStore.OpenSession()) { //Select documents from the "Products" collection, with a Counter named `ProductLikes`. //Querying upon Counter values (e.g. using "Where") is not possible. //In this example the documents that contain the Counter are NOT returned, only Counter values. var query = session.Query <Product>() .Select(product => RavenQuery.Counter(product, "ProductLikes")); var queryResults = query.ToList(); //Show ProductLikes's value, or NULL for documents with no such Counter. foreach (var counterValue in queryResults) { Console.WriteLine("ProductLikes: " + counterValue); } } #endregion //Query a collection for documents with a Counter named "ProductLikes" using (var session = docStore.OpenSession()) { #region counters_region_load_include1 //include single Counters var productPage = session.Load <Product>("products/1-C", includeBuilder => includeBuilder.IncludeCounter("ProductLikes") .IncludeCounter("ProductDislikes") .IncludeCounter("ProductDownloads")); #endregion } using (var session = docStore.OpenSession()) { #region counters_region_load_include2 //include multiple Counters //note that you can combine the inclusion of Counters and documents. var productPage = session.Load <Product>("orders/1-A", includeBuilder => includeBuilder.IncludeDocuments("products/1-C") .IncludeCounters(new[] { "ProductLikes", "ProductDislikes" })); #endregion } using (var session = docStore.OpenSession()) { #region counters_region_query_include_single_Counter //include a single Counter var query = session.Query <Product>() .Include(includeBuilder => includeBuilder.IncludeCounter("ProductLikes")); #endregion } using (var session = docStore.OpenSession()) { #region counters_region_query_include_multiple_Counters //include multiple Counters var query = session.Query <Product>() .Include(includeBuilder => includeBuilder.IncludeCounters(new[] { "ProductLikes", "ProductDownloads" })); #endregion } using (var session = docStore.OpenSession()) { #region counters_region_rawqueries_counter //Various RQL expressions sent to the server using counter() //Returned Counter value is accumulated var rawquery1 = session.Advanced .RawQuery <CounterResult>("from products as p select counter(p, \"ProductLikes\")") .ToList(); var rawquery2 = session.Advanced .RawQuery <CounterResult>("from products select counter(\"ProductLikes\") as ProductLikesCount") .ToList(); var rawquery3 = session.Advanced .RawQuery <CounterResult>("from products where PricePerUnit > 50 select Name, counter(\"ProductLikes\")") .ToList(); #endregion #region counters_region_rawqueries_counterRaw //An RQL expression sent to the server using counterRaw() //Returned Counter value is distributed var query = session.Advanced .RawQuery <CounterResultRaw>("from users as u select counterRaw(u, \"downloads\")") .ToList(); #endregion } }
public void ShouldConsiderBothCountersAndCmpXchgInQueryEtagComputation() { using (var store = GetDocumentStore()) { var key = "names/ayende"; using (var session = store.OpenSession()) { session.Store(new User { Name = key }, "users/1"); session.CountersFor("users/1").Increment("downloads", 100); session.SaveChanges(); } // put compare exchange value using (var session = store.OpenSession(new SessionOptions { TransactionMode = TransactionMode.ClusterWide })) { session.Advanced.ClusterTransaction.CreateCompareExchangeValue(key, "Oren"); session.SaveChanges(); } // query based on compare exchange value using (var session = store.OpenSession()) { var query = session.Query <User>() .Select(u => new { CmpXngValue = RavenQuery.CmpXchg <string>(u.Name), CounterValue = RavenQuery.Counter(u, "downloads") }); var result = query.First(); Assert.Equal("Oren", result.CmpXngValue); Assert.Equal(100, result.CounterValue); } // update the compare exchange value using (var session = store.OpenSession(new SessionOptions { TransactionMode = TransactionMode.ClusterWide })) { var cmpxchg = session.Advanced.ClusterTransaction.GetCompareExchangeValue <string>(key); cmpxchg.Value = "Rahien"; session.SaveChanges(); } // verify that the compare exchange value is updated using (var session = store.OpenSession(new SessionOptions { TransactionMode = TransactionMode.ClusterWide })) { var cmpxchg = session.Advanced.ClusterTransaction.GetCompareExchangeValue <string>(key); Assert.Equal("Rahien", cmpxchg.Value); } // re run the query // the query result should not be served from cache using (var session = store.OpenSession()) { var query = session.Query <User>() .Select(u => new { CmpXngValue = RavenQuery.CmpXchg <string>(u.Name), CounterValue = RavenQuery.Counter(u, "downloads") }); var result = query.First(); Assert.Equal("Rahien", result.CmpXngValue); Assert.Equal(100, result.CounterValue); } // increment counter value using (var session = store.OpenSession()) { session.CountersFor("users/1").Increment("downloads", 100); session.SaveChanges(); } // re run the query // the query result should not be served from cache using (var session = store.OpenSession()) { var query = session.Query <User>() .Select(u => new { CmpXngValue = RavenQuery.CmpXchg <string>(u.Name), CounterValue = RavenQuery.Counter(u, "downloads") }); var result = query.First(); Assert.Equal("Rahien", result.CmpXngValue); Assert.Equal(200, result.CounterValue); } } }
public override void RunActualTest() { string randTag1; string randTag2; var dict = new Dictionary <string, (long?LikesCount, long?TotalViews)>(); IRavenQueryable <BlogComment> query; int toUpdateCount; using (var session = DocumentStore.OpenSession()) { ReportInfo("Starting Stream query on BlogComments collection"); // choose 2 different random tags randTag1 = ((CommentTag)Random.Next(0, 9)).ToString(); do { randTag2 = ((CommentTag)Random.Next(0, 9)).ToString(); } while (randTag2 == randTag1); query = session.Query <BlogComment>() .Where(comment => comment.Rating > 50 && comment.Tag.In(new[] { randTag1, randTag2 })); toUpdateCount = query.Count(); if (toUpdateCount == 0) { ReportInfo("Aborting. No BlogComments to update"); return; } ReportInfo("Collecting old counter values by stream query"); var projection = query.Select(c => new { Likes = RavenQuery.Counter("likes"), TotalViews = RavenQuery.Counter("total-views") }); var stream = session.Advanced.Stream(projection); try { while (stream.MoveNext()) { if (stream.Current.Document.Likes == null) { ReportFailure($"Failed on document '{stream.Current.Id}'. " + "Invalid data - counter 'likes' is missing while the parent document has 'Rating' > 0. Aborting", null); } if (stream.Current.Document.TotalViews == null) { ReportFailure($"Failed on document '{stream.Current.Id}'. " + "Invalid data - counter 'total-views' is missing while the parent document has 'Rating' > 0. Aborting", null); } dict.Add(stream.Current.Id, (stream.Current.Document.Likes, stream.Current.Document.TotalViews)); } } catch (Exception e) { ReportFailure("An error occurred during stream query. Aborting. ", e); return; } } // Need wait for non stale .. var script = @"from BlogComments as comment " + $"where comment.Rating > 50 and comment.Tag in('{randTag1}', '{randTag2}')" + @" update { incrementCounter(comment, 'total-views'); incrementCounter(comment, 'likes'); }"; ReportInfo($"Starting PatchByQueryOperation. Number of BlogComments to patch : {toUpdateCount}"); var op = DocumentStore.Operations.Send(new PatchByQueryOperation(script)); try { op.WaitForCompletion(TimeSpan.FromMinutes(1)); } catch (Exception e1) { ReportFailure("An error occurred while waiting for PatchByQueryOperation to complete. Trying again", e1); try { op.WaitForCompletion(TimeSpan.FromMinutes(1)); } catch (Exception e2) { ReportFailure("Failed to complete PatchByQueryOperation after waiting for 2 minutes. Aborting.", e2); return; } } ReportInfo("Finished PatchByQueryOperation on BlogComments. " + "Asserting counter values"); using (var session = DocumentStore.OpenSession()) { var projection = query.Select(c => new { Likes = RavenQuery.Counter("likes"), TotalViews = RavenQuery.Counter("total-views") }); var stream = session.Advanced.Stream(projection); try { while (stream.MoveNext()) { if (dict.TryGetValue(stream.Current.Id, out var oldCounterValues) == false) { // recently added result, skip assertion continue; } if (stream.Current.Document.Likes <= oldCounterValues.LikesCount) { ReportFailure($"Failed on counter 'likes' of document {stream.Current.Id}. " + "Expected old value < new value, but got : " + $"old value = {oldCounterValues.LikesCount}, new value = {stream.Current.Document.Likes}", null); return; } if (stream.Current.Document.TotalViews <= oldCounterValues.TotalViews) { ReportFailure($"Failed on counter 'total-views' of document {stream.Current.Id}. " + "Expected old value < new value, but got : " + $"old value = {oldCounterValues.TotalViews}, new value = {stream.Current.Document.TotalViews}", null); return; } } } catch (Exception e) { ReportFailure("An error occurred during stream query. Aborting. ", e); return; } ReportSuccess("Finished asserting counter values"); } }
public override void RunActualTest() { using (var session = DocumentStore.OpenSession()) { ReportInfo("Started querying docs where Tag in ('Sports', 'Music', 'Tech')"); var query = session.Query <BlogComment>() .Customize(x => x.WaitForNonStaleResults(TimeSpan.FromSeconds(30))) .Where(comment => comment.Tag.In(new[] { "Sports", "Music", "Tech" })) .Select(x => new ProjectionResult { Id = x.Id, Tag = x.Tag, Rating = x.Rating, Likes = RavenQuery.Counter("likes"), Dislikes = RavenQuery.Counter("dislikes"), TotalViews = RavenQuery.Counter("total-views") }); List <ProjectionResult> result; var retries = 3; while (true) { try { result = query.ToList(); break; } catch (Exception e) { if (--retries > 0) { ReportFailure("Encounter an error when trying to query. Trying again. ", e); continue; } ReportFailure("Failed to get query results after 3 tries", e); return; } } if (result.Count == 0) { ReportInfo("No matching results. Aborting"); return; } ReportInfo($"Found {result.Count} matching results. " + "Asserting valid counter values"); foreach (var doc in result) { // assert likes <= total views if (doc.Likes.HasValue && (doc.TotalViews == null || doc.Likes > doc.TotalViews)) { ReportFailure($"Failed on doc {doc.Id} with tag {doc.Tag}. " + "Expected 'likes' <= 'total-views' but got " + $"'likes' : {doc.Likes}, total-views : {doc.TotalViews}.", null); return; } // assert likes <= total views if (doc.Dislikes.HasValue && (doc.TotalViews == null || doc.Dislikes > doc.TotalViews)) { ReportFailure($"Failed on doc {doc.Id} with tag {doc.Tag}. " + "Expected 'dislikes' <= 'total-views' but got " + $"'dislikes' : {doc.Dislikes}, total-views : {doc.TotalViews}.", null); return; } } ReportSuccess("Finished asserting valid counter values"); } }