private void SobrescrevaConventions()
 {
     base.Conventions.FindCollectionName = type =>
                                           NomenclaturaDeColecaoCustomizada.ContainsKey(type)
             ? NomenclaturaDeColecaoCustomizada[type]
             : DocumentConventions.DefaultGetCollectionName(type);
 }
示例#2
0
        public void WithCustomizedTagNameAndIdentityProperty()
        {
            var id = string.Empty;

            using (var store = GetDocumentStore())
            {
                var defaultFindIdentityProperty = store.Conventions.FindIdentityProperty;
                store.Conventions.FindIdentityProperty = property =>
                                                         typeof(IEntity).GetTypeInfo().IsAssignableFrom(property.DeclaringType)
                      ? property.Name == "Id2"
                      : defaultFindIdentityProperty(property);

                store.Conventions.FindCollectionName = type =>
                                                       typeof(IDomainObject).IsAssignableFrom(type)
                                                        ? "domainobjects"
                                                        : DocumentConventions.DefaultGetCollectionName(type);

                using (var session = store.OpenSession())
                {
                    var domainObject = new DomainObject();
                    session.Store(domainObject);
                    var domainObject2 = new DomainObject();
                    session.Store(domainObject2);
                    session.SaveChanges();
                    id = domainObject.Id2;
                }
                var matchingDomainObjects = store.OpenSession().Query <IDomainObject>().Where(_ => _.Id2 == id).ToList();
                Assert.Equal(matchingDomainObjects.Count, 1);
            }
        }
示例#3
0
        private static string GetCollectionNameForType(Type type)
        {
            var collectionNameAttribute = Attribute.GetCustomAttribute(
                type,
                typeof(CollectionNameAttribute)
                ) as CollectionNameAttribute;

            if (collectionNameAttribute is object)
            {
                return(collectionNameAttribute.Name);
            }
            return(DocumentConventions.DefaultGetCollectionName(type));
        }
示例#4
0
        public static DocumentConventions AddFindCollectionName(this DocumentConventions conventions, Func <Type, string> func)
        {
            var current = conventions.FindCollectionName;

            conventions.FindCollectionName = type =>
            {
                return(func?.Invoke(type)
                       ?? current?.Invoke(type)
                       ?? DocumentConventions.DefaultGetCollectionName(type));
            };

            return(conventions);
        }
示例#5
0
        /// <summary>
        ///		Gets full document ID for a given entity (e.g. for '1-A' returns 'users/1-A')
        /// </summary>
        /// <typeparam name="T"> The entity type (e.g. class `Users`) </typeparam>
        /// <param name="session"> Session to resolve conventions for converting the ID </param>
        /// <param name="shortId"> The short ID (e.g. '1-A') </param>
        /// <returns> A full ID (e.g. 'users/1-A') </returns>
        internal static string GetFullId <T>(this IAsyncDocumentSession session, string shortId) where T : IEntity
        {
            // In input we don't trust. Though I might be a bit paranoiac, but this value can come from outside of the app and be passed to Raven
            if (!new Regex(@"^\d{1,19}\-[a-z]{1}$", RegexOptions.IgnoreCase).IsMatch(shortId))
            {
                throw new ArgumentException("ID has incorrect format", nameof(shortId));
            }

            // Pluralise the collection name (e.g. 'User' becomes 'Users', 'Person' becomes 'People')
            var pluralisedName = DocumentConventions.DefaultGetCollectionName(typeof(T));
            // Fix the later case - converts 'Users' to 'users', 'BacklogItems' to 'backlogItems'
            var prefix = session.Advanced.DocumentStore.Conventions.TransformTypeCollectionNameToDocumentIdPrefix(pluralisedName);

            return($"{prefix}/{shortId}");
        }
示例#6
0
        public CustomizeCollectionAssignmentForEntities()
        {
            var store = new DocumentStore();

            #region custom_collection_name
            store.Conventions.FindCollectionName = type =>
            {
                if (typeof(Category).IsAssignableFrom(type))
                {
                    return("ProductGroups");
                }

                return(DocumentConventions.DefaultGetCollectionName(type));
            };
            #endregion
        }
