public async Task <DynamicArray> GetAsync(int start, int pageSize)
            {
                var command = new GetDocumentCommand(start, pageSize);

                await RequestExecutor.ExecuteAsync(command, Context);

                return(new DynamicArray(command.Result.Results));
            }
Example #2
0
        protected virtual HttpRequestMessage CreateRequest(GetDocumentCommand cmd)
        {
            var req = new HttpRequest(HttpMethod.Get, GenerateRequestUrl(cmd.Id, cmd.Rev));

            req.SetIfMatch(cmd.Rev);

            return(req);
        }
Example #3
0
        public virtual async Task <DocumentResponse> GetAsync(GetDocumentCommand cmd)
        {
            Ensure.That(cmd, "cmd").IsNotNull();

            var req = CreateRequest(cmd);
            var res = SendAsync(req);

            return(ProcessDocumentResponse(await res.ForAwait()));
        }
            public async Task <DynamicArray> GetAsync(string[] ids)
            {
                if (ids == null)
                {
                    throw new ArgumentNullException(nameof(ids));
                }

                var command = new GetDocumentCommand(ids, includes: null, metadataOnly: false);

                await RequestExecutor.ExecuteAsync(command, Context);

                return(new DynamicArray(command.Result.Results));
            }
Example #5
0
        public T Load <T>(string id) where T : new()
        {
            object existingEntity;

            if (IdentityMap.TryGetValue(id, out existingEntity))
            {
                return((T)existingEntity);
            }

            var           getDocumentCommand = new GetDocumentCommand(CouchDatabase.Name, id);
            CouchDocument couchDocument      = CouchDatabase.CouchProxy.Execute <CouchDocument>(getDocumentCommand);

            return(StalkEntity <T>(couchDocument));
        }
Example #6
0
        public async Task RefreshAsync <T>(T entity, CancellationToken token = default(CancellationToken))
        {
            DocumentInfo documentInfo;

            if (DocumentsByEntity.TryGetValue(entity, out documentInfo) == false)
            {
                throw new InvalidOperationException("Cannot refresh a transient instance");
            }
            IncrementRequestCount();

            var command = new GetDocumentCommand(new[] { documentInfo.Id }, includes: null, metadataOnly: false);
            await RequestExecutor.ExecuteAsync(command, Context, token, SessionInfo).ConfigureAwait(false);

            RefreshInternal(entity, command, documentInfo);
        }
Example #7
0
        /// <summary>
        /// Refreshes the specified entity from Raven server.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity">The entity.</param>
        public void Refresh <T>(T entity)
        {
            DocumentInfo documentInfo;

            if (DocumentsByEntity.TryGetValue(entity, out documentInfo) == false)
            {
                throw new InvalidOperationException("Cannot refresh a transient instance");
            }
            IncrementRequestCount();

            var command = new GetDocumentCommand(new[] { documentInfo.Id }, includes: null, metadataOnly: false);

            RequestExecutor.Execute(command, Context, sessionInfo: SessionInfo);

            RefreshInternal(entity, command, documentInfo);
        }
Example #8
0
        public async Task RefreshAsync <T>(T entity, CancellationToken token = default(CancellationToken))
        {
            DocumentInfo documentInfo;

            if (DocumentsByEntity.TryGetValue(entity, out documentInfo) == false)
            {
                throw new InvalidOperationException("Cannot refresh a transient instance");
            }
            IncrementRequestCount();

            var command = new GetDocumentCommand
            {
                Ids     = new[] { documentInfo.Id },
                Context = this.Context
            };
            await RequestExecuter.ExecuteAsync(command, Context, token);

            RefreshInternal(entity, command, documentInfo);
        }
