コード例 #1
0
        public void AssertJsonSerializer()
        {
            string connectionString = "AccountEndpoint=https://localtestcosmos.documents.azure.com:443/;AccountKey=425Mcv8CXQqzRNCgFNjIhT424GK99CKJvASowTnq15Vt8LeahXTcN5wt3342vQ==;";
            var    configuration    = new CosmosConfiguration(connectionString);

            Assert.IsInstanceOfType(configuration.CosmosJsonSerializer, typeof(CosmosJsonSerializerWrapper));
        }
コード例 #2
0
        public async Task TestCustomJsonSerializer()
        {
            int toStreamCount   = 0;
            int fromStreamCount = 0;

            Mock <CosmosJsonSerializer> mockJsonSerializer = new Mock <CosmosJsonSerializer>();

            //The item object will be serialized with the custom json serializer.
            ToDoActivity testItem = CreateRandomToDoActivity();

            mockJsonSerializer.Setup(x => x.ToStream <ToDoActivity>(It.IsAny <ToDoActivity>())).Callback(() => toStreamCount++).Returns(this.jsonSerializer.ToStream <ToDoActivity>(testItem));
            mockJsonSerializer.Setup(x => x.FromStream <ToDoActivity>(It.IsAny <Stream>())).Callback <Stream>(x => { x.Dispose(); fromStreamCount++; }).Returns(testItem);

            //Create a new cosmos client with the mocked cosmos json serializer
            CosmosConfiguration configuration = TestCommon.GetDefaultConfiguration();

            configuration.UseCustomJsonSerializer(mockJsonSerializer.Object);
            CosmosClient    mockClient    = TestCommon.CreateCosmosClient(configuration);
            CosmosContainer mockContainer = mockClient.Databases[this.database.Id].Containers[this.container.Id];

            //Validate that the custom json serializer is used for creating the item
            CosmosItemResponse <ToDoActivity> response = await mockContainer.Items.CreateItemAsync <ToDoActivity>(partitionKey : testItem.status, item : testItem);

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);

            Assert.AreEqual(1, toStreamCount);
            Assert.AreEqual(1, fromStreamCount);

            await mockContainer.Items.DeleteItemAsync <ToDoActivity>(testItem.status, testItem.id);
        }
コード例 #3
0
        public async Task TestCustomPropertyWithHandler()
        {
            CustomHandler testHandler = new CustomHandler();

            // Add the random guid to the property
            Guid   randomGuid  = Guid.NewGuid();
            string propertyKey = "Test";

            testHandler.UpdateRequestMessage = x => x.Properties[propertyKey] = randomGuid;

            CosmosConfiguration configuration = TestCommon.GetDefaultConfiguration()
                                                .AddCustomHandlers(testHandler);
            CosmosClient customClient = TestCommon.CreateCosmosClient(configuration);

            ToDoActivity testItem = CreateRandomToDoActivity();

            using (CosmosResponseMessage response = await customClient.Databases[this.database.Id].Containers[this.Container.Id].Items.CreateItemStreamAsync(
                       partitionKey: testItem.status,
                       streamPayload: this.jsonSerializer.ToStream(testItem)))
            {
                Assert.IsNotNull(response);
                Assert.IsNotNull(response.RequestMessage);
                Assert.IsNotNull(response.RequestMessage.Properties);
                Assert.AreEqual(randomGuid, response.RequestMessage.Properties[propertyKey]);
            }
        }
        /// <summary>
        /// Initialize a static instance of the <see cref="CosmosClient"/>.
        /// </summary>
        /// <returns></returns>
        private static CosmosClient InitializeCosmosClient()
        {
            string endpoint = configuration["EndPointUrl"];

            if (string.IsNullOrEmpty(endpoint))
            {
                throw new ArgumentNullException("Please specify a valid endpoint in the appSettings.json");
            }

            string authKey = configuration["AuthorizationKey"];

            if (string.IsNullOrEmpty(authKey) || string.Equals(authKey, "Super secret key"))
            {
                throw new ArgumentException("Please specify a valid AuthorizationKey in the appSettings.json");
            }

            var cosmosConfiguration = new CosmosConfiguration(endpoint,
                                                              authKey);
            // Customize client configuration

            var cosmosClient = new CosmosClient(cosmosConfiguration);

            // Optional. Initialize container
            CosmosDatabaseResponse databaseResponse = cosmosClient.Databases.CreateDatabaseIfNotExistsAsync("mydb").Result;
            CosmosDatabase         database         = databaseResponse.Database;

            var containerResponse = database.Containers.CreateContainerIfNotExistsAsync("mycoll", "/id").Result;

            return(cosmosClient);
        }
