public void Can_Use_NodaTime_DateTimeZone_In_Document()
        {
            var zone = DateTimeZoneProviders.Tzdb.GetSystemDefault();

            using (var documentStore = NewDocumentStore())
            {
                using (var session = documentStore.OpenSession())
                {
                    session.Store(new Foo {
                        Id = "foos/1", DateTimeZone = zone
                    });
                    session.SaveChanges();
                }

                using (var session = documentStore.OpenSession())
                {
                    var foo = session.Load <Foo>("foos/1");

                    Assert.Equal(zone, foo.DateTimeZone);
                }

                using (var session = documentStore.OpenSession())
                {
                    var command = new GetDocumentsCommand("foos/1", null, false);
                    session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
                    var json = (BlittableJsonReaderObject)command.Result.Results[0];
                    System.Diagnostics.Debug.WriteLine(json.ToString());
                    json.TryGet("DateTimeZone", out string value);
                    Assert.Equal(zone.Id, value);
                }
            }
        }
Example #2
0
 public void Should_Load_Many_Ids_As_Post_Request_Directly()
 {
     using (var store = GetDocumentStore())
     {
         var ids = new List <string>();
         using (var session = store.OpenSession())
         {
             // Length of all the ids together should be larger than 1024 for POST request
             for (int i = 0; i < 200; i++)
             {
                 var id = "users/" + i;
                 ids.Add(id);
                 session.Store(new User()
                 {
                     Name = "Person " + i
                 }, id);
             }
             session.SaveChanges();
         }
         var rq1 = store.GetRequestExecutor();
         var cmd = new GetDocumentsCommand(ids.ToArray(), null, true);
         using (var ctx = new JsonOperationContext(1024, 1024, SharedMultipleUseFlag.None))
         {
             rq1.Execute(cmd, ctx);
         }
     }
 }
        private void Can_Use_NodaTime_Instant_In_Document(Instant instant)
        {
            using (var documentStore = NewDocumentStore())
            {
                using (var session = documentStore.OpenSession())
                {
                    session.Store(new Foo {
                        Id = "foos/1", Instant = instant
                    });
                    session.SaveChanges();
                }

                using (var session = documentStore.OpenSession())
                {
                    var foo = session.Load <Foo>("foos/1");

                    Assert.Equal(instant.ToUnixTimeTicks(), foo.Instant.ToUnixTimeTicks());
                }

                using (var session = documentStore.OpenSession())
                {
                    var command = new GetDocumentsCommand("foos/1", null, false);
                    session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
                    var json = (BlittableJsonReaderObject)command.Result.Results[0];
                    System.Diagnostics.Debug.WriteLine(json.ToString());
                    var expected = instant.ToString(NodaUtil.Instant.FullIsoPattern.PatternText, null);
                    json.TryGet("Instant", out string value);
                    Assert.Equal(expected, value);
                }
            }
        }
Example #4
0
        private void Can_Use_NodaTime_Offset_In_Document(Offset offset)
        {
            using (var documentStore = NewDocumentStore())
            {
                using (var session = documentStore.OpenSession())
                {
                    session.Store(new Foo {
                        Id = "foos/1", Offst = offset
                    });
                    session.SaveChanges();
                }

                using (var session = documentStore.OpenSession())
                {
                    var foo = session.Load <Foo>("foos/1");

                    Assert.Equal(offset, foo.Offst);
                }

                using (var session = documentStore.OpenSession())
                {
                    var command = new GetDocumentsCommand("foos/1", null, false);
                    session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
                    var json = (BlittableJsonReaderObject)command.Result.Results[0];
                    System.Diagnostics.Debug.WriteLine(json.ToString());
                    var expected = offset.ToTimeSpan().ToString("c");
                    json.TryGet("Offst", out string value);
                    Assert.Equal(expected, value);
                }
            }
        }