Example #9
0
        /// <summary>
        /// Get command for new client tests
        /// </summary>
        /// <param name="session"></param>
        /// <param name="ids"></param>
        /// <param name="etag"></param>
        /// <param name="documentInfo"></param>
        /// <returns></returns>
        public static BlittableJsonReaderObject GetCommand(IDocumentSession session, string[] ids,
                                                           out DocumentInfo documentInfo)
        {
            var command = new GetDocumentCommand
            {
                Ids     = ids,
                Context = session.Advanced.Context
            };

            if (session.Advanced.RequestExecuter == null)
            {
                Console.WriteLine();
            }
            session.Advanced.RequestExecuter.Execute(command, session.Advanced.Context);
            var document = (BlittableJsonReaderObject)command.Result.Results[0];
            BlittableJsonReaderObject metadata;

            if (document.TryGet(Constants.Metadata.Key, out metadata) == false)
            {
                throw new InvalidOperationException("Document must have a metadata");
            }
            string id;

            if (metadata.TryGet(Constants.Metadata.Id, out id) == false)
            {
                throw new InvalidOperationException("Document must have an id");
            }
            long?etag;

            if (metadata.TryGet(Constants.Metadata.Etag, out etag) == false)
            {
                throw new InvalidOperationException("Document must have an etag");
            }
            documentInfo = new DocumentInfo
            {
                Id       = id,
                Document = document,
                Metadata = metadata,
                ETag     = etag
            };
            return(document);
        }
Example #10
0
        /// <summary>
        /// Refreshes the specified entity from Raven server.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity">The entity.</param>
        public void Refresh <T>(T entity)
        {
            DocumentInfo documentInfo;

            if (DocumentsByEntity.TryGetValue(entity, out documentInfo) == false)
            {
                throw new InvalidOperationException("Cannot refresh a transient instance");
            }
            IncrementRequestCount();

            var command = new GetDocumentCommand
            {
                Ids     = new[] { documentInfo.Id },
                Context = this.Context
            };

            RequestExecuter.Execute(command, Context);

            RefreshInternal(entity, command, documentInfo);
        }
            public async Task <DynamicBlittableJson> GetAsync(string id, bool metadataOnly = false)
            {
                if (id == null)
                {
                    throw new ArgumentNullException(nameof(id));
                }

                var command = new GetDocumentCommand(id, includes: null, metadataOnly: metadataOnly);

                await RequestExecutor.ExecuteAsync(command, Context);

                if (command.Result == null || command.Result.Results.Length == 0)
                {
                    return(null);
                }

                var json = (BlittableJsonReaderObject)command.Result.Results[0];

                return(new DynamicBlittableJson(json));
            }
Example #12
0
        public void IncludeShouldNotReturnDuplicates()
        {
            using (var store = GetDocumentStore())
            {
                string orderId;

                using (var session = store.OpenSession())
                {
                    var employee = new Employee()
                    {
                        FirstName = "John"
                    };

                    session.Store(employee);

                    var order = new Order
                    {
                        Employee = employee.Id
                    };

                    session.Store(order);

                    orderId = order.Id;

                    session.SaveChanges();
                }

                var command = new GetDocumentCommand(new[] { orderId }, new[] { "Employee" }, false);
                using (var commands = store.Commands())
                {
                    commands.RequestExecutor.Execute(command, commands.Context, CancellationToken.None);

                    var result = command.Result;
                    Assert.Equal(1, result.Includes.Count);
                }
            }
        }
Example #13
0
        public async Task IfIncludedDocumentIsConflictedItShouldNotThrowConflictException()
        {
            using (var store1 = GetDocumentStore())
                using (var store2 = GetDocumentStore())
                {
                    using (var session = store1.OpenSession())
                    {
                        session.Store(new Address
                        {
                            City = "New York"
                        }, "addresses/1");
                        session.SaveChanges();
                    }

                    using (var session = store2.OpenSession())
                    {
                        session.Store(new Address
                        {
                            City = "Torun"
                        }, "addresses/1");

                        session.Store(new User
                        {
                            Name      = "John",
                            AddressId = "addresses/1"
                        }, "users/1");

                        session.SaveChanges();
                    }

                    await SetupReplicationAsync(store1, store2);

                    WaitForConflict(store2, "addresses/1");

                    using (var session = store2.OpenSession())
                    {
                        var documentQuery = session.Advanced
                                            .DocumentQuery <User>()
                                            .Include(x => x.AddressId);

                        var iq = documentQuery.GetIndexQuery();

                        var user = documentQuery
                                   .First();

                        Assert.Equal("John", user.Name);

                        Assert.Throws <DocumentConflictException>(() => session.Load <Address>(user.AddressId));

                        using (var commands = store2.Commands())
                        {
                            var qr = commands.Query(iq);

                            var address  = (BlittableJsonReaderObject)qr.Includes["addresses/1"];
                            var metadata = address.GetMetadata();
                            Assert.Equal("addresses/1", metadata.GetId());
                            Assert.True(metadata.TryGetConflict(out var conflict));
                            Assert.True(conflict);
                        }
                    }

                    using (var session = store2.OpenSession())
                    {
                        var user = session
                                   .Include <User>(x => x.AddressId)
                                   .Load("users/1");

                        Assert.Equal("John", user.Name);

                        Assert.Throws <DocumentConflictException>(() => session.Load <Address>(user.AddressId));

                        using (var commands = store2.Commands())
                        {
                            var command = new GetDocumentCommand("users/1", includes: new[] { "AddressId" }, metadataOnly: false);

                            commands.RequestExecutor.Execute(command, commands.Context);

                            var address  = (BlittableJsonReaderObject)command.Result.Includes["addresses/1"];
                            var metadata = address.GetMetadata();
                            Assert.Equal("addresses/1", metadata.GetId());
                            Assert.True(metadata.TryGetConflict(out var conflict));
                            Assert.True(conflict);
                        }
                    }
                }
        }