コード例 #5
0
        private CosmosConfiguration BuildCosmosConfiguration()
        {
            var config = BuildConfig();
            var batch  = new CosmosConfiguration();

            config.GetSection("documents").Bind(batch);
            return(batch);
        }
コード例 #6
0
 public CosmosClientFactory(CosmosConfiguration configuration)
 {
     _client = new CosmosClient(
         configuration.EndpointUrl,
         configuration.PrimaryKey
         );
     _databaseName = configuration.DatabaseName;
 }
コード例 #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CosmosUserRepository{T}"/> class.
        /// </summary>
        /// <param name="cosmosConfiguration">Configuration to create connection with an Azure Cosmos DB Database</param>
        /// <param name="loggerFactory">Logger factory to create a logger</param>
        public CosmosUserRepository(CosmosConfiguration cosmosConfiguration, ILoggerFactory loggerFactory)
            : base(cosmosConfiguration, loggerFactory)
        {
            this.Logger.LogTrace("Beginning construction of Cosmos User Repository");

            this.container = this.CosmosClient.GetContainer(this.DatabaseId, UserBase.ContainerId);

            this.Logger.LogTrace("Construction of Cosmos User Repository complete");
        }
コード例 #8
0
        protected override void ConfigureTransportAndPersistence(IBusConfigurator cfg)
        {
            var mongoCfg = new CosmosConfiguration(_fixture.ConnectionString,
                                                   _fixture.DbName,
                                                   CosmosSagaStateRepositoryOptions.Default,
                                                   CosmosOutboxRepositoryOptions.Default);

            cfg.UseInMemoryTransport()
            .UseCosmosPersistence(mongoCfg);
        }
コード例 #9
0
        /// <summary>
        /// Initialize the db
        /// </summary>
        /// <returns></returns>
        public static async Task InitDbConnection()
        {
            CosmosConfiguration config = new CosmosConfiguration(Endpoint, PrimaryKey);

            client = new CosmosClient(config);
            CosmosDatabase database = await client.Databases.CreateDatabaseIfNotExistsAsync(DatabaseId);

            CosmosContainer container = await database.Containers.CreateContainerIfNotExistsAsync(ContainerId, "/CategoryName");

            items = container.Items;
        }
コード例 #10
0
        public static CosmosClient CreateMockCosmosClient(CosmosRequestHandler preProcessingHandler = null, CosmosConfiguration configuration = null)
        {
            DocumentClient      documentClient      = new MockDocumentClient();
            CosmosConfiguration cosmosConfiguration =
                configuration?.AddCustomHandlers(preProcessingHandler)
                ?? new CosmosConfiguration("http://localhost", Guid.NewGuid().ToString())
                .AddCustomHandlers(preProcessingHandler);

            return(new CosmosClient(
                       cosmosConfiguration,
                       documentClient));
        }
コード例 #11
0
        private static CosmosClient InitializeCosmosClient()
        {
            var connectionString =
                Environment.GetEnvironmentVariable("CosmosDB:ConnectionString");

            var cosmosConfiguration =
                new CosmosConfiguration(connectionString);

            var cosmosClient =
                new CosmosClient(cosmosConfiguration);

            return(cosmosClient);
        }
コード例 #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SearchService"/> class.
        /// </summary>
        /// <param name="loggerFactory">Logger factory for this service</param>
        /// <param name="configuration">Application configuration</param>
        public SearchService(ILoggerFactory loggerFactory, IConfiguration configuration)
            : base(loggerFactory, configuration)
        {
            this.Logger.LogTrace("Construction of Search Service beginning");

            // Build configurations
            var cosmosConfiguration = CosmosConfiguration.BuildFromConfiguration(this.Configuration);
            var searchConfiguration = AzureSearchConfiguration.BuildFromConfiguration(this.Configuration);

            this.userRepository   = new CosmosUserRepository <ReadByAllUser>(cosmosConfiguration, loggerFactory);
            this.searchRepository = new AzureSearchRepository(searchConfiguration, loggerFactory);

            this.Logger.LogTrace("Construction of Search Service complete");
        }