示例#7
0
        private void AddRavenDBServices(IServiceCollection services)
        {
            services.AddSingleton <IDocumentStore>(s =>
            {
                IDocumentStore store = new DocumentStore()
                {
                    Urls     = new[] { Configuration.GetValue <string>("RavenDBEndpoint") },
                    Database = Configuration.GetValue <string>("RavenDBDataBase")
                };
                store.Conventions.FindCollectionName = type =>
                {
                    if (typeof(TossEntity).IsAssignableFrom(type))
                    {
                        return("TossEntity");
                    }

                    return(DocumentConventions.DefaultGetCollectionName(type));
                };

                store.Initialize();
                //taken from https://ravendb.net/docs/article-page/4.1/csharp/client-api/operations/server-wide/create-database
                try
                {
                    store.Maintenance.ForDatabase(store.Database).Send(new GetStatisticsOperation());
                }
                catch (DatabaseDoesNotExistException)
                {
                    try
                    {
                        store.Maintenance.Server.Send(new CreateDatabaseOperation(new DatabaseRecord(store.Database)));
                    }
                    catch (ConcurrencyException)
                    {
                        // The database was already created before calling CreateDatabaseOperation
                    }
                }
                IndexCreation.CreateIndexes(typeof(Startup).Assembly, store);
                return(store);
            });

            services.AddScoped(s => s.GetRequiredService <IDocumentStore>().OpenAsyncSession());
            services.AddSingleton <RavenDBIdUtil>();
            services
            .AddRavenDbIdentity <ApplicationUser>();
        }
 public void OtherWays()
 {
     #region other_ways_1
     DocumentStore store = new DocumentStore()
     {
         Conventions =
         {
             FindCollectionName = type =>
             {
                 if (typeof(Animal).IsAssignableFrom(type))
                 {
                     return("Animals");
                 }
                 return(DocumentConventions.DefaultGetCollectionName(type));
             }
         }
     };
     #endregion
 }
示例#9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="IndexDefinitionBuilder{TDocument,TReduceResult}"/> class.
        /// </summary>
        protected AbstractIndexDefinitionBuilder(string indexName)
        {
            _indexName = indexName ?? DocumentConventions.DefaultGetCollectionName(GetType());
            if (_indexName.Length > 256)
                throw new ArgumentException("The index name is limited to 256 characters, but was: " + _indexName, nameof(indexName));

            Stores = new Dictionary<Expression<Func<TReduceResult, object>>, FieldStorage>();
            StoresStrings = new Dictionary<string, FieldStorage>();
            Indexes = new Dictionary<Expression<Func<TReduceResult, object>>, FieldIndexing>();
            IndexesStrings = new Dictionary<string, FieldIndexing>();
            SuggestionsOptions = new HashSet<Expression<Func<TReduceResult, object>>>();
            Analyzers = new Dictionary<Expression<Func<TReduceResult, object>>, string>();
            AnalyzersStrings = new Dictionary<string, string>();
            TermVectors = new Dictionary<Expression<Func<TReduceResult, object>>, FieldTermVector>();
            TermVectorsStrings = new Dictionary<string, FieldTermVector>();
            SpatialIndexes = new Dictionary<Expression<Func<TReduceResult, object>>, SpatialOptions>();
            SpatialIndexesStrings = new Dictionary<string, SpatialOptions>();
            Configuration = new IndexConfiguration();
        }
示例#10
0
        /// <summary>
        ///     Configure RavenDB Document Store
        /// </summary>
        public static void PreInitializeDocumentStore(this IDocumentStore store)
        {
            store.Conventions.UseOptimisticConcurrency = true;

            // Added this so that when the property is missing in the DB, default values are assigned during serialization
            store.Conventions.Serialization = new NewtonsoftJsonSerializationConventions
            {
                CustomizeJsonSerializer = serializer => serializer.NullValueHandling = NullValueHandling.Ignore
            };

            // Set one collection for derived classes
            store.Conventions.FindCollectionName = type =>
            {
                if (typeof(BacklogItem).IsAssignableFrom(type))
                {
                    return(DocumentConventions.DefaultGetCollectionName(typeof(BacklogItem)));                            // "BacklogItems";
                }
                return(DocumentConventions.DefaultGetCollectionName(type));
            };
        }
