예제 #1
0
        /// <summary>
        /// Creates a Cosmos DB database and a container with the specified partition key.
        /// </summary>
        /// <returns></returns>
        private static async Task <CosmosDbClientFactory> InitializeCosmosClientInstanceAsync(IConfigurationSection configurationSection)
        {
            string databaseName = configurationSection.GetSection("DatabaseName").Value;
            string tutorLearningProfilesContainerName = configurationSection.GetSection("TutorLearningProfilesContainerName").Value;
            string chatMessagesContainerName          = configurationSection.GetSection("ChatMessagesContainerName").Value;
            string account = configurationSection.GetSection("Account").Value;
            string key     = configurationSection.GetSection("Key").Value;
            CosmosClientBuilder clientBuilder = new CosmosClientBuilder(account, key);
            var serializerOptions             = new CosmosSerializationOptions
            {
                PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase
            };

            CosmosClient client = clientBuilder
                                  .WithConnectionModeDirect()
                                  .WithSerializerOptions(serializerOptions)
                                  .Build();
            CosmosDbClientFactory cosmosDbService = new CosmosDbClientFactory(client);
            DatabaseResponse      database        = await client.CreateDatabaseIfNotExistsAsync(databaseName);

            await database.Database.CreateContainerIfNotExistsAsync(tutorLearningProfilesContainerName, "/id");

            await database.Database.CreateContainerIfNotExistsAsync(chatMessagesContainerName, "/id");

            return(cosmosDbService);
        }
예제 #2
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            string identificationConfidence = GlobalSettings.GetKeyValue("IdentificationConfidence");

            if (string.IsNullOrEmpty(identificationConfidence))
            {
                AppConstants.IdentificationConfidence = double.Parse(identificationConfidence);
            }
            var checkForDbConsistency = bool.Parse(GlobalSettings.GetKeyValue("checkForDbConsistency"));
            //First register the db client (which is needed for the strongly typed repos)
            var cosmosDbEndpoint = GlobalSettings.GetKeyValue("cosmosDbEndpoint");
            var cosmosDbKey      = GlobalSettings.GetKeyValue("cosmosDbKey");
            var dbClient         = new DocumentClient(
                new Uri(cosmosDbEndpoint),
                cosmosDbKey,
                new ConnectionPolicy {
                EnableEndpointDiscovery = false
            });

            builder.Services.AddSingleton <ICosmosDbClientFactory>((s) =>
            {
                var factory = new CosmosDbClientFactory(
                    AppConstants.DbName,
                    new Dictionary <string, string> {
                    { AppConstants.DbColCrowdDemographics, AppConstants.DbColCrowdDemographicsPartitionKey },
                    { AppConstants.DbColVisitors, AppConstants.DbColVisitorsPartitionKey },
                    { AppConstants.DbColIdentifiedVisitor, AppConstants.DbColIdentifiedVisitorPartitionKey }
                },
                    dbClient);
                if (checkForDbConsistency)
                {
                    factory.EnsureDbSetupAsync().Wait();
                }
                return(factory);
            });

            //Register our cosmos db repository :)
            builder.Services.AddSingleton <ICrowdDemographicsRepository, CrowdDemographicsRepository>();
            builder.Services.AddSingleton <IVisitorsRepository, VisitorsRepository>();
            builder.Services.AddSingleton <IIdentifiedVisitorRepository, IdentifiedVisitorRepo>();

            //builder.Services.AddTransient<IVisitorIdentificationManager>((s) =>
            //{
            //    return new VisitorIdentificationManager(settings.CognitiveKey,
            //        settings.CognitiveEndpoint,
            //        settings.FaceWorkspaceDataFilter,
            //        settings.CosmosDbEndpoint,
            //        settings.CosmosDbKey,
            //        settings.CosmosDBName,
            //        settings.StorageConnection,
            //        settings.PersonsStorageContainer);
            //});

            //If you need further control over Service Bus, you can also inject the repo for it.
            //var serviceBusConnection = GlobalSettings.GetKeyValue("serviceBusConnection");
            //builder.Services.AddSingleton<IAzureServiceBusRepository>((s) =>
            //{
            //    return new AzureServiceBusRepository(serviceBusConnection, AppConstants.SBTopic, AppConstants.SBSubscription);
            //});
        }
