Exemple #1
0
        public static BackgroundTaskBuilder AddDocumentDbBackgroundTaskStore(this BackgroundTaskBuilder builder,
                                                                             Action <DocumentDbOptions> configureAction = null)
        {
            Bootstrap.SetDefaultJsonSettings();

            const string slot = Constants.ConnectionSlots.BackgroundTasks;

            if (configureAction != null)
            {
                builder.Services.Configure(slot, configureAction);
            }

            builder.Services.AddLocalTimestamps();
            builder.Services.AddMetrics();
            builder.Services.AddSingleton <IDocumentDbRepository <BackgroundTaskDocument> >(r =>
                                                                                            new DocumentDbRepository <BackgroundTaskDocument>(slot,
                                                                                                                                              r.GetRequiredService <IOptionsMonitor <DocumentDbOptions> >(),
                                                                                                                                              r.GetService <ISafeLogger <DocumentDbRepository <BackgroundTaskDocument> > >()
                                                                                                                                              ));
            builder.Services.Replace(ServiceDescriptor.Singleton <IBackgroundTaskStore, DocumentDbBackgroundTaskStore>());

            var serviceProvider = builder.Services.BuildServiceProvider();
            var options         = serviceProvider.GetRequiredService <IOptions <BackgroundTaskOptions> >();

            var dbOptions = new DocumentDbOptions();

            configureAction?.Invoke(dbOptions);

            MigrateToLatest(options.Value, dbOptions);

            return(builder);
        }
Exemple #2
0
        public static SchemaBuilder AddDocumentDbSchemaStores(this SchemaBuilder builder,
                                                              Action <DocumentDbOptions> configureAction = null)
        {
            Bootstrap.SetDefaultJsonSettings();

            const string slot = Constants.ConnectionSlots.Schema;

            if (configureAction != null)
            {
                builder.Services.Configure(slot, configureAction);
            }

            builder.Services.AddLocalTimestamps();
            builder.Services.AddMetrics();
            builder.Services.AddSingleton <IApplicationVersionStore, DocumentApplicationVersionStore>();
            builder.Services.AddSingleton <ISchemaVersionStore, DocumentSchemaVersionStore>();

            var serviceProvider = builder.Services.BuildServiceProvider();
            var options         = serviceProvider.GetRequiredService <IOptions <SchemaOptions> >();

            var dbOptions = new DocumentDbOptions();

            configureAction?.Invoke(dbOptions);

            MigrateToLatest(options.Value, dbOptions);

            return(builder);
        }
 public RecipeBookDataManager(IOptions <DocumentDbOptions> documentDbOptions)
 {
     _documentDbOptions = documentDbOptions.Value ?? throw new ArgumentNullException(nameof(documentDbOptions));
     _documentClient    = new DocumentClient(new Uri(_documentDbOptions.Endpoint), _documentDbOptions.Key, new ConnectionPolicy {
         EnableEndpointDiscovery = false
     });
 }
Exemple #4
0
        protected StoreBase(IDocumentClient documentClient, IOptions <DocumentDbOptions> options, string collectionName)
        {
            this.documentClient = documentClient;
            this.options        = options.Value;
            this.collectionName = collectionName;

            this.collectionUri = UriFactory.CreateDocumentCollectionUri(this.options.Database, collectionName);
        }
 public ScoresController(IDataProtectionProvider dataProtectionProvider, IOptions <DocumentDbOptions> documentDbOptions, DocumentClient documentClient, ILogger <ScoresController> logger, IOptions <AadB2cApplicationOptions> aadB2cApplicationOptions)
 {
     this.aadB2cApplicationOptions = aadB2cApplicationOptions.Value;
     this.authenticationContext    = new AuthenticationContext($"https://login.microsoftonline.com/{aadB2cApplicationOptions.Value.Tenant}");
     this.clientCredential         = new ClientCredential(aadB2cApplicationOptions.Value.ApplicationId, aadB2cApplicationOptions.Value.ApplicationKey);
     this.dataProtector            = dataProtectionProvider.CreateProtector("schultztables");
     this.documentDbOptions        = documentDbOptions.Value;
     this.documentClient           = documentClient;
     this.logger = logger;
 }
        /// <summary>
        /// Creates a new instance of the <see cref="CreatePostCommand"/> class.
        /// </summary>
        /// <param name="options">The document db options</param>
        /// <param name="post">The post to create</param>
        /// <exception cref="System.ArgumentNullException">The post can't be null</exception>
        public CreatePostCommand(DocumentDbOptions options, Domain.Entities.Post post)
            : base(options)
        {
            if (post == null)
            {
                throw new ArgumentNullException("post");
            }

            this.post = post;
        }