コード例 #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceBase"/> class.
        /// </summary>
        /// <param name="loggerFactory">Logger factory for this service</param>
        /// <param name="configurationMaybeNull">Application configuration</param>
        public ServiceBase(ILoggerFactory loggerFactory, IConfiguration?configurationMaybeNull)
        {
            this.Configuration = Ensure.IsNotNull(() => configurationMaybeNull);

            loggerFactory = Ensure.IsNotNull(() => loggerFactory);
            this.Logger   = loggerFactory.CreateLogger <ServiceBase>();

            // Build cosmos configuration
            var cosmosConfiguration = CosmosConfiguration.BuildFromConfiguration(this.Configuration);

            this.userRepository = new CosmosUserRepository <AdminUser>(cosmosConfiguration, loggerFactory);

            this.Logger.LogTrace("Construction of ServiceBase complete");
        }
コード例 #14
0
        private CosmosConfiguration BuildCosmosConfiguration()
        {
            var configuration = new CosmosConfiguration(_endPoint, _authKey)
            {
                UserAgentSuffix = _userAgent,
                ConnectionMode  = ConnectionMode.Direct
            };

            if (_region != null)
            {
                configuration = configuration.UseCurrentRegion(_region);
            }

            return(configuration);
        }
コード例 #15
0
        protected override void ConfigureTransportAndPersistence(IBusConfigurator cfg)
        {
            var(_, dbName) = _cosmosFixture.CreateDbContext();
            var mongoCfg = new CosmosConfiguration(_cosmosFixture.ConnectionString,
                                                   dbName,
                                                   CosmosSagaStateRepositoryOptions.Default,
                                                   CosmosOutboxRepositoryOptions.Default);

            cfg.UseAzureServiceBusTransport(_sbFixture.Configuration, builder =>
            {
                builder.UseMessageNamingPolicy <StartSimpleSaga>(() =>
                                                                 new QueueReferences(_topicName, _subscriptionName));
            })
            .UseCosmosPersistence(mongoCfg);
        }
コード例 #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Entrypoint"/> class.
        /// </summary>
        public Entrypoint()
        {
            var builder = new ConfigurationBuilder();

            // Tell the builder to look for the appsettings.json file
            builder.AddJsonFile("Properties/appsettings.json", optional: false, reloadOnChange: true);

            // Add user secrets
            builder.AddUserSecrets <Entrypoint>();

            // Build configuration
            var configuration = builder.Build();

            // Build and validate Cosmos Configuration
            this.cosmosConfiguration = CosmosConfiguration.BuildFromConfiguration(configuration);
        }
コード例 #17
0
        public async Task SetUpAsync()
        {
            _configuration = new CosmosConfiguration()
            {
                EndpointUrl         = TestContext.Parameters["EndpointUrl"],
                AuthorizationKey    = TestContext.Parameters["AuthorizationKey"],
                RecipeDatabaseName  = TestContext.Parameters["RecipeDatabaseName"],
                RecipeContainerName = $"integrationtest-{Guid.NewGuid()}"
            };

            var cosmosclient      = new CosmosClient(_configuration.EndpointUrl, _configuration.AuthorizationKey);
            var database          = cosmosclient.GetDatabase(_configuration.RecipeDatabaseName);
            var containerResponse = await database.CreateContainerIfNotExistsAsync(_configuration.RecipeContainerName, "/id");

            _container = containerResponse.Container;
        }
コード例 #18
0
        public void ConfigureServices()
        {
            var services = new ServiceCollection();

            services.AddMemoryCache();

            services.AddOptions();
            services.Configure <SearchConfiguration>(options =>
            {
                Configuration.GetSection("search").Bind(options);
                SearchConfiguration.Validate(options);
            });
            services.Configure <CosmosConfiguration>(options =>
            {
                Configuration.GetSection("documents").Bind(options);
                CosmosConfiguration.Validate(options);
            });
            services.Configure <StorageConfiguration>((config) =>
            {
                Configuration.GetSection("storage").Bind(config);
                StorageConfiguration.Validate(config);
            });
            services.Configure <BatchConfiguration>((config) =>
            {
                Configuration.GetSection("batch").Bind(config);
                BatchConfiguration.Validate(config);
            });

            var armTemplatesMap = new ArmTemplatesMap();

            services.AddSingleton(armTemplatesMap);
            var staticAssetsMap = new StaticAssetsMap();

            services.AddSingleton(staticAssetsMap);

            services.AddSingleton <ApplicationJobs>();
            services.AddSingleton <DatasetStorageService>();
            services.AddSingleton <DatasetOwnersService>();
            services.AddSingleton <DatasetEditStorageService>();
            services.AddSingleton <UserDataStorageService>();
            services.AddSingleton <SasTokenService>();
            services.AddSingleton <ValidationService>();
            services.AddSingleton <DatasetSearchService>();
            services.AddSingleton <FileSearchService>();

            ServiceProvider = services.BuildServiceProvider();
        }