Example #5
0
 public DocumentsController(UploadDocumentsCommand uploadDocumentsDocumentsCommand,
                            GetDocumentsCommand getDocumentsCommand,
                            UpdateDocumentsCommand updateDocumentsCommand)
 {
     _uploadDocumentsDocumentsCommand = uploadDocumentsDocumentsCommand;
     _getDocumentsCommand             = getDocumentsCommand;
     _updateDocumentsCommand          = updateDocumentsCommand;
 }
Example #6
0
            public async Task <DynamicArray> GetAsync(int start, int pageSize)
            {
                var command = new GetDocumentsCommand(start, pageSize);

                await RequestExecutor.ExecuteAsync(command, Context);

                return(new DynamicArray(command.Result.Results));
            }
        public void Changes()
        {
            var store = new DocumentStore().Initialize();

            #region events_1
            store.OnBeforeStore         += (s, e) => { };
            store.OnAfterSaveChanges    += (s, e) => { };
            store.OnBeforeDelete        += (s, e) => { };
            store.OnBeforeQueryExecuted += (s, e) => { };
            #endregion

            #region urls_1
            new DocumentStore
            {
                Urls = new []
                {
                    "http://ravendb-1:8080",
                    "http://ravendb-2:8080",
                    "http://ravendb-3:8080"
                }
            }.Initialize();
            #endregion

            #region request_executor_1
            RequestExecutor requestExecutor = store.GetRequestExecutor();

            using (requestExecutor.ContextPool.AllocateOperationContext(out JsonOperationContext context))
            {
                var command = new GetDocumentsCommand(start: 0, pageSize: 10);
                requestExecutor.Execute(command, context);

                GetDocumentsResult result = command.Result;
            }
            #endregion

            #region request_executor_2
            int numberOfCachedItems = requestExecutor.Cache.NumberOfItems;

            requestExecutor.Cache.Clear();
            #endregion

            #region request_executor_3
            var numberOfSentRequests = requestExecutor.NumberOfServerRequests;
            #endregion

            #region request_executor_4
            requestExecutor.DefaultTimeout = TimeSpan.FromSeconds(180);
            #endregion

            #region request_executor_5
            using (store.SetRequestsTimeout(TimeSpan.FromMilliseconds(180)))
            {
            }
            #endregion
        }
Example #8
0
 public void Single()
 {
     using (var store = new DocumentStore())
         using (var session = store.OpenSession())
         {
             #region get_sample_single
             var command = new GetDocumentsCommand("orders/1-A", null, false);
             session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
             var order = (BlittableJsonReaderObject)command.Result.Results[0];
             #endregion
         }
 }
Example #9
0
 public void Paged()
 {
     using (var store = new DocumentStore())
         using (var session = store.OpenSession())
         {
             #region get_sample_paged
             var command = new GetDocumentsCommand(start: 0, pageSize: 128);
             session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
             var first10Docs = command.Result.Results;
             #endregion
         }
 }
Example #10
0
 public void Missing()
 {
     using (var store = new DocumentStore())
         using (var session = store.OpenSession())
         {
             #region get_sample_missing
             // Assuming that products/9999-A doesn't exist.
             var command = new GetDocumentsCommand(new[] { "products/1-A", "products/9999-A", "products/3-A" }, null, false);
             session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
             var products = command.Result.Results; // products/1-A, null, products/3-A
             #endregion
         }
 }
Example #11
0
            public async Task <DynamicArray> GetAsync(string[] ids)
            {
                if (ids == null)
                {
                    throw new ArgumentNullException(nameof(ids));
                }

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

                await RequestExecutor.ExecuteAsync(command, Context);

                return(new DynamicArray(command.Result.Results));
            }
Example #12
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 GetDocumentsCommand(new[] { documentInfo.Id }, includes: null, metadataOnly: false);
            await RequestExecutor.ExecuteAsync(command, Context, SessionInfo, token).ConfigureAwait(false);

            RefreshInternal(entity, command, documentInfo);
        }