Exemple #7
0
        private static void DefaultDbOptions(string connectionString, DocumentDbOptions o)
        {
            var connectionStringBuilder = new DocumentDbConnectionStringBuilder(connectionString);

            o.AccountKey ??= connectionStringBuilder.AccountKey;
            o.AccountEndpoint ??= connectionStringBuilder.AccountEndpoint;
            o.DatabaseId ??= connectionStringBuilder.Database;
            o.CollectionId ??= connectionStringBuilder.DefaultCollection ?? Constants.Runtime.DefaultCollection;

            o.SharedCollection  = true;            // Anything
            o.PartitionKeyPaths = new[] { "/id" };
        }
Exemple #8
0
        private static void DefaultDbOptions(string connectionString, DocumentDbOptions o)
        {
            var builder = new DocumentDbConnectionStringBuilder(connectionString);

            o.AccountKey ??= builder.AccountKey;
            o.AccountEndpoint ??= builder.AccountEndpoint;
            o.DatabaseId ??= builder.Database;
            o.CollectionId ??= builder.DefaultCollection ?? Constants.Identity.DefaultCollection;

            o.SharedCollection  = true;            // User, Role, Tenant, Application, etc.
            o.PartitionKeyPaths = new[] { "/id" };
        }
        /// <summary>
        /// Add a health check for Azure DocumentDb database.
        /// </summary>
        /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
        /// <param name="setup">The action to configure the DocumentDb connection parameters.</param>
        /// <param name="name">The health check name. Optional. If <c>null</c> the type name 'documentdb' will be used for the name.</param>
        /// <param name="failureStatus">
        /// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
        /// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
        /// </param>
        /// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
        /// <returns>The <see cref="IHealthChecksBuilder"/>.</returns></param>
        public static IHealthChecksBuilder AddDocumentDb(this IHealthChecksBuilder builder, Action <DocumentDbOptions> setup, string name = default, HealthStatus?failureStatus = default, IEnumerable <string> tags = default)
        {
            var documentDbOptions = new DocumentDbOptions();

            setup?.Invoke(documentDbOptions);

            return(builder.Add(new HealthCheckRegistration(
                                   name ?? NAME,
                                   sp => new DocumentDbHealthCheck(documentDbOptions),
                                   failureStatus,
                                   tags)));
        }
Exemple #10
0
        private static void DefaultDbOptions(string connectionString, DocumentDbOptions o)
        {
            var connectionStringBuilder = new DocumentDbConnectionStringBuilder(connectionString);

            o.AccountKey      = connectionStringBuilder.AccountKey;
            o.AccountEndpoint = connectionStringBuilder.AccountEndpoint;
            o.CollectionId    = connectionStringBuilder.DefaultCollection ?? "BackgroundTasks";
            o.DatabaseId      = connectionStringBuilder.Database ?? "Default";

            o.SharedCollection  = true;            // Sequence, Document, etc.
            o.PartitionKeyPaths = new[] { "/id" };
        }
Exemple #11
0
        private static void DefaultDbOptions(string connectionString, DocumentDbOptions o)
        {
            var connectionStringBuilder = new DocumentDbConnectionStringBuilder(connectionString);

            o.AccountKey      = connectionStringBuilder.AccountKey;
            o.AccountEndpoint = connectionStringBuilder.AccountEndpoint;
            o.CollectionId    = connectionStringBuilder.DefaultCollection ?? Constants.Schemas.DefaultCollection;
            o.DatabaseId      = connectionStringBuilder.Database ?? "Default";

            o.SharedCollection  = true;            // SchemaVersionDocument, ApplicationVersionDocument
            o.PartitionKeyPaths = new[] { "/id" };
        }
        public static BeatPulseContext AddDocumentDb(this BeatPulseContext context, Action <DocumentDbOptions> options, string name = nameof(DocumentDbLiveness), string defaultPath = "documentdb")
        {
            var documentDbOptions = new DocumentDbOptions();

            options(documentDbOptions);

            context.AddLiveness(name, setup =>
            {
                setup.UsePath(defaultPath);
                setup.UseFactory(sp => new DocumentDbLiveness(documentDbOptions, sp.GetService <ILogger <DocumentDbLiveness> >()));
            });

            return(context);
        }