コード例 #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UserService"/> class.
        /// </summary>
        /// <param name="loggerFactory">Logger factory for this service</param>
        /// <param name="configuration">Application configuration</param>
        public UserService(ILoggerFactory loggerFactory, IConfiguration configuration)
            : base(loggerFactory, configuration)
        {
            this.Logger.LogTrace("Construction of User Service beginning");

            // Build user repository
            var cosmosConfiguration = CosmosConfiguration.BuildFromConfiguration(this.Configuration);

            this.userRepository = new CosmosUserRepository <AdminUser>(cosmosConfiguration, loggerFactory);

            // Build AAD Repository
            var azureActiveDirectoryConfiguration = AzureActiveDirectoryConfiguration.BuildFromConfiguration(this.Configuration);

            this.azureActiveDirectoryRepository = new AzureActiveDirectoryRepository(loggerFactory, azureActiveDirectoryConfiguration);

            this.Logger.LogTrace("Construction of User Service complete");
        }
コード例 #20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CosmosRepositoryBase"/> class.
        /// </summary>
        /// <param name="cosmosConfiguration">Configuration to create connection with an Azure Cosmos DB Database</param>
        /// <param name="loggerFactory">Logger factory to create a logger</param>
        public CosmosRepositoryBase(CosmosConfiguration cosmosConfiguration, ILoggerFactory loggerFactory)
            : base(loggerFactory)
        {
            this.Logger.LogTrace("Construction of Cosmos Repository Base starting");

            // Validate input arguments
            cosmosConfiguration = Ensure.IsNotNull(() => cosmosConfiguration);
            cosmosConfiguration.Validate();

            // Set database id
            this.DatabaseId = Ensure.IsNotNullOrWhitespace(() => cosmosConfiguration.DatabaseId);

            this.CosmosClient = CosmosRepositoryBase
                                .CosmosClientFactory
                                .GetCosmosClient(Ensure.IsNotNullOrWhitespace(() => cosmosConfiguration.ConnectionString));

            this.Logger.LogTrace("Construction of Cosmos Repository Base complete");
        }
コード例 #21
0
ファイル: CosmosService.cs プロジェクト: aakashpawar/ToDoList
        public static async Task Initialize(IConfiguration configuration)
        {
            databaseId  = configuration.GetSection("CosmosDb").GetSection("Database").Value ?? "Tasks";
            containerId = configuration.GetSection("CosmosDb").GetSection("Container").Value ?? "Items";
            endpoint    = configuration.GetSection("CosmosDb").GetSection("Endpoint").Value;
            primaryKey  = configuration.GetSection("CosmosDb").GetSection("PrimaryKey").Value;

            var config = new CosmosConfiguration(endpoint, primaryKey);

            client = new CosmosClient(config);

            CosmosDatabase database = await client.Databases.CreateDatabaseIfNotExistsAsync(databaseId);

            CosmosContainer container =
                await database.Containers.CreateContainerIfNotExistsAsync(containerId, "/category");

            items = container.Items;
        }
コード例 #22
0
        public void ThenTheTenantCalledShouldContainCosmosConfigurationForACosmosContainerDefinitionWithDatabaseNameAndContainerName(
            string tenantName,
            string databaseName,
            string containerName)
        {
            InMemoryTenantProvider tenantProvider =
                ContainerBindings.GetServiceProvider(this.scenarioContext).GetRequiredService <InMemoryTenantProvider>();

            ITenant tenant = tenantProvider.GetTenantByName(tenantName)
                             ?? throw new TenantNotFoundException($"Could not find tenant with name '{tenantName}'");

            var containerDefinition = new CosmosContainerDefinition(databaseName, containerName, null);

            CosmosConfiguration tenantConfigItem = tenant.GetCosmosConfiguration(containerDefinition);

            // GetCosmosStorageConfiguration would have thrown an exception if the config didn't exist, but we'll do a
            // not null assertion anyway...
            Assert.IsNotNull(tenantConfigItem);
        }