Example #13
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 GetDocumentsCommand(new[] { documentInfo.Id }, includes: null, metadataOnly: false);

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

            RefreshInternal(entity, command, documentInfo);
        }
Example #14
0
        public List <Task> GetTasks()
        {
            var session = store.OpenSession();
            var command = new GetDocumentsCommand(start: 0, pageSize: 1024);

            session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);

            return(command.Result.Results
                   .OfType <BlittableJsonReaderObject>()
                   .Select(obj => new Task()
            {
                Id = ((BlittableJsonReaderObject)obj["@metadata"])["@id"].ToString(),
                Title = obj["Title"].ToString(),
                Completed = (bool)obj["Completed"]
            })
                   .ToList());
        }
Example #15
0
 public void Includes()
 {
     using (var store = new DocumentStore())
         using (var session = store.OpenSession())
         {
             #region get_sample_includes
             // Fetch employees/5-A and his boss.
             var command = new GetDocumentsCommand("employees/5-A", includes: new[] { "ReportsTo" }, metadataOnly: false);
             session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
             var employee = (BlittableJsonReaderObject)command.Result.Results[0];
             if (employee.TryGet <string>("ReportsTo", out var bossId))
             {
                 var boss = command.Result.Includes[bossId];
             }
             #endregion
         }
 }
Example #16
0
        public EntityStructure GetEntityStructure(string DocName, string Database)
        {
            EntityStructure retval = new EntityStructure();

            try
            {
                Session = GetSession(Database);
                var command = new GetDocumentsCommand(DocName, null, metadataOnly: true);
                Session.Advanced.RequestExecutor.Execute(command, Session.Advanced.Context);
                var result           = (BlittableJsonReaderObject)command.Result.Results[0];
                var documentMetadata = (BlittableJsonReaderObject)result["@metadata"];

                // Print out all the metadata properties.
                EntityStructure entityData = new EntityStructure();

                string sheetname;
                sheetname                          = DocName;
                entityData.EntityName              = DocName;
                entityData.DataSourceID            = ConnProp.ConnectionName;
                entityData.SchemaOrOwnerOrDatabase = Database;
                List <EntityField> Fields = new List <EntityField>();
                int y = 0;
                foreach (var propertyName in documentMetadata.GetPropertyNames())
                {
                    documentMetadata.TryGet <object>(propertyName, out var metaPropValue);

                    EntityField f = new EntityField();
                    f.fieldname  = propertyName;
                    f.fieldtype  = "System.String";
                    f.FoundValue = false;
                    f.EntityName = sheetname;
                    f.FieldIndex = y;
                    Fields.Add(f);
                    y += 1;
                }
                return(retval);
            }
            catch (Exception ex)
            {
                DME_Editor.AddLogMessage(ex.Message, "Could not Create Entity structure for RavenDB Entity " + DocName, DateTime.Now, -1, ConnProp.Url, Errors.Failed);
                return(null);
            }
        }