Exemple #13
0
        private static void MigrateToLatest(RuntimeOptions runtimeOptions, DocumentDbOptions dbOptions)
        {
            var runner = new DocumentDbMigrationRunner(dbOptions);

            if (runtimeOptions.CreateIfNotExists)
            {
                runner.CreateDatabaseIfNotExistsAsync().GetAwaiter().GetResult();
            }

            if (runtimeOptions.MigrateOnStartup)
            {
                runner.CreateCollectionIfNotExistsAsync().GetAwaiter().GetResult();
            }
        }
Exemple #14
0
        static void Main(string[] args)
        {
            DocumentDbOptions dbOptions = new DocumentDbOptions();

            dbOptions.EndpointUrl      = ConfigurationManager.AppSettings["EndPointUrl"];
            dbOptions.AuthorizationKey = ConfigurationManager.AppSettings["AuthorizationKey"];
            dbOptions.DatabaseId       = ConfigurationManager.AppSettings["DatabaseId"];
            dbOptions.CollectionId     = ConfigurationManager.AppSettings["CollectionId"];

            BaseRepository  rep         = new BaseRepository(dbOptions);
            CategoryService catService  = new CategoryService(rep);
            UserService     userService = new UserService(rep);


            //create user
            User newUser = new User();

            newUser.Firstname = "John";
            newUser.Lastname  = "Smith";
            newUser.Email     = "*****@*****.**";
            newUser.Username  = "******";

            User createdUser;

            createdUser = userService.Create(newUser).Result;


            //var k = rep.GetItemAsync<User>("7714f0c0-3dc0-47b5-a859-f3df5e94cbec").Result;
            var r   = rep.GetItemsAsync <User>(p => p.Id == "7714f0c0-3dc0-47b5-a859-f3df5e94cbec").Result;
            var sql = "select * from documents where id = '7714f0c0-3dc0-47b5-a859-f3df5e94cbec'";
            var r1  = rep.GetItemsAsync <User>(sql).Result;
            //create some categories for user
            //for (Int32 i = 0; i < 10; i++)
            //{

            //    Category newCat = new Category();
            //    Category createdCategory;

            //    newCat.Title = "Category " + i.ToString();
            //    newCat.CreateBy = createdUser.Id;
            //    createdCategory = catService.Create(newCat).Result;

            //}

            var allUsers          = rep.GetItemsAsync <User>().Result;
            var allCategories     = rep.GetItemsAsync <Category>().Result;
            var allUserCategories = rep.GetItemsAsync <UserCategories>().Result;

            Console.WriteLine("\n Creating documents");
        }
        public static void Initialize(DocumentDbOptions documentDbOptions)
        {
            // Connect the client
            DocumentClient client = new DocumentClient(new Uri(documentDbOptions.Endpoint), documentDbOptions.Key, new ConnectionPolicy {
                EnableEndpointDiscovery = false
            });

            // Initialize the database
            CreateDatabaseIfNotExistsAsync(client, documentDbOptions.DatabaseId).Wait();

            // create database collections
            CreateCollectionIfNotExistsAsync <RecipeUser>(client, documentDbOptions.DatabaseId).Wait();
            CreateCollectionIfNotExistsAsync <RecipeEntry>(client, documentDbOptions.DatabaseId).Wait();
        }
Exemple #16
0
        private static void MigrateToLatest(BackgroundTaskOptions taskOptions, DocumentDbOptions dbOptions)
        {
            var runner = new DocumentDbMigrationRunner(dbOptions);

            if (taskOptions.Store.CreateIfNotExists)
            {
                runner.CreateDatabaseIfNotExistsAsync().GetAwaiter().GetResult();
            }

            if (taskOptions.Store.MigrateOnStartup)
            {
                runner.CreateCollectionIfNotExistsAsync().GetAwaiter().GetResult();
            }
        }