コード例 #23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var cosmosConfiguration = new CosmosConfiguration();

            Configuration.GetSection("Cosmos").Bind(cosmosConfiguration);

            var testConfiguration = new TestConfiguration();

            Configuration.GetSection("TestData").Bind(testConfiguration);
            services.AddSingleton(testConfiguration);

            services.AddControllers();

            var cosmosClient = InitializeCosmosDb(cosmosConfiguration).GetAwaiter().GetResult();

            services.AddSingleton(new UserPartitionRepository(cosmosClient, cosmosConfiguration.Database, DataConstants.USER_CONTAINER));
            services.AddSingleton(new UserInstitutionPartitionRepository(cosmosClient, cosmosConfiguration.Database, DataConstants.USER_INSTITUTION_CONTAINER));
            services.AddSingleton(new FinancialAccountPartitionRepository(cosmosClient, cosmosConfiguration.Database, DataConstants.FINANCIAL_ACCOUNT_CONTAINER));
            services.AddHostedService <StartupService>();
        }
コード例 #24
0
        private static EnrollmentConfigurationItem[] GetWorkflowConfig(FeatureContext featureContext)
        {
            IConfiguration configuration = ContainerBindings
                                           .GetServiceProvider(featureContext)
                                           .GetRequiredService <IConfiguration>();

            // Note: this next part is using configuration types from the old (v2) Corvus.Tenancy
            // libraries. Unfortunately, this is currently unavoidable because the current version
            // of Marain.TenantManagement.Abstractions defines enrollment mechanism in terms of
            // those older types.

            // Load the config items we need:
            CosmosConfiguration cosmosConfiguration =
                configuration.GetSection("TestCosmosConfiguration").Get <CosmosConfiguration>()
                ?? new CosmosConfiguration();

            cosmosConfiguration.DatabaseName = "endjinspecssharedthroughput";

            BlobStorageConfiguration storageConfiguration =
                configuration.GetSection("TestBlobStorageConfiguration").Get <BlobStorageConfiguration>()
                ?? new BlobStorageConfiguration();

            return(new EnrollmentConfigurationItem[]
            {
                new EnrollmentBlobStorageConfigurationItem
                {
                    Key = "workflowStore",
                    Configuration = storageConfiguration,
                },
                new EnrollmentCosmosConfigurationItem
                {
                    Key = "workflowInstanceStore",
                    Configuration = cosmosConfiguration,
                },
                new EnrollmentBlobStorageConfigurationItem
                {
                    Key = "operationsStore",
                    Configuration = storageConfiguration,
                },
            });
        }
        public static async Task SetupCosmosContainerForRootTenant(FeatureContext featureContext)
        {
            IServiceProvider serviceProvider      = ContainerBindings.GetServiceProvider(featureContext);
            ITenantCosmosContainerFactory factory = serviceProvider.GetRequiredService <ITenantCosmosContainerFactory>();
            ITenantProvider tenantProvider        = serviceProvider.GetRequiredService <ITenantProvider>();

            string containerBase = Guid.NewGuid().ToString();

            CosmosConfiguration config = tenantProvider.Root.GetDefaultCosmosConfiguration();

            config.DatabaseName          = "endjinspecssharedthroughput";
            config.DisableTenantIdPrefix = true;
            tenantProvider.Root.SetDefaultCosmosConfiguration(config);

            Container contentManagementSpecsContainer = await factory.GetContainerForTenantAsync(
                tenantProvider.Root,
                new CosmosContainerDefinition("endjinspecssharedthroughput", $"{containerBase}contentmanagementspecs", Content.PartitionKeyPath, databaseThroughput : 400)).ConfigureAwait(false);

            featureContext.Set(contentManagementSpecsContainer, ContentManagementSpecsContainer);
            featureContext.Set <IContentStore>(new CosmosContentStore(contentManagementSpecsContainer), ContentManagementSpecsContentStore);
        }