示例#11
0
            public MapReduce()
            {
                Map = users => from user in users
                      select new Result
                {
                    Name  = user.Name,
                    Count = 1
                };

                Reduce = results => from result in results
                         group result by result.Name
                         into g
                         select new
                {
                    Name  = g.Key,
                    Count = g.Sum(x => x.Count)
                };

                OutputReduceToCollection = DocumentConventions.DefaultGetCollectionName(typeof(Result));
            }
        public DocumentStoreHolder(IOptions <RavenSettings> options)
        {
            var setting = options.Value;

            Store = new DocumentStore
            {
                Urls        = new string[] { setting.Url },
                Database    = setting.DefaultDatabase,
                Conventions =
                {
                    FindCollectionName = type =>
                    {
                        //if (typeof(IEvent).IsAssignableFrom(type))
                        //{
                        //    return "CQRSLiteEvent";
                        //}

                        return(DocumentConventions.DefaultGetCollectionName(type));
                    }
                }
            }.Initialize();
        }
示例#13
0
        public RavenDbConnection(DbConnectionModel dbConnection)
        {
            if (_connection != null)
            {
                return;
            }

            //var config = appSetting.Get<RavenDbConnectionConfig>("DbConnection");
            var config = dbConnection as RavenDbConnectionConfig;

            _connection = new DocumentStore()
            {
                Urls     = config.Servers,
                Database = config.DatabaseName,

                Conventions =
                {
                    FindCollectionName = type =>
                    {
                        _tableTypes ??= Globals.GetClassTypeWithAttribute <TableAttribute>();

                        if (_tableTypes.All(t => t != type))
                        {
                            return(DocumentConventions.DefaultGetCollectionName(type));
                        }

                        var name       = (type.GetCustomAttribute(typeof(TableAttribute)) as TableAttribute)?.Name;
                        return(string.IsNullOrWhiteSpace(name)
                            ? DocumentConventions.DefaultGetCollectionName(type)
                            : name);
                    }
                }
            };

            _connection.Initialize();
        }
示例#14
0
        /// <summary>
        /// Returns a new <see cref="RavenDbStorage"/>.
        /// </summary>
        /// <param name="urls">The RavenDB Urls.</param>
        /// <param name="database">The RavenDB database name.</param>
        /// <param name="identifier">The identifier for store.</param>
        /// <param name="certificate">The client certificate to use for authentication.</param>
        /// <param name="waitForIndexes">Whether to wait for indexes after save.</param>
        /// <param name="waitForReplication">whether to wait for replication after save.</param>
        public RavenDbStorage(string[] urls, string database, string identifier = "mini-profiler",
                              X509Certificate2 certificate = null, bool waitForIndexes = false, bool waitForReplication = false)
        {
            _waitForReplication = waitForReplication;
            _waitForIndexes     = waitForIndexes;
            _store = new DocumentStore
            {
                Urls        = urls,
                Database    = database,
                Identifier  = identifier,
                Certificate = certificate
            };
            _store.Conventions.FindCollectionName = type =>
            {
                if (type == typeof(MiniProfilerDoc))
                {
                    return(nameof(MiniProfiler));
                }

                return(DocumentConventions.DefaultGetCollectionName(type));
            };
            _store.Initialize();
            WithIndexCreation();
        }
示例#15
0
        public async Task FindCollectionName_WhenSubscribeToApiChanges(char c)
        {
            var mre = new AsyncManualResetEvent();

            using var store = GetDocumentStore(new Options
            {
                ModifyDocumentStore = s => s.Conventions.FindCollectionName = type => "Test" + c + DocumentConventions.DefaultGetCollectionName(type)
            });

            var subscription = store.Changes();
            await subscription.EnsureConnectedNow();

            var observableWithTask = subscription
                                     .ForDocumentsInCollection <User>();

            observableWithTask.Subscribe(change => mre.Set());
            await observableWithTask.EnsureSubscribedNow();

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

                await session.SaveChangesAsync();
            }

            Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(15)));
        }
示例#16
0
        public async Task FindCollectionName_WhenQuery(char c)
        {
            using var store = GetDocumentStore(new Options
            {
                ModifyDocumentStore = s => s.Conventions.FindCollectionName = type => "Test" + c + DocumentConventions.DefaultGetCollectionName(type)
            });

            using (var session = store.OpenAsyncSession())
            {
                var car = new Car {
                    Manufacturer = "BMW"
                };
                await session.StoreAsync(car);

                await session.StoreAsync(new User { CarId = car.Id });

                await session.SaveChangesAsync();
            }

            using (var session = store.OpenAsyncSession())
            {
                var results = await session
                              .Query <User>()
                              .ToArrayAsync();

                Assert.Equal(1, results.Length);
            }

            using (var session = store.OpenAsyncSession())
            {
                var results = await session.Advanced
                              .AsyncDocumentQuery <User>()
                              .ToArrayAsync();

                Assert.Equal(1, results.Length);
            }

            using (var session = store.OpenSession())
            {
                var results = session
                              .Query <User>()
                              .ToArray();

                Assert.Equal(1, results.Length);
            }

            using (var session = store.OpenSession())
            {
                var results = session.Advanced
                              .DocumentQuery <User>()
                              .ToArray();

                Assert.Equal(1, results.Length);
            }
        }