Exemple #17
0
        /// <summary>
        ///     If you want control over creating the users and roles collections, use this overload.
        ///     This method only registers DocumentDB stores, you also need to call AddIdentity.
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="documentClient"></param>
        /// <param name="collectionFactory">Function containing DocumentCollection</param>
        public static IdentityBuilder RegisterDocumentDBStores <TUser, TRole>(
            this IdentityBuilder builder,
            Action <DocumentDbOptions> documentDbOptions)
            where TRole : IdentityRole
            where TUser : IdentityUser
        {
            var dbOptions = new DocumentDbOptions();

            documentDbOptions(dbOptions);

            if (dbOptions == null)
            {
                throw new ArgumentException("dbOptions cannot be null.");
            }
            if (dbOptions.DocumentUrl == null)
            {
                throw new ArgumentException("DocumentUrl cannot be null.");
            }
            if (dbOptions.DocumentKey == null)
            {
                throw new ArgumentException("DocumentKey cannot be null.");
            }
            if (dbOptions.DatabaseId == null)
            {
                throw new ArgumentException("DatabaseId cannot be null.");
            }
            if (dbOptions.CollectionId == null)
            {
                throw new ArgumentException("CollectionId cannot be null.");
            }

            var documentClient = new DocumentClient(new Uri(dbOptions.DocumentUrl), dbOptions.DocumentKey, dbOptions.ConnectionPolicy);
            var database       = new Database {
                Id = dbOptions.DatabaseId
            };

            database = documentClient.CreateDatabaseIfNotExistsAsync(database).Result;
            var collection = new DocumentCollection {
                Id = dbOptions.CollectionId
            };

            if (dbOptions.PartitionKeyDefinition != null)
            {
                collection.PartitionKey = dbOptions.PartitionKeyDefinition;
            }
            collection = documentClient.CreateDocumentCollectionIfNotExistsAsync(database.AltLink, collection).Result;

            return(RegisterDocumentDBStores <TUser, TRole>(builder, documentClient, (p) => collection));
        }
Exemple #18
0
        private static void MigrateToLatest <TKey>(string connectionString, IdentityOptionsExtended identityOptions,
                                                   DocumentDbOptions options) where TKey : IEquatable <TKey>
        {
            var runner = new MigrationRunner(connectionString, options);

            if (identityOptions.Stores.CreateIfNotExists)
            {
                runner.CreateDatabaseIfNotExistsAsync(CancellationToken.None).Wait();
            }

            if (identityOptions.Stores.MigrateOnStartup)
            {
                runner.MigrateUp(CancellationToken.None);
            }
        }
Exemple #19
0
        public static IBaseRepository GetRepository()
        {
            if (repository == null)
            {
                lock (syncRoot)
                {
                    if (repository == null)
                    {
                        DocumentDbOptions dbOptions = new DocumentDbOptions();
                        dbOptions.EndpointUrl      = ConfigurationManager.AppSettings["EndPointUrl"];
                        dbOptions.AuthorizationKey = ConfigurationManager.AppSettings["AuthorizationKey"];
                        dbOptions.DatabaseId       = ConfigurationManager.AppSettings["DatabaseId"];
                        dbOptions.CollectionId     = ConfigurationManager.AppSettings["CollectionId"];
                        repository = new BaseRepository(dbOptions);
                    }
                }
            }

            return(repository);
        }