예제 #3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            List <string> collectionNames = new List <string>();

            collectionNames.Add("Users");
            collectionNames.Add("Sessions");
            DocumentClient _document = new DocumentClient(new Uri(Configuration["CosmosDB:URL"]),
                                                          Configuration["CosmosDB:PrimaryKey"]);

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            CosmosDbClientFactory myFactory = new CosmosDbClientFactory(Configuration["CosmosDB:DatabaseId"],
                                                                        collectionNames, _document);

            myFactory.EnsureDbSetupAsync().Wait();

            services.TryAddSingleton <IUserRepository, CosmosDBUserRepository>();
            services.TryAddTransient <ICosmosDbClientFactory>(S => new CosmosDbClientFactory(Configuration["CosmosDB:DatabaseId"], collectionNames, _document));
            services.TryAddSingleton <ISessionRepository, CosmosDBSessionRepository>();

            services.AddCustomMembership <CosmosDBMembership>((options) => {
                options.AuthenticationType     = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultPathAfterLogin  = "******";
                options.DefaultPathAfterLogout = "/Account/Login";
            });

            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie((options) =>
            {
                options.LoginPath = new PathString("/account/login");
                options.Events    = new CookieAuthenticationEvents()
                {
                    OnValidatePrincipal = async(c) =>
                    {
                        var membership = c.HttpContext.RequestServices.GetRequiredService <ICustomMembership>();
                        var isValid    = await membership.ValidateLoginAsync(c.Principal);
                        if (!isValid)
                        {
                            c.RejectPrincipal();
                        }
                    }
                };
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddMvc();
            services.AddOptions();
        }
        public async Task GetById_When_called_then_works()
        {
            var client = CosmosDbClientFactory.Create();

            var customer = new Customer {
                FirstName = "FN1", LastName = "LN1"
            };
            await client.Create(customer);

            customer = await client.GetById <Customer>("f094539f-f7d5-4b4a-a52d-c70632a2050c");

            Assert.IsNotNull(customer);
        }
        public async Task FindAll_When_called_then_works()
        {
            var client = CosmosDbClientFactory.Create();

            var customer = new Customer {
                FirstName = "FN1", LastName = "LN1"
            };
            await client.Create(customer);


            var customers = await client.FindAll <Customer>();

            Assert.AreEqual(1, customers.Count);
            Assert.IsNotNull(customers[0]);
        }
        public static IServiceCollection AddCosmosDb(this IServiceCollection services, Uri serviceEndpoint,
                                                     string authKey, string databaseName, List <string> collectionNames)
        {
            var documentClient = new DocumentClient(serviceEndpoint, authKey, new JsonSerializerSettings
            {
                NullValueHandling    = NullValueHandling.Ignore,
                DefaultValueHandling = DefaultValueHandling.Ignore,
                ContractResolver     = new CamelCasePropertyNamesContractResolver()
            });

            documentClient.OpenAsync().Wait();

            var cosmosDbClientFactory = new CosmosDbClientFactory(databaseName, collectionNames, documentClient);

            cosmosDbClientFactory.EnsureDbSetupAsync().Wait();

            services.AddSingleton <ICosmosDbClientFactory>(cosmosDbClientFactory);

            return(services);
        }
예제 #7
0
    public static IServiceCollection AddCosmosDb(this IServiceCollection services, CosmosDbOptions cosmosDbOptions)
    {
        var documentClient = new DocumentClient(cosmosDbOptions.Endpoint, cosmosDbOptions.Key, new JsonSerializerSettings
        {
            NullValueHandling    = NullValueHandling.Ignore,
            DefaultValueHandling = DefaultValueHandling.Ignore,
            ContractResolver     = new CamelCasePropertyNamesContractResolver()
        });

        documentClient.OpenAsync().Wait();

        var collectionNames = cosmosDbOptions.Collections.Select(n => n.Name).ToList();

        var cosmosDbClientFactory = new CosmosDbClientFactory(cosmosDbOptions.DatabaseName, collectionNames, documentClient);

        cosmosDbClientFactory.EnsureDbSetupAsync().Wait();

        services.AddSingleton <ICosmosDbClientFactory>(cosmosDbClientFactory);

        return(services);
    }
예제 #8
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var checkForDbConsistency = bool.Parse(GlobalSettings.GetKeyValue("checkForDbConsistency"));
            //First register the db client (which is needed for the strongly typed repos)
            var cosmosDbEndpoint = GlobalSettings.GetKeyValue("cosmosDbEndpoint");
            var cosmosDbKey      = GlobalSettings.GetKeyValue("cosmosDbKey");
            var dbClient         = new DocumentClient(
                new Uri(cosmosDbEndpoint),
                cosmosDbKey,
                new ConnectionPolicy {
                EnableEndpointDiscovery = false
            });

            builder.Services.AddSingleton <ICosmosDbClientFactory>((s) =>
            {
                var factory = new CosmosDbClientFactory(
                    AppConstants.DbName,
                    new Dictionary <string, string> {
                    { AppConstants.DbColCrowdDemographics, AppConstants.DbColCrowdDemographicsPartitionKey },
                    { AppConstants.DbColVisitors, AppConstants.DbColVisitorsPartitionKey },
                },
                    dbClient);
                if (checkForDbConsistency)
                {
                    factory.EnsureDbSetupAsync().Wait();
                }
                return(factory);
            });

            //Register our cosmos db repository :)
            builder.Services.AddSingleton <ICrowdDemographicsRepository, CrowdDemographicsRepository>();
            builder.Services.AddSingleton <IVisitorsRepository, VisitorsRepository>();

            //If you need further control over Service Bus, you can also inject the repo for it.
            //var serviceBusConnection = GlobalSettings.GetKeyValue("serviceBusConnection");
            //builder.Services.AddSingleton<IAzureServiceBusRepository>((s) =>
            //{
            //    return new AzureServiceBusRepository(serviceBusConnection, AppConstants.SBTopic, AppConstants.SBSubscription);
            //});
        }
        public async Task Find_When_called_then_works()
        {
            var client = CosmosDbClientFactory.Create();

            var customer = new Customer {
                FirstName = "FN1", LastName = "LN1"
            };
            await client.Create(customer);

            customer = new Customer {
                FirstName = "FN2", LastName = "LN2"
            };
            await client.Create(customer);

            var query     = client.CreateQuery <Customer>();
            var customers = await client.Find(query.Where(c => c.FirstName == "FN1"));

            //https://github.com/Azure/azure-cosmos-dotnet-v3/issues/589

            Assert.AreEqual(1, customers.Count);
            Assert.AreEqual("FN1", customers[0].FirstName);
        }
        public VisitorIdentificationManager(string cognitiveKey,
                                            string cognitiveEndpoint,
                                            string faceFilter,
                                            string cosmosDbEndpoint,
                                            string cosmosDbKey,
                                            string cosmosDbName,
                                            string storageConnection,
                                            string storageContainerName)
        {
            key      = cognitiveKey;
            endpoint = cognitiveEndpoint;
            faceWorkspaceDataFilter = faceFilter;

            FaceServiceHelper.ApiKey                = key;
            FaceServiceHelper.ApiEndpoint           = endpoint;
            FaceListManager.FaceListsUserDataFilter = faceWorkspaceDataFilter;

            var dbClient = new DocumentClient(
                new Uri(cosmosDbEndpoint),
                cosmosDbKey,
                new ConnectionPolicy {
                EnableEndpointDiscovery = false
            });

            var dbFactory = new CosmosDbClientFactory(
                cosmosDbName,
                new Dictionary <string, string> {
                { AppConstants.DbColIdentifiedVisitor, AppConstants.DbColIdentifiedVisitorPartitionKey },
                { AppConstants.DbColIdentifiedVisitorGroup, AppConstants.DbColIdentifiedVisitorPartitionKey }
            },
                dbClient);

            identifiedVisitorRepo      = new IdentifiedVisitorRepo(dbFactory);
            identifiedVisitorGroupRepo = new IdentifiedVisitorGroupRepo(dbFactory);

            storageRepo = new AzureBlobStorageRepository(storageConnection, storageContainerName);

            //serviceBusRepo = new AzureServiceBusRepository(serviceBusConnection, AppConstants.SBTopic, AppConstants.SBSubscription);
        }
        public CosmosDbService CreateCosmosDbService()
        {
            var client = CosmosDbClientFactory.Create(Config.CosmosDbOptions);

            return(new CosmosDbService(client));
        }
 public async Task Setup()
 {
     var client      = CosmosDbClientFactory.Create(Config.CosmosDbOptions);
     var bulkService = new CosmosDbService(client);
     await bulkService.DeleteAll <Customer>();
 }