コード例 #26
0
        protected override void ConfigureTransportAndPersistence(IBusConfigurator cfg)
        {
            var(_, dbName) = _cosmosFixture.CreateDbContext();
            var cosmosCfg = new CosmosConfiguration(_cosmosFixture.ConnectionString,
                                                    dbName,
                                                    CosmosSagaStateRepositoryOptions.Default,
                                                    CosmosOutboxRepositoryOptions.Default);

            cfg.UseAzureServiceBusTransport(_sbFixture.Configuration, builder =>
            {
                QueueReferencesPolicy <DummyEvent> policy = () =>
                {
                    var sp               = cfg.Services.BuildServiceProvider();
                    var sysInfo          = sp.GetService <SystemInfo>();
                    var subscriptionName = sysInfo.ClientGroup;
                    return(new QueueReferences(_topicName, subscriptionName));
                };

                builder.UseMessageNamingPolicy(policy);
            })
            .UseCosmosPersistence(cosmosCfg);
        }
コード例 #27
0
        public void Initialize()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                          .AddEnvironmentVariables();

            IConfigurationRoot configuration = builder.Build();

            var cosmosConfiguration = new CosmosConfiguration();

            configuration.GetSection("CosmosConfiguration").Bind(cosmosConfiguration);

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddOptions();

            serviceCollection.Configure <CosmosConfiguration>(c =>
            {
                configuration.GetSection("CosmosConfiguration").Bind(c);
            });

            //serviceCollection.AddSingleton<IUserRepository, UserRepository>();
            //serviceCollection.AddSingleton<IRoleRepository, RoleRepository>();

            serviceCollection.AddScoped <IUserRepository, UserRepository>();
            serviceCollection.AddScoped <IUserStore <User>, UserRepository>();

            serviceCollection.AddScoped <IRoleRepository, RoleRepository>();
            serviceCollection.AddScoped <IRoleStore <Role>, RoleRepository>();

            serviceCollection.AddScoped <IPasswordHasher <User>, ApplicationPasswordHasher>();
            serviceCollection.AddScoped <UserManager <User>, ApplicationUserManager>();
            serviceCollection.AddScoped <RoleManager <Role>, ApplicationRoleManager>();
            serviceCollection.AddScoped <SignInManager <User>, ApplicationSignInManager>();

            _serviceProvider = serviceCollection.BuildServiceProvider();
        }
コード例 #28
0
        public static async Task SetupTransientTenant(FeatureContext context)
        {
            // This needs to run after the ServiceProvider has been constructed
            IServiceProvider provider       = ContainerBindings.GetServiceProvider(context);
            ITenantProvider  tenantProvider = provider.GetRequiredService <ITenantProvider>();

            // In order to ensure the Cosmos aspects of the Tenancy setup are fully configured, we need to resolve
            // the ITenantCosmosContainerFactory, which triggers setting default config to the root tenant.
            // HACK: This is a hack until we can come up with a better way of handling deferred initialisation.
            provider.GetRequiredService <ITenantCosmosContainerFactory>();

            ITenant rootTenant      = tenantProvider.Root;
            ITenant transientTenant = await tenantProvider.CreateChildTenantAsync(rootTenant.Id).ConfigureAwait(false);

            CosmosConfiguration config = rootTenant.GetDefaultCosmosConfiguration() ?? new CosmosConfiguration();

            config.DatabaseName          = "endjinspecssharedthroughput";
            config.DisableTenantIdPrefix = true;
            transientTenant.SetDefaultCosmosConfiguration(config);

            await tenantProvider.UpdateTenantAsync(transientTenant).ConfigureAwait(false);

            context.Set(transientTenant);
        }