Example #14
0
        public async Task CanCreateDocumentsIfPatchingAppliedByIndex()
        {
            using (var store = GetDocumentStore())
            {
                using (var session = store.OpenAsyncSession())
                {
                    await session.StoreAsync(new CustomType
                    {
                        Id    = "Item/1",
                        Value = 1
                    });

                    await session.StoreAsync(new CustomType
                    {
                        Id    = "Item/2",
                        Value = 2
                    });

                    await session.SaveChangesAsync();
                }

                JsonOperationContext context;
                store.GetRequestExecuter(store.DefaultDatabase).ContextPool.AllocateOperationContext(out context);

                var putIndexOperation = new PutIndexOperation(context);
                var indexCommand      = putIndexOperation.CreateRequest(store.Conventions, "TestIndex", new IndexDefinition
                {
                    Maps = { @"from doc in docs.CustomTypes 
                                     select new { doc.Value }" }
                });
                if (indexCommand != null)
                {
                    store.GetRequestExecuter(store.DefaultDatabase).Execute(indexCommand, context);
                }



                using (var session = store.OpenAsyncSession())
                {
                    await session.Advanced.AsyncDocumentQuery <CustomType>("TestIndex")
                    .WaitForNonStaleResults()
                    .ToListAsync();
                }

                var patchByIndexOperation = new PatchByIndexOperation(context);
                var patchCommand          = patchByIndexOperation.CreateRequest("TestIndex",
                                                                                new IndexQuery {
                    Query = "Value:1"
                },
                                                                                null, new PatchRequest {
                    Script = @"PutDocument('NewItem/3', {'CopiedValue': this.Value });"
                }, store);
                if (patchCommand != null)
                {
                    store.GetRequestExecuter(store.DefaultDatabase).Execute(patchCommand, context);
                }

                var getDocumentCommand = new GetDocumentCommand
                {
                    Ids     = new[] { "Item/1", "Item/2" },
                    Context = context
                };
                store.GetRequestExecuter(store.DefaultDatabase).Execute(getDocumentCommand, context);

                var results = getDocumentCommand.Result.Results;
                Assert.Equal(2, results.Length);

                getDocumentCommand = new GetDocumentCommand
                {
                    Ids     = new[] { "NewItem/3" },
                    Context = context
                };
                store.GetRequestExecuter(store.DefaultDatabase).Execute(getDocumentCommand, context);

                results = getDocumentCommand.Result.Results;
                Assert.Equal(1, results.Length);
                var    res = (BlittableJsonReaderObject)results[0];
                object obj;
                res.TryGetMember("CopiedValue", out obj);
                Assert.Equal(1, ((Int64)obj));
            }
        }
Example #15
0
        public async Task GetAsync()
        {
            using (var store = GetDocumentStore())
            {
                var dummy = JObject.FromObject(new User());
                dummy.Remove("Id");

                using (var session = store.OpenAsyncSession())
                {
                    await session.StoreAsync(new User { Name = "Fitzchak" }, "users/1");

                    await session.StoreAsync(new User { Name = "Arek" }, "users/2");

                    await session.SaveChangesAsync();
                }

                var requestExecuter = store
                                      .GetRequestExecutor();

                using (requestExecuter.ContextPool.AllocateOperationContext(out JsonOperationContext context))
                {
                    var getDocumentCommand = new GetDocumentCommand(new[] { "users/1", "users/2" }, includes: null, metadataOnly: false);

                    requestExecuter
                    .Execute(getDocumentCommand, context);

                    var docs = getDocumentCommand.Result;
                    Assert.Equal(2, docs.Results.Length);

                    var doc1 = docs.Results[0] as BlittableJsonReaderObject;
                    var doc2 = docs.Results[1] as BlittableJsonReaderObject;

                    Assert.NotNull(doc1);

                    var doc1Properties = doc1.GetPropertyNames();
                    Assert.True(doc1Properties.Contains("@metadata"));
                    Assert.Equal(dummy.Count + 1, doc1Properties.Length); // +1 for @metadata

                    Assert.NotNull(doc2);

                    var doc2Properties = doc2.GetPropertyNames();
                    Assert.True(doc2Properties.Contains("@metadata"));
                    Assert.Equal(dummy.Count + 1, doc2Properties.Length); // +1 for @metadata

                    using (var session = (DocumentSession)store.OpenSession())
                    {
                        var user1 = (User)session.EntityToBlittable.ConvertToEntity(typeof(User), "users/1", doc1);
                        var user2 = (User)session.EntityToBlittable.ConvertToEntity(typeof(User), "users/2", doc2);

                        Assert.Equal("Fitzchak", user1.Name);
                        Assert.Equal("Arek", user2.Name);
                    }

                    getDocumentCommand = new GetDocumentCommand(new[] { "users/1", "users/2" }, includes: null,
                                                                metadataOnly: true);

                    requestExecuter
                    .Execute(getDocumentCommand, context);

                    docs = getDocumentCommand.Result;
                    Assert.Equal(2, docs.Results.Length);

                    doc1 = docs.Results[0] as BlittableJsonReaderObject;
                    doc2 = docs.Results[1] as BlittableJsonReaderObject;

                    Assert.NotNull(doc1);

                    doc1Properties = doc1.GetPropertyNames();
                    Assert.True(doc1Properties.Contains("@metadata"));
                    Assert.Equal(1, doc1Properties.Length);

                    Assert.NotNull(doc2);

                    doc2Properties = doc2.GetPropertyNames();
                    Assert.True(doc2Properties.Contains("@metadata"));
                    Assert.Equal(1, doc2Properties.Length);
                }
            }
        }
Example #16
0
        public async Task CanPerformAdvancedWithSetBasedUpdates()
        {
            using (var store = GetDocumentStore())
            {
                var item1 = new CustomType
                {
                    Id       = "someId/1",
                    Owner    = "bob",
                    Value    = 12143,
                    Comments = new List <string>(new[] { "one", "two", "seven" })
                };
                var item2 = new CustomType
                {
                    Id       = "someId/2",
                    Owner    = "NOT bob",
                    Value    = 9999,
                    Comments = new List <string>(new[] { "one", "two", "seven" })
                };

                using (var session = store.OpenAsyncSession())
                {
                    await session.StoreAsync(item1);

                    await session.StoreAsync(item2);

                    await session.SaveChangesAsync();
                }

                JsonOperationContext context;
                store.GetRequestExecuter(store.DefaultDatabase).ContextPool.AllocateOperationContext(out context);

                var putIndexOperation = new PutIndexOperation(context);
                var indexCommand      = putIndexOperation.CreateRequest(store.Conventions, "TestIndex", new IndexDefinition
                {
                    Maps = { @"from doc in docs.CustomTypes 
                                     select new { doc.Owner }" }
                });
                if (indexCommand != null)
                {
                    store.GetRequestExecuter(store.DefaultDatabase).Execute(indexCommand, context);
                }

                WaitForIndexing(store);
                store.OpenSession().Advanced.DocumentQuery <CustomType>("TestIndex")
                .WaitForNonStaleResults().ToList();

                var patchByIndexOperation = new PatchByIndexOperation(context);
                var patchCommand          = patchByIndexOperation.CreateRequest("TestIndex",
                                                                                new IndexQuery {
                    Query = "Owner:bob"
                },
                                                                                null, new PatchRequest {
                    Script = sampleScript
                }, store);
                if (patchCommand != null)
                {
                    store.GetRequestExecuter(store.DefaultDatabase).Execute(patchCommand, context);
                }

                var getDocumentCommand = new GetDocumentCommand
                {
                    Ids     = new[] { item1.Id },
                    Context = context
                };
                store.GetRequestExecuter(store.DefaultDatabase).Execute(getDocumentCommand, context);

                var results = getDocumentCommand.Result.Results;
                Assert.Equal(1, results.Length);
                var    res = (BlittableJsonReaderObject)results[0];
                object obj;
                res.TryGetMember("Comments", out obj);
                Assert.Equal(2, ((BlittableJsonReaderArray)obj).Length);
                Assert.Equal("one test", ((BlittableJsonReaderArray)obj).GetStringByIndex(0));
                Assert.Equal("two", ((BlittableJsonReaderArray)obj).GetStringByIndex(1));
                res.TryGetMember("Value", out obj);
                Assert.Equal(12144, ((Int64)obj));
                res.TryGetMember("newValue", out obj);
                Assert.Equal("err!!", obj.ToString());


                getDocumentCommand = new GetDocumentCommand
                {
                    Ids     = new[] { item2.Id },
                    Context = context
                };
                store.GetRequestExecuter(store.DefaultDatabase).Execute(getDocumentCommand, context);

                results = getDocumentCommand.Result.Results;
                Assert.Equal(1, results.Length);
                res = (BlittableJsonReaderObject)results[0];
                res.TryGetMember("Comments", out obj);
                Assert.Equal(3, ((BlittableJsonReaderArray)obj).Length);
                Assert.Equal("one", ((BlittableJsonReaderArray)obj).GetStringByIndex(0));
                Assert.Equal("two", ((BlittableJsonReaderArray)obj).GetStringByIndex(1));
                Assert.Equal("seven", ((BlittableJsonReaderArray)obj).GetStringByIndex(2));
                res.TryGetMember("Value", out obj);
                Assert.Equal(9999, ((Int64)obj));
            }
        }
Example #17
0
 public static Task <DocumentResponse> ExecuteAsync(this IClient client, GetDocumentCommand cmd)
 {
     return(client.Documents.GetAsync(cmd));
 }
Example #18
0
        public async Task Simple_Bulk_Insert_Should_Work()
        {
            var fooBars = new[]
            {
                new FooBar {
                    Name = "John Doe"
                },
                new FooBar {
                    Name = "Jane Doe"
                },
                new FooBar {
                    Name = "Mega John"
                },
                new FooBar {
                    Name = "Mega Jane"
                }
            };

            using (var store = GetDocumentStore())
            {
                using (var bulkInsert = store.BulkInsert())
                {
                    await bulkInsert.StoreAsync(fooBars[0]);

                    await bulkInsert.StoreAsync(fooBars[1]);

                    await bulkInsert.StoreAsync(fooBars[2]);

                    await bulkInsert.StoreAsync(fooBars[3]);
                }

                store.GetRequestExecutor(store.Database).ContextPool.AllocateOperationContext(out JsonOperationContext context);

                var getDocumentCommand = new GetDocumentCommand(new[] { "FooBars/1-A", "FooBars/2-A", "FooBars/3-A", "FooBars/4-A" }, includes: null, metadataOnly: false);

                store.GetRequestExecutor(store.Database).Execute(getDocumentCommand, context);

                var results = getDocumentCommand.Result.Results;

                Assert.Equal(4, results.Length);

                var doc1 = results[0];
                var doc2 = results[1];
                var doc3 = results[2];
                var doc4 = results[3];
                Assert.NotNull(doc1);
                Assert.NotNull(doc2);
                Assert.NotNull(doc3);
                Assert.NotNull(doc4);

                object name;
                ((BlittableJsonReaderObject)doc1).TryGetMember("Name", out name);
                Assert.Equal("John Doe", name.ToString());
                ((BlittableJsonReaderObject)doc2).TryGetMember("Name", out name);
                Assert.Equal("Jane Doe", name.ToString());
                ((BlittableJsonReaderObject)doc3).TryGetMember("Name", out name);
                Assert.Equal("Mega John", name.ToString());
                ((BlittableJsonReaderObject)doc4).TryGetMember("Name", out name);
                Assert.Equal("Mega Jane", name.ToString());
            }
        }