Exemple #20
0
        public static IdentityBuilder AddDocumentDbIdentityStore <TKey, TUser, TRole, TTenant, TApplication>(
            this IdentityBuilder identityBuilder,
            Action <DocumentDbOptions> configureAction = null,
            ConnectionScope scope = ConnectionScope.ByRequest)
            where TKey : IEquatable <TKey>
            where TUser : IdentityUserExtended <TKey>
            where TRole : IdentityRoleExtended <TKey>
            where TTenant : IdentityTenant <TKey>
            where TApplication : IdentityApplication <TKey>
        {
            var services = identityBuilder.Services;

            const string slot = Constants.ConnectionSlots.Identity;

            if (configureAction != null)
            {
                services.Configure(slot, configureAction);
            }

            var options = new DocumentDbOptions();

            configureAction?.Invoke(options);

            identityBuilder
            .AddIdentityStores <TKey, TUser, TRole, TTenant, TApplication>();

            var dialect = new DocumentDbDialect();

            SqlBuilder.Dialect = dialect;

            SimpleDataDescriptor.TableNameConvention = s =>
            {
                return(s switch
                {
                    nameof(IdentityRoleExtended) => nameof(IdentityRole),
                    nameof(IdentityUserExtended) => nameof(IdentityUser),
                    _ => s
                });
            };
Exemple #21
0
 public MigrationRunner(string connectionString, DocumentDbOptions options)
 {
     _options = options;
     _builder = new DocumentDbConnectionStringBuilder(connectionString);
     _client  = _builder.Build();
 }
Exemple #22
0
 protected StoreBase(ICosmosClientAccessor clientAccessor, IOptions <DocumentDbOptions> options, string collectionName)
 {
     this.options = options.Value;
     container    = clientAccessor.Client.GetContainer(options.Value.Database, collectionName);
 }
Exemple #23
0
 public DocumentDbCommand(DocumentDbOptions options)
 {
     _options    = options;
     _parameters = new DocumentDbParameterCollection();
 }
 public DocumentDbMigrationRunner(DocumentDbOptions options)
 {
     _options = options;
     Client   = new DocumentClient(options.AccountEndpoint, options.AccountKey, Defaults.JsonSettings);
 }
Exemple #25
0
        public static IdentityBuilder AddDocumentDbIdentityStore <TKey, TUser, TRole, TTenant>(
            this IdentityBuilder identityBuilder,
            string connectionString,
            ConnectionScope scope = ConnectionScope.ByRequest,
            Action <DocumentDbOptions> configureDocumentDb = null)
            where TKey : IEquatable <TKey>
            where TUser : IdentityUserExtended <TKey>
            where TRole : IdentityRoleExtended <TKey>
            where TTenant : IdentityTenant <TKey>
        {
            var services = identityBuilder.Services;

            services.AddSingleton <ITypeRegistry, TypeRegistry>();

            var serviceProvider = services.BuildServiceProvider();
            var builder         = new DocumentDbConnectionStringBuilder(connectionString);

            void ConfigureAction(DocumentDbOptions o)
            {
                configureDocumentDb?.Invoke(o);
                o.DatabaseId   = o.DatabaseId ?? builder.Database;
                o.CollectionId = o.CollectionId ?? builder.DefaultCollection ?? Constants.Identity.DefaultCollection;
            }

            identityBuilder.Services.Configure <DocumentDbOptions>(ConfigureAction);

            var dialect = new DocumentDbDialect();

            identityBuilder.AddSqlStores <DocumentDbConnectionFactory, TKey, TUser, TRole, TTenant>(connectionString,
                                                                                                    scope,
                                                                                                    OnCommand <TKey>(), OnConnection);

            SqlBuilder.Dialect = dialect;

            SimpleDataDescriptor.TableNameConvention = s =>
            {
                switch (s)
                {
                case nameof(IdentityRoleExtended):
                    return(nameof(IdentityRole));

                case nameof(IdentityUserExtended):
                    return(nameof(IdentityUser));

                default:
                    return(s);
                }
            };

            DescriptorColumnMapper.AddTypeMap <TUser>(StringComparer.Ordinal);
            DescriptorColumnMapper.AddTypeMap <TRole>(StringComparer.Ordinal);
            DescriptorColumnMapper.AddTypeMap <TTenant>(StringComparer.Ordinal);

            services.AddMetrics();
            services.AddSingleton(dialect);
            services.AddSingleton <IQueryableProvider <TUser>, DocumentDbQueryableProvider <TUser> >();
            services.AddSingleton <IQueryableProvider <TRole>, DocumentDbQueryableProvider <TRole> >();
            services.AddSingleton <IQueryableProvider <TTenant>, DocumentDbQueryableProvider <TTenant> >();

            var options = new DocumentDbOptions();

            ConfigureAction(options);

            var identityOptions = serviceProvider.GetRequiredService <IOptions <IdentityOptionsExtended> >().Value;

            MigrateToLatest <TKey>(connectionString, identityOptions, options);

            return(identityBuilder);
        }
Exemple #26
0
 public DocumentDbCommand(DocumentDbConnection connection, DocumentDbOptions options) : this(options) => _connection = connection;
Exemple #27
0
 public DocumentDbConnection(DocumentDbOptions options)
 {
     _options = options;
     _builder = new DocumentDbConnectionStringBuilder();
 }
Exemple #28
0
 public DocumentDbConnection(DocumentClient client, DocumentDbOptions options) : this(options) => Client = client;
Exemple #29
0
 public CreateIdentitySchema(DocumentClient client, string databaseId, DocumentDbOptions options)
 {
     _client     = client;
     _databaseId = databaseId;
     _options    = options;
 }
Exemple #30
0
 /// <summary>
 /// Creates a new instance of the <see cref="GetPostsQuery"/> class.
 /// </summary>
 /// <param name="options"></param>
 public GetPostsQuery(DocumentDbOptions options)
     : base(options)
 {
 }