コード例 #29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddApplicationInsightsTelemetry();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IConfiguration>(Configuration);

            services.AddOptions();
            services.Configure <IdentityProviderConfiguration>(options =>
            {
                Configuration.GetSection("azuread").Bind(options);
                IdentityProviderConfiguration.Validate(options);
            });
            services.Configure <SearchConfiguration>(options =>
            {
                Configuration.GetSection("search").Bind(options);
                SearchConfiguration.Validate(options);
            });
            services.Configure <CosmosConfiguration>(options =>
            {
                Configuration.GetSection("documents").Bind(options);
                CosmosConfiguration.Validate(options);
            });
            services.Configure <StorageConfiguration>((config) =>
            {
                Configuration.GetSection("storage").Bind(config);
                StorageConfiguration.Validate(config);
            });
            services.Configure <BatchConfiguration>((config) =>
            {
                Configuration.GetSection("batch").Bind(config);
                BatchConfiguration.Validate(config);
            });
            services.Configure <AppInsightsConfiguration>((config) =>
            {
                Configuration.GetSection("applicationinsights").Bind(config);
                AppInsightsConfiguration.Validate(config);
            });

            var armTemplatesMap = new ArmTemplatesMap();

            services.AddSingleton(armTemplatesMap);
            var staticAssetsMap = new StaticAssetsMap();

            services.AddSingleton(staticAssetsMap);

            services.AddMemoryCache();



            //services
            //    .AddAuthentication(options =>
            //    {
            //        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            //        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            //    })
            //    .AddJwtBearer(options =>
            //    {
            //        options.Audience = Configuration["azureADConfig:clientId"];
            //        options.Authority = Configuration["azureADConfig:authority"];
            //        options.Events = new JwtBearerEvents
            //        {
            //            OnMessageReceived = FetchAuthTokenFromCookie,
            //            OnTokenValidated = async context =>
            //            {
            //                var principal = context.Principal;
            //                var ODREmailList = Configuration["ODRAdminList"].Split(";");
            //            }
            //        };
            //    });

            //services
            //    .AddAuthentication(options =>
            //    {
            //        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            //    })
            //    .AddJwtBearer(options =>
            //    {
            //        options.Audience = Configuration["azureADConfig:clientId"];
            //        options.Authority = Configuration["azureADConfig:authority"];

            //        options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            //        {
            //            ValidAudience = Configuration["azureADConfig:clientId"],
            //            ValidIssuer = $"https://login.microsoftonline.com/" + Configuration["azureADConfig:tenantId"] + "/v2.0"
            //        };

            //        options.Events = new JwtBearerEvents
            //        {
            //            OnMessageReceived = FetchAuthTokenFromCookie,
            //            //OnTokenValidated = async context =>
            //            //{
            //            //    var principal = context.Principal;

            //            //    if (Configuration.GetChildren().Any(item => item.Key == "ODRAdminList") && principal.Claims.Any(c => c.Type == "preferred_username"))
            //            //    {

            //            //        var ODRAdminsList = Configuration["ODRAdminList"].Split(";").ToList();
            //            //        var testSubject = principal.Claims.FirstOrDefault(c => c.Type == "preferred_username").Value;

            //            //        if (ODRAdminsList.Contains(testSubject))
            //            //        {

            //            //            var claims = new List<Claim>
            //            //            {
            //            //                new Claim(ClaimTypes.Role, "ODRAdmin")
            //            //            };
            //            //            var appIdentity = new ClaimsIdentity(claims);
            //            //            principal.AddIdentity(appIdentity);

            //            //        }
            //            //    }
            //            //}
            //        };
            //    });

            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                var tenantName          = Configuration["AzureAD:Tenant"].Split('.').First();
                var policyName          = Configuration["AzureAD:Policy"];
                var audience            = Configuration["AzureAD:Audience"];
                options.MetadataAddress = $"https://{tenantName}.b2clogin.com/{tenantName}.onmicrosoft.com/{policyName}/v2.0/.well-known/openid-configuration";
                options.Audience        = audience;
                options.Events          = new JwtBearerEvents
                {
                    OnMessageReceived      = FetchAuthTokenFromCookie,
                    OnAuthenticationFailed = context =>
                    {
                        var ctx = context;
                        return(Task.FromResult(0));
                    },
                };
            });

            services.AddMvc();

            services
            .AddAuthorization(options =>
            {
                options.AddPolicy(PolicyNames.MustBeInAdminGroup, policy =>
                {
                    var authorizedAdminUsers = Configuration["AuthorizedAdminUsers"];
                    policy.Requirements.Add(new AzureActiveDirectoryGroupRequirement(authorizedAdminUsers));
                });
            });

            services.AddSingleton <IAuthorizationHandler, AzureActiveDirectoryGroupHandler>();

            //if (CurrentEnvironment.IsDevelopment())
            //{
            //    services.AddSingleton<IAuthorizationHandler, DevelopmentOnlyNoAuthDirectoryGroupHandler>();
            //}
            //else
            //{
            //    services.AddSingleton<IAuthorizationHandler, AzureActiveDirectoryGroupHandler>();
            //}

            services.AddScoped <DatasetSearchService>();
            services.AddScoped <UserDataSearchService>();
            services.AddScoped <DatasetStorageService>();
            services.AddScoped <AppInsightsService>();
            services.AddScoped <UserDataStorageService>();
            services.AddScoped <LicenseStorageService>();
            services.AddScoped <SasTokenService>();
            services.AddScoped <ValidationService>();
            services.AddScoped <ApplicationJobs>();

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ui-app";
            });

            // Add Swagger generator
            if (Configuration.GetValue <bool>("Application:EnableSwagger"))
            {
                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
                    {
                        Title   = "MSR ODR Admin API",
                        Version = "v1"
                    });
                });
            }
        }