Example #17
0
            public async Task <DynamicBlittableJson> GetAsync(string id, bool metadataOnly = false)
            {
                if (id == null)
                {
                    throw new ArgumentNullException(nameof(id));
                }

                var command = new GetDocumentsCommand(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 #18
0
 public void StartsWith()
 {
     using (var store = new DocumentStore())
         using (var session = store.OpenSession())
         {
             #region get_sample_startswith
             // return up to 128 documents with key that starts with 'products'
             var command = new GetDocumentsCommand(
                 startWith: "products",
                 startAfter: null,
                 matches: null,
                 exclude: null,
                 start: 0,
                 pageSize: 128,
                 metadataOnly: false);
             session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
             var products = command.Result.Results;
             #endregion
         }
 }
        public void Can_Use_NodaTime_Interval_In_Document()
        {
            var now      = SystemClock.Instance.GetCurrentInstant();
            var start    = now - Duration.FromMinutes(5);
            var end      = now + Duration.FromMinutes(5);
            var interval = new Interval(start, end);

            using (var documentStore = NewDocumentStore())
            {
                using (var session = documentStore.OpenSession())
                {
                    session.Store(new Foo {
                        Id = "foos/1", Interval = interval
                    });
                    session.SaveChanges();
                }

                using (var session = documentStore.OpenSession())
                {
                    var foo = session.Load <Foo>("foos/1");

                    Assert.Equal(interval, foo.Interval);
                }

                using (var session = documentStore.OpenSession())
                {
                    var command = new GetDocumentsCommand("foos/1", null, false);
                    session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
                    var json = (BlittableJsonReaderObject)command.Result.Results[0];
                    System.Diagnostics.Debug.WriteLine(json.ToString());
                    var expectedStart = interval.Start.ToString(NodaUtil.Instant.FullIsoPattern.PatternText, null);
                    var expectedEnd   = interval.End.ToString(NodaUtil.Instant.FullIsoPattern.PatternText, null);
                    json.TryGetMember("Interval", out var obj);
                    var bInterval = obj as BlittableJsonReaderObject;
                    bInterval.TryGet("Start", out string valueStart);
                    bInterval.TryGet("End", out string valueEnd);
                    Assert.Equal(expectedStart, valueStart);
                    Assert.Equal(expectedEnd, valueEnd);
                }
            }
        }
        public void Can_Use_NodaTime_DateInterval_In_Document()
        {
            var today        = NodaUtil.LocalDate.Today;
            var start        = today.PlusDays(-1);
            var end          = today.PlusDays(1);
            var dateInterval = new DateInterval(start, end);

            using (var documentStore = NewDocumentStore())
            {
                using (var session = documentStore.OpenSession())
                {
                    session.Store(new Foo {
                        Id = "foos/1", DateInterval = dateInterval
                    });
                    session.SaveChanges();
                }

                using (var session = documentStore.OpenSession())
                {
                    var foo = session.Load <Foo>("foos/1");

                    Assert.Equal(dateInterval, foo.DateInterval);
                }

                using (var session = documentStore.OpenSession())
                {
                    var command = new GetDocumentsCommand("foos/1", null, false);
                    session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
                    var json = (BlittableJsonReaderObject)command.Result.Results[0];
                    System.Diagnostics.Debug.WriteLine(json.ToString());
                    var expectedStart = dateInterval.Start.ToString(LocalDatePattern.Iso.PatternText, null);
                    var expectedEnd   = dateInterval.End.ToString(LocalDatePattern.Iso.PatternText, null);
                    json.TryGetMember("DateInterval", out var obj);
                    var bInterval = obj as BlittableJsonReaderObject;
                    bInterval.TryGet("Start", out string valueStart);
                    bInterval.TryGet("End", out string valueEnd);
                    Assert.Equal(expectedStart, valueStart);
                    Assert.Equal(expectedEnd, valueEnd);
                }
            }
        }
Example #21
0
        public async Task Examples()
        {
            using (var documentStore = new DocumentStore())
            {
                #region commands_1
                using (var session = documentStore.OpenSession())
                {
                    var command = new GetDocumentsCommand("orders/1-A", null, false);
                    session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
                    var order = (BlittableJsonReaderObject)command.Result.Results[0];
                }
                #endregion

                #region commands_1_async
                using (var session = documentStore.OpenAsyncSession())
                {
                    var command = new GetDocumentsCommand("orders/1-A", null, false);
                    await session.Advanced.RequestExecutor.ExecuteAsync(command, session.Advanced.Context);

                    var order = (BlittableJsonReaderObject)command.Result.Results[0];
                }
                #endregion

                #region commands_2
                using (var session = documentStore.OpenSession())
                {
                    var command = new DeleteDocumentCommand("employees/1-A", null);
                    session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
                }
                #endregion

                #region commands_2_async
                using (var session = documentStore.OpenAsyncSession())
                {
                    var command = new DeleteDocumentCommand("employees/1-A", null);
                    await session.Advanced.RequestExecutor.ExecuteAsync(command, session.Advanced.Context);
                }
                #endregion
            }
        }
Example #22
0
 public void StartsWithMatchesEnd()
 {
     using (var store = new DocumentStore())
         using (var session = store.OpenSession())
         {
             #region get_sample_startswith_matches_end
             // return up to 128 documents with key that starts with 'products/'
             // and rest of the key have length of 3, begins and ends with "1"
             // and contains any character at 2nd position e.g. products/101, products/1B1
             var command = new GetDocumentsCommand(
                 startWith: "products",
                 startAfter: null,
                 matches: "1?1",
                 exclude: null,
                 start: 0,
                 pageSize: 128,
                 metadataOnly: false);
             session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
             var products = command.Result.Results;
             #endregion
         }
 }
Example #23
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 GetDocumentsCommand(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 #24
0
        public void PropertySortOrderSustained()
        {
            using (var store = GetDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    session.Store(new MyEntity
                    {
                        Username       = "******",
                        Password       = "******",
                        AgentDutyCode  = "code",
                        OrganizationId = "rr"
                    }, "things/1");
                    session.SaveChanges();
                }

                GetDocumentsCommand getDocsCommand = new GetDocumentsCommand("things/1", null, false);
                store.Commands().Execute(getDocsCommand);
                var res = getDocsCommand.Result.Results[0] as BlittableJsonReaderObject;

                var propertiesByInsertionOrder = res.GetPropertiesByInsertionOrder();

                var expectedOrder = new[] { "Username", "Password", "OrganizationId", "AgentDutyCode" };

                var propertyNames = res.GetPropertyNames();
                WaitForUserToContinueTheTest(store);
                for (var i = 0; i < expectedOrder.Length; i++)
                {
                    var matchingPropertyId = propertiesByInsertionOrder.Properties.Array[i + propertiesByInsertionOrder.Properties.Offset];
                    BlittableJsonReaderObject.PropertyDetails propDetails = new BlittableJsonReaderObject.PropertyDetails();

                    res.GetPropertyByIndex(matchingPropertyId, ref propDetails);

                    Assert.Equal(expectedOrder[i], propDetails.Name.ToString());
                }
            }
        }
Example #25
0
        public void ShouldSupportRawNumbersFloatingPoint(int stringLength)
        {
            string GetNumber(int length)
            {
                var sb = new StringBuilder("0.");

                for (var i = 1; i <= length; i++)
                {
                    sb.Append(((char)((byte)'0' + (i % 10))).ToString());
                }
                return(sb.ToString());
            }

            string bigNumString = string.Join(string.Empty, GetNumber(stringLength));

            using (var store = GetDocumentStore())
            {
                var requestExecuter = store.GetRequestExecutor();
                using (requestExecuter.ContextPool.AllocateOperationContext(out var context))
                {
                    var reader = context.ReadObject(new Sparrow.Json.Parsing.DynamicJsonValue
                    {
                        ["BigNumber"] = new LazyNumberValue(context.GetLazyString(bigNumString))
                    }, "num");
                    requestExecuter.Execute(new PutDocumentCommand("bignum/1", null, reader), context);
                }

                using (requestExecuter.ContextPool.AllocateOperationContext(out var context))
                {
                    GetDocumentsCommand getDoc = new GetDocumentsCommand("bignum/1", null, false);
                    requestExecuter.Execute(getDoc, context);
                    var doc = getDoc.Result.Results[0] as BlittableJsonReaderObject;
                    Assert.True(doc.TryGet <LazyNumberValue>("BigNumber", out var rawNum));
                    Assert.Equal(bigNumString, rawNum.Inner.ToString());
                }
            }
        }
        private void Can_Use_NodaTime_ZonedDateTime_In_Document(ZonedDateTime zdt)
        {
            using (var documentStore = NewDocumentStore())
            {
                using (var session = documentStore.OpenSession())
                {
                    session.Store(new Foo {
                        Id = "foos/1", ZonedDateTime = zdt
                    });
                    session.SaveChanges();
                }

                using (var session = documentStore.OpenSession())
                {
                    var foo = session.Load <Foo>("foos/1");

                    Assert.Equal(zdt, foo.ZonedDateTime);
                }

                using (var session = documentStore.OpenSession())
                {
                    var command = new GetDocumentsCommand("foos/1", null, false);
                    session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
                    var json = (BlittableJsonReaderObject)command.Result.Results[0];
                    System.Diagnostics.Debug.WriteLine(json.ToString());
                    var expectedDateTime = zdt.ToDateTimeOffset().ToString("o");
                    var expectedZone     = zdt.Zone.Id;
                    json.TryGetMember("ZonedDateTime", out var obj);
                    var bInterval = obj as BlittableJsonReaderObject;
                    bInterval.TryGet("OffsetDateTime", out string value1);
                    bInterval.TryGet("Zone", out string value2);
                    Assert.Equal(expectedDateTime, value1);
                    Assert.Equal(expectedZone, value2);
                }
            }
        }
Example #27
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 GetDocumentsCommand(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 GetDocumentsCommand(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 #28
0
        private void ParseCommand(string line)
        {
            if (string.IsNullOrEmpty(line))
            {
                return;
            }
            //NOTE: Parse in ascending length order!
            if (line.Substring(0, 1).Equals("#"))
            {
                return;
            }
            if (line.Length < 4)
            {
                Warn("invalid command: {0}", line);
                return;
            }

            if (line.Substring(0, 4).ToLower().Equals("quit") || line.Substring(0, 4).ToLower().Equals("exit"))
            {
                return;
            }

            var    idx = line.IndexOf(' ');
            string cmd;

            if (idx < 0)
            {
                idx = 0;
                cmd = line;
            }
            else
            {
                cmd = line.Substring(0, idx).ToLower();
            }

            var args = idx == 0 ? string.Empty : line.Substring(idx + 1).Trim();

            if (CR.abort.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new AbortCommand();
                c.Execute(context);
                StopTimer(CR.abort + " " + args);
                return;
            }
            if (CR.addalias.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new AddAliasCommand();
                c.Execute(context, args);
                StopTimer(CR.addalias + " " + args);
                return;
            }
            if (CR.addindex.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new AddIndexCommand();
                c.Execute(context, args);
                StopTimer(CR.addindex + " " + args);
                return;
            }
            if (CR.close.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new CloseCommand();
                c.Execute(context, args);
                StopTimer(CR.close + " " + args);
                return;
            }
            if (CR.commit.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new CommitCommand();
                c.Execute(context, args);
                StopTimer(CR.commit + " " + args);
                return;
            }
            if (CR.compactcontainer.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new CompactContainerCommand();
                c.Execute(context, args);
                StopTimer(CR.compactcontainer + " " + args);
                return;
            }
            if (CR.contextquery.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new ContextQueryCommand();
                c.Execute(context, args);
                StopTimer(CR.contextquery + " " + args);
                return;
            }
            if (CR.cquery.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new CQueryCommand();
                c.Execute(context, args);
                StopTimer(CR.cquery + " " + args);
                return;
            }
            if (CR.createcontainer.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new CreateContainerCommand();
                c.Execute(context, args);
                StopTimer(CR.createcontainer + " " + args);
                return;
            }
            if (CR.delindex.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new DeleteIndexCommand();
                c.Execute(context, args);
                StopTimer(CR.delindex + " " + args);
                return;
            }
            if (CR.echo.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                Msg(args);
                return;
            }
            if (CR.getdocuments.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new GetDocumentsCommand();
                c.Execute(context, args);
                StopTimer(CR.getdocuments + " " + args);
                return;
            }
            if (CR.getmetadata.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new GetMetadataCommand();
                c.Execute(context, args);
                StopTimer(CR.getmetadata + " " + args);
                return;
            }
            if (CR.help.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                var c = new HelpCommand();
                c.Execute(args);
                return;
            }
            if (CR.info.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new InfoCommand();
                c.Execute(context, args);
                StopTimer(CR.info + " " + args);
                return;
            }
            if (CR.listindexes.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new ListIndexesCommand();
                c.Execute(context, args);
                StopTimer(CR.listindexes + " " + args);
                return;
            }
            if (CR.lookupedgeindex.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new LookupEdgeIndexCommand();
                c.Execute(context, args);
                StopTimer(CR.lookupedgeindex + " " + args);
                return;
            }
            if (CR.lookupindex.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new LookupIndexCommand();
                c.Execute(context, args);
                StopTimer(CR.lookupindex + " " + args);
                return;
            }
            if (CR.lookupstats.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new LookupStatisticsCommand();
                c.Execute(context, args);
                StopTimer(CR.lookupstats + " " + args);
                return;
            }
            if (CR.opencontainer.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new OpenContainerCommand();
                c.Execute(context, args);
                StopTimer(CR.opencontainer + " " + args);
                return;
            }
            if (CR.preload.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new PreloadCommand();
                c.Execute(context, args);
                StopTimer(CR.preload + " " + args);
                return;
            }
            if (CR.prepare.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new PrepareCommand();
                c.Execute(context, args);
                StopTimer(CR.prepare + " " + args);
                return;
            }
            if (CR.print.IndexOf(cmd, 0, StringComparison.Ordinal) == 0 || cmd.ToLower().Equals("printnames"))
            {
                StartTimer();
                var c = new PrintCommand();
                c.Execute(context, cmd.Equals("printnames") ? "printnames " + args : args);
                StopTimer(cmd.Equals("printnames") ? "printNames" : CR.print);
                return;
            }
            if (CR.putdocuments.Equals(cmd))
            {
                StartTimer();
                var c = new PutDocumentsCommand();
                c.Execute(context, args);
                StopTimer(CR.putdocuments + " " + args);
                return;
            }
            if (CR.putdocument.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new PutDocumentCommand();
                c.Execute(context, args);
                StopTimer(CR.putdocument + " " + args);
                return;
            }
            if (CR.query.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new QueryCommand();
                c.Execute(context, args);
                StopTimer(CR.query + " " + args);
                return;
            }
            if (CR.queryplan.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new QueryPlanCommand();
                c.Execute(context, args);
                StopTimer(CR.queryplan + " " + args);
                return;
            }
            if (CR.reindexcontainer.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new ReindexContainerCommand();
                c.Execute(context, args);
                StopTimer(CR.reindexcontainer + " " + args);
                return;
            }
            if (CR.removealias.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new RemoveAliasCommand();
                c.Execute(context, args);
                StopTimer(CR.removealias + " " + args);
                return;
            }
            if (CR.removecontainer.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new RemoveContainerCommand();
                c.Execute(context, args);
                StopTimer(CR.removecontainer + " " + args);
                return;
            }
            if (CR.removedocument.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new RemoveDocumentCommand();
                c.Execute(context, args);
                StopTimer(CR.removedocument + " " + args);
                return;
            }
            if (CR.run.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                var c = new RunCommand();
                c.Execute(context, args);
                var l2 = new List <string>(originalArgs)
                {
                    "-s", c.Script
                };
                StartTimer();
                Main(l2.ToArray());
                StopTimer(CR.run + " " + args);
                return;
            }
            if (CR.setautoindexing.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetAutoIndexingCommand();
                c.Execute(context, args);
                StopTimer(CR.setautoindexing + " " + args);
                return;
            }
            if (CR.setbaseuri.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetBaseUriCommand();
                c.Execute(context, args);
                StopTimer(CR.setbaseuri + " " + args);
                return;
            }
            if (CR.setignore.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                var c = new SetIgnoreCommand();
                c.Execute(context, args);
                ignoreErrors = c.Ignore;
                return;
            }
            if (CR.setlazy.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetLazyCommand();
                c.Execute(context, args);
                StopTimer(CR.setlazy + " " + args);
                return;
            }
            if (CR.setmetadata.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetMetadataCommand();
                c.Execute(context, args);
                StopTimer(CR.setmetadata + " " + args);
                return;
            }
            if (CR.setnamespace.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetNamespaceCommand();
                c.Execute(context, args);
                StopTimer(CR.setnamespace + " " + args);
                return;
            }
            if (CR.setprojection.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetProjectionCommand();
                c.Execute(context, args);
                StopTimer(CR.setprojection + " " + args);
                return;
            }
            if (CR.setquerytimeout.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetQueryTimeoutCommand();
                c.Execute(context, args);
                StopTimer(CR.setquerytimeout + " " + args);
                return;
            }
            if (CR.setvariable.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetVariableCommand();
                c.Execute(context, args);
                StopTimer(CR.setvariable + " " + args);
                return;
            }
            if (CR.setverbose.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetVerboseCommand();
                c.Execute(context, args);
                StopTimer(CR.setverbose + " " + args);
                return;
            }
            if (CR.sync.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                context.Sync();
                StopTimer(CR.sync + " " + args);
                return;
            }
            if (CR.time.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                time = true;
                ParseCommand(args);
                return;
            }
            if (CR.transaction.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new TransactionCommand();
                c.Execute(context, args);
                StopTimer(CR.transaction + " " + args);
                return;
            }
            if (CR.upgradecontainer.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new UpgradeContainerCommand();
                c.Execute(context, args);
                StopTimer(CR.upgradecontainer + " " + args);
                return;
            }

            Warn("Command not recognized: {0}", cmd);
        }
Example #29
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 GetDocumentsCommand(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());
            }
        }
Example #30
0
        public async Task TopologyUpdateDuringFailoverShouldntFaileCommand()
        {
            const int nodesAmount = 5;
            var       leader      = await this.CreateRaftClusterAndGetLeader(nodesAmount);

            var defaultDatabase = GetDatabaseName();

            await CreateDatabaseInCluster(defaultDatabase, nodesAmount, leader.WebUrl).ConfigureAwait(false);

            string tag1, tag2, tag3;

            using (var store = new DocumentStore
            {
                Urls = new[] { leader.WebUrl },
                Database = defaultDatabase
            }.Initialize())
            {
                var reqEx = store.GetRequestExecutor();

                Topology topology = null;

                while (reqEx.Topology == null)
                {
                    await Task.Delay(100);
                }
                topology = reqEx.Topology;
                var serverNode1 = topology.Nodes[0];
                await reqEx.UpdateTopologyAsync(
                    node : serverNode1,
                    timeout : 10_000);

                var node1 = Servers.First(x => x.WebUrl.Equals(serverNode1.Url, StringComparison.InvariantCultureIgnoreCase));
                await DisposeServerAndWaitForFinishOfDisposalAsync(node1);

                var serverNode2 = topology.Nodes[1];
                var node2       = Servers.First(x => x.WebUrl.Equals(serverNode2.Url, StringComparison.InvariantCultureIgnoreCase));
                await DisposeServerAndWaitForFinishOfDisposalAsync(node2);

                using (reqEx.ContextPool.AllocateOperationContext(out var context))
                {
                    var command = new GetDocumentsCommand(0, 1);
                    var task    = reqEx.ExecuteAsync(command, context);

                    var mre = new ManualResetEvent(false);

                    reqEx.FailedRequest += (x, y) =>
                    {
                        mre.WaitOne();
                    };

                    while (command.FailedNodes == null || command.FailedNodes.Count == 0)
                    {
                        await Task.Delay(100);
                    }
                    while (await reqEx.UpdateTopologyAsync(topology.Nodes[3], 10_000, forceUpdate: true) == false ||
                           reqEx.Topology.Etag == topology.Etag)
                    {
                        await Task.Delay(100);
                    }

                    mre.Set();
                    await task;
                }
            }
        }