示例#17
0
 public string FindCollectionBy(Type type) => this._collections.Where(w => w.Type == type).SingleOrDefault()?.CollectionName ?? DocumentConventions.DefaultGetCollectionName(type);
示例#18
0
        public async Task FindCollectionName_WhenLoadWithInclude(char c)
        {
            using var store = GetDocumentStore(new Options
            {
                ModifyDocumentStore = s => s.Conventions.FindCollectionName = type => "Test" + c + DocumentConventions.DefaultGetCollectionName(type)
            });

            var user = new User();

            using (var session = store.OpenAsyncSession())
            {
                var car = new Car {
                    Manufacturer = "BMW"
                };
                await session.StoreAsync(car);

                user.CarId = car.Id;
                await session.StoreAsync(user);

                await session.SaveChangesAsync();
            }

            using (var session = store.OpenAsyncSession())
            {
                var loadedUser = await session.Include <User, Car>(x => x.CarId)
                                 .LoadAsync(user.Id);

                Assert.NotNull(loadedUser);
                Assert.True(session.Advanced.IsLoaded(user.CarId), "Included data should be loaded");
            }
        }
示例#19
0
        public async Task FindCollectionName_WhenSubscribeWithInclude(char c)
        {
            using var store = GetDocumentStore(new Options
            {
                ModifyDocumentStore = s => s.Conventions.FindCollectionName = type => "Test" + c + DocumentConventions.DefaultGetCollectionName(type)
            });

            var user = new User();

            using (var session = store.OpenAsyncSession())
            {
                var car = new Car {
                    Manufacturer = "BMW"
                };
                await session.StoreAsync(car);

                user.CarId = car.Id;
                await session.StoreAsync(user);

                await session.SaveChangesAsync();
            }

            var name = await store.Subscriptions.CreateAsync(new SubscriptionCreationOptions <User>
            {
                Includes = builder => builder
                           .IncludeDocuments(x => x.CarId)
            });

            await using (var sub = store.Subscriptions.GetSubscriptionWorker <User>(name))
            {
                var mre = new AsyncManualResetEvent();
                var r   = sub.Run(batch =>
                {
                    Assert.NotEmpty(batch.Items);
                    using (var s = batch.OpenSession())
                    {
                        foreach (var item in batch.Items)
                        {
                            s.Load <Car>(item.Result.CarId);
                        }
                        Assert.Equal(0, s.Advanced.NumberOfRequests);
                    }
                    mre.Set();
                });
                var isSet = await mre.WaitAsync(TimeSpan.FromSeconds(30));

                await sub.DisposeAsync();

                await r;// no error
                Assert.True(isSet);
            }
        }
示例#20
0
        private async Task TestWhenCollectionAndIdContainSpecialChars <T>(char c) where T : AbstractGenericIndexCreationTask <IndexResult>, new()
        {
            //TODO RavenDB-15533
            if (c == '\v' || c >= 14 && c <= 31)
            {
                return;
            }

            using var store = GetDocumentStore(new Options
            {
                ModifyDocumentStore = s => s.Conventions.FindCollectionName = type => "Test" + c + DocumentConventions.DefaultGetCollectionName(type)
            });

            using (var session = store.OpenAsyncSession())
            {
                var car = new Car {
                    Manufacturer = "BMW"
                };
                await session.StoreAsync(car);

                await session.StoreAsync(new User { CarId = car.Id });

                await session.SaveChangesAsync();
            }

            var index = new T();
            await index.ExecuteAsync(store);

            Indexes.WaitForIndexing(store);

            using (var session = store.OpenAsyncSession())
            {
                var results = await session
                              .Query <IndexResult, T>()
                              .Where(x => x.CarManufacturer == "BMW")
                              .OfType <User>()
                              .ToArrayAsync();

                Assert.Equal(1, results.Length);
            }
        }