コード例 #30
0
        /// <summary>
        /// Adds the runtime services to the instance.
        /// </summary>
        /// <param name="services">The services.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IConfiguration>(this.Configuration);
            services.AddSingleton <ITelemetryInitializer, TelemetryUserAndSessionContext>();
            services.AddApplicationInsightsTelemetry();

            services.AddOptions();
            services.Configure <IdentityProviderConfiguration>(options =>
            {
                Configuration.GetSection("azuread").Bind(options);
                IdentityProviderConfiguration.Validate(options);
            });
            services.Configure <SearchConfiguration>(options =>
            {
                Configuration.GetSection("search").Bind(options);
                SearchConfiguration.Validate(options);
            });
            services.Configure <CosmosConfiguration>(options =>
            {
                Configuration.GetSection("documents").Bind(options);
                CosmosConfiguration.Validate(options);
            });
            services.Configure <StorageConfiguration>((config) =>
            {
                Configuration.GetSection("storage").Bind(config);
                StorageConfiguration.Validate(config);
            });
            services.Configure <WebServerConfiguration>(options =>
            {
                Configuration.GetSection("webserver").Bind(options);
                WebServerConfiguration.Validate(options);
            });
            services.Configure <BatchConfiguration>((config) =>
            {
                Configuration.GetSection("batch").Bind(config);
                BatchConfiguration.Validate(config);
            });

            var armTemplatesMap = Configuration.GetSection("armTemplates").Get <ArmTemplatesMap>();

            services.AddSingleton(armTemplatesMap);
            var staticAssetsMap = Configuration.GetSection("staticAssets").Get <StaticAssetsMap>();

            services.AddSingleton(staticAssetsMap);

            services.AddMemoryCache();

            services.AddCors(options =>
            {
                options.AddPolicy("DefaultPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .WithMethods("GET", "POST", "PUT", "DELETE")
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });

            services.AddResponseCompression(opt =>
            {
                opt.EnableForHttps = true;
            });

            services.AddMvc()
            .AddMvcOptions(options =>
            {
                options.Filters.Add(new TelemetryExceptionFilter(new LoggerFactory()));
            })
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.Converters.Add(new StringEnumConverter
                {
                    CamelCaseText = true
                });
            });

            services.AddScoped <DatasetSearchService>();
            services.AddScoped <FileSearchService>();
            services.AddScoped <DatasetStorageService>();
            services.AddScoped <DatasetOwnersService>();
            services.AddScoped <DatasetEditStorageService>();
            services.AddScoped <UserDataStorageService>();
            services.AddScoped <FileStorageService>();
            services.AddScoped <LicenseStorageService>();
            services.AddScoped <ValidationService>();
            services.AddScoped <SasTokenService>();
            services.AddScoped <GenerateFilePreview>();
            services.AddScoped <CurrentUserService>();
            services.AddScoped <ApplicationJobs>();

            if (this.UseSwagger)
            {
                services.UseSwagger(this.Configuration);
            }

            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                var tenantName          = Configuration["AzureAD:Tenant"].Split('.').First();
                var policyName          = Configuration["AzureAD:Policy"];
                var audience            = Configuration["AzureAD:Audience"];
                options.MetadataAddress = $"https://{tenantName}.b2clogin.com/{tenantName}.onmicrosoft.com/{policyName}/v2.0/.well-known/openid-configuration";
                options.Audience        = audience;
                options.Events          = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        var ctx = context;
                        return(Task.FromResult(0));
                    },
                };
            });
        }