private void Load()
        {
            //Set all service settings from config files.
            CosmosDBCollectionName = Configuration.GetValue <string>("CosmosDBSettings:CosmosDBCollectionName");
            CosmosServiceEndpoint  = Configuration.GetValue <string>("CosmosDBSettings:CosmosServiceEndpoint");
            CosmosDBDatabaseName   = Configuration.GetValue <string>("CosmosDBSettings:CosmosDBDatabaseName");
            CosmosDBKey            = Configuration.GetValue <string>("CosmosDBSettings:CosmosDBKey");
            searchServiceName      = Configuration.GetValue <string>("AzureSearchSettings:searchServiceName");
            queryApiKey            = Configuration.GetValue <string>("AzureSearchSettings:queryApiKey");
            indexName    = Configuration.GetValue <string>("AzureSearchSettings:indexName");
            luisEndPoint = Configuration.GetValue <string>("LuisSettings:luisEndPoint");

            //Open connection with CosmosDB.
            _myStorage = new CosmosDbStorage(new CosmosDbStorageOptions
            {
                AuthKey          = CosmosDBKey,
                CollectionId     = CosmosDBCollectionName,
                CosmosDBEndpoint = new Uri(CosmosServiceEndpoint),
                DatabaseId       = CosmosDBDatabaseName,
            });

            //Create a search index client object to interact with Azure Search Service.
            indexClient = new SearchIndexClient(
                searchServiceName,
                indexName,
                new SearchCredentials(queryApiKey));
        }
Exemple #2
0
        public void ConfigureServices(IServiceCollection services)
        {
            var botConfig = new BotConfig(_configuration);

            services.AddSingleton <BotConfiguration>(botConfig);

            if (_env.IsDevelopment())
            {
                var logger = _loggerFactory.CreateLogger(nameof(ConfigureServices));
                logger.LogInformation($"Bot file secret: {botConfig.Secret}");
                botConfig.Save();
            }

            var storage = new CosmosDbStorage(new CosmosDbStorageOptions {
                CosmosDBEndpoint = new Uri(botConfig.CosmosStorage.Endpoint),
                AuthKey          = botConfig.CosmosStorage.Key,
                DatabaseId       = botConfig.CosmosStorage.Database,
                CollectionId     = botConfig.CosmosStorage.Collection
            });

            var state = new ConversationState(storage);

            services.AddSingleton(state);

            services.AddBot <AisBot> (options => {
                options.Middleware.Add(new AutoSaveStateMiddleware(state));
            });

            services.AddBotApplicationInsights(botConfig);

            services.AddSingleton(new QnAMaker(botConfig.QnAMaker));
        }
Exemple #3
0
        public async Task Database_Creation_Request_Options_Should_Be_Used()
        {
            var documentClientMock = GetDocumentClient();

            var databaseCreationRequestOptions = new RequestOptions {
                OfferThroughput = 1000
            };
            var documentCollectionRequestOptions = new RequestOptions {
                OfferThroughput = 500
            };

            var optionsWithConfigurator = new CosmosDbCustomClientOptions
            {
                CollectionId = "testId",
                DatabaseId   = "testDb",
                DatabaseCreationRequestOptions   = databaseCreationRequestOptions,
                DocumentCollectionRequestOptions = documentCollectionRequestOptions,
            };

            var storage = new CosmosDbStorage(documentClientMock.Object, optionsWithConfigurator);
            await storage.DeleteAsync(new string[] { "foo" }, CancellationToken.None);

            documentClientMock.Verify(client => client.CreateDatabaseIfNotExistsAsync(It.IsAny <Database>(), databaseCreationRequestOptions), Times.Once());
            documentClientMock.Verify(client => client.CreateDocumentCollectionIfNotExistsAsync(It.IsAny <Uri>(), It.IsAny <DocumentCollection>(), documentCollectionRequestOptions), Times.Once());
        }
Exemple #4
0
    public void WithExistingCosmosClient_GetConnection_ReturnsNonNullInstance()
    {
        CosmosDbStorage storage = CreateSutWithCosmosClient();

        using CosmosDbConnection connection = (CosmosDbConnection)storage.GetConnection();
        Assert.NotNull(connection);
    }
        public async Task ReadAsyncWithoutPartitionKey()
        {
            // The WriteAsync method receive a object as a parameter then encapsulate it in a object named "document"
            // The partitionKeyPath must have the "document" value to properly route the values as partitionKey
            // <see also cref="WriteAsync(IDictionary{string, object}, CancellationToken)"/>
            const string partitionKeyPath = "document/city";

            await CreateCosmosDbWithPartitionedCollection(partitionKeyPath);

            // Connect to the cosmosDb created before without partitionKey
            var storage = new CosmosDbStorage(CreateCosmosDbStorageOptions());
            var changes = new Dictionary <string, object>
            {
                { DocumentId, _itemToTest }
            };

            await storage.WriteAsync(changes, CancellationToken.None);

            var badRequestExceptionThrown = false;

            try
            {
                await storage.ReadAsync <StoreItem>(new string[] { DocumentId }, CancellationToken.None);
            }
            catch (DocumentClientException ex)
            {
                badRequestExceptionThrown = ex.StatusCode == HttpStatusCode.BadRequest;
            }

            Assert.True(badRequestExceptionThrown, "Expected: DocumentClientException with HttpStatusCode.BadRequest");

            // TODO: netcoreapp3.0 throws Microsoft.Azure.Documents.BadRequestException which derives from DocumentClientException, but it is internal
            //await Assert.ThrowsAsync<DocumentClientException>(async () => await storage.ReadAsync<StoreItem>(new string[] { DocumentId }, CancellationToken.None));
        }
    public CosmosDbDistributedLockFacts(ContainerFixture containerFixture, ITestOutputHelper testOutputHelper)
    {
        ContainerFixture = containerFixture;
        Storage          = containerFixture.Storage;

        ContainerFixture.SetupLogger(testOutputHelper);
    }
    public JobQueueMonitoringApiFacts(ContainerFixture containerFixture, ITestOutputHelper testOutputHelper)
    {
        ContainerFixture = containerFixture;
        Storage          = containerFixture.Storage;

        ContainerFixture.SetupLogger(testOutputHelper);
    }
Exemple #8
0
        public async Task ReadAsyncWithPartitionKey()
        {
            if (CheckEmulator())
            {
                /// The WriteAsync method receive a object as a parameter then encapsulate it in a object named "document"
                /// The partitionKeyPath must have the "document" value to properly route the values as partitionKey
                /// <seealso cref="WriteAsync(IDictionary{string, object}, CancellationToken)"/>
                var partitionKeyPath = "document/city";

                await CreateCosmosDbWithPartitionedCollection(partitionKeyPath);

                // Connect to the comosDb created before with "Contoso" as partitionKey
                var storage = new CosmosDbStorage(CreateCosmosDbStorageOptions("Contoso"));
                var changes = new Dictionary <string, object>
                {
                    { DocumentId, itemToTest }
                };

                await storage.WriteAsync(changes, CancellationToken.None);

                var result = await storage.ReadAsync <StoreItem>(new string[] { DocumentId }, CancellationToken.None);

                Assert.AreEqual(itemToTest.City, result[DocumentId].City);
            }
        }
Exemple #9
0
        public async Task DeleteAsyncFromPartitionedCollection()
        {
            if (CheckEmulator())
            {
                /// The WriteAsync method receive a object as a parameter then encapsulate it in a object named "document"
                /// The partitionKeyPath must have the "document" value to properly route the values as partitionKey
                /// <seealso cref="WriteAsync(IDictionary{string, object}, CancellationToken)"/>
                var partitionKeyPath = "document/city";

                await CreateCosmosDbWithPartitionedCollection(partitionKeyPath);

                // Connect to the comosDb created before with "Contoso" as partitionKey
                var storage = new CosmosDbStorage(CreateCosmosDbStorageOptions("Contoso"));
                var changes = new Dictionary <string, object>
                {
                    { DocumentId, itemToTest }
                };

                await storage.WriteAsync(changes, CancellationToken.None);

                var result = await Task.WhenAny(storage.DeleteAsync(new string[] { DocumentId }, CancellationToken.None)).ConfigureAwait(false);

                Assert.IsTrue(result.IsCompletedSuccessfully);
            }
        }
Exemple #10
0
    public void WithExistingCosmosClient_GetMonitoringApi_ReturnsNonNullInstance()
    {
        CosmosDbStorage storage = CreateSutWithCosmosClient();
        IMonitoringApi  api     = storage.GetMonitoringApi();

        Assert.NotNull(api);
    }
        public void DeleteOrder()
        {
            OrderControllerTest Controller = new OrderControllerTest();
            var result = CosmosDbStorage <Order> .DeleteAsync(id);

            Assert.IsNotNull(result);
        }
    public ContainerFixture()
    {
        LogProvider.SetCurrentLogProvider(null);

        IConfiguration configuration = new ConfigurationBuilder()
                                       .AddJsonFile("appsettings.json", false, false)
                                       .AddEnvironmentVariables()
                                       .Build();

        IConfigurationSection section = configuration.GetSection("CosmosDB");
        string url       = section.GetValue <string>("Url");
        string secret    = section.GetValue <string>("Secret");
        string database  = section.GetValue <string>("Database");
        string container = section.GetValue <string>("Container");

        CosmosDbStorageOptions option = new()
        {
            CountersAggregateInterval     = TimeSpan.Zero,
            ExpirationCheckInterval       = TimeSpan.Zero,
            QueuePollInterval             = TimeSpan.Zero,
            CountersAggregateMaxItemCount = 1,
            TransactionalLockTimeout      = TimeSpan.Zero
        };

        Storage = CosmosDbStorage.Create(url, secret, database, container, storageOptions: option);
    }
Exemple #13
0
        public void GetProduct_byId()
        {
            ProductController controller = new ProductController();

            var result = CosmosDbStorage <Product> .GetItemsAsync(d => d.InStock == true);

            Assert.IsNotNull(result);
        }
        public void Get_ALL_Orders()
        {
            OrderControllerTest controller = new OrderControllerTest();

            var results = CosmosDbStorage <Order> .GetItemsAsync(o => o.Id != null);

            Assert.IsNotNull(results);
        }
        public void Place_Order()
        {
            OrderControllerTest Controller = new OrderControllerTest();

            var results = CosmosDbStorage <Order> .CreateItemAsync(order);

            Assert.IsNotNull(results);
        }
Exemple #16
0
        public FetchedJob(CosmosDbStorage storage, Documents.Queue data)
        {
            this.storage = storage;
            this.data    = data;

            TimeSpan keepAliveInterval = TimeSpan.FromMinutes(5);

            timer = new Timer(KeepAliveJobCallback, data, keepAliveInterval, keepAliveInterval);
        }
Exemple #17
0
 public ConversationStorage(IConfiguration configuration)
 {
     cosmosDbStorage = new CosmosDbStorage(new CosmosDbStorageOptions
     {
         AuthKey          = configuration["CosmosDBKey"],
         CollectionId     = configuration["ConversationStateCollectionName"],
         CosmosDBEndpoint = new Uri(configuration["CosmosServiceEndpoint"]),
         DatabaseId       = configuration["CosmosDBDatabaseName"],
     });
 }
Exemple #18
0
        public void GetItemsAsync()
        {
            // Arrange
            ProductController controller = new ProductController();

            // Act
            var results = CosmosDbStorage <Product> .GetItemsAsync(p => p.InStock);

            // Assert
            Assert.IsNotNull(results);
        }
Exemple #19
0
        public void Sanatize_Key_Should_Work()
        {
            // Note: The SanatizeKey method delegates to the CosmosDBKeyEscape class. The method is
            // marked as obsolete, and should no longer be used. This test is here to make sure
            // the method does actually delegate, as we can't remove it due to back-compat reasons.
#pragma warning disable 0618
            // Ascii code of "?" is "3f".
            var sanitizedKey = CosmosDbStorage.SanitizeKey("?test?");
            Assert.AreEqual(sanitizedKey, "*3ftest*3f");
#pragma warning restore 0618
        }
        public async Task StatePersistsThroughMultiTurn_TypeNameHandlingNone()
        {
            var storage = new CosmosDbStorage(
                CreateCosmosDbStorageOptions(),
                new JsonSerializer()
            {
                TypeNameHandling = TypeNameHandling.None
            });

            await StatePersistsThroughMultiTurn(storage);
        }
        public new async Task InitializeAsync()
        {
            await base.InitializeAsync();

            Storage = new CosmosDbStorage(new CosmosDbStorageOptions
            {
                AuthKey          = AuthKey,
                CollectionId     = ContainerId,
                CosmosDBEndpoint = new Uri(ServiceEndpoint),
                DatabaseId       = DatabaseId,
            });
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Create the Bot Framework Adapter.
            services.AddSingleton <IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();

            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
            services.AddTransient <IBot, PictureBot>();

            //init bot
            services.AddBot <PictureBot>(options =>
            {
                //read appsettings.json
                var secretKey   = Configuration.GetSection("MicrosoftAppId")?.Value;
                var botFilePath = Configuration.GetSection("MicrosoftAppPassword")?.Value;

                options.CredentialProvider = new SimpleCredentialProvider(secretKey, botFilePath);
            });


            services.AddSingleton <PictureBotAccessors>(sp =>
            {
                var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                if (options == null)
                {
                    throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the state accessors");
                }

                //read Cosmos DB settings from appsettings.json
                CosmosDbStorage _myStorage = new CosmosDbStorage(new CosmosDbStorageOptions
                {
                    AuthKey          = Configuration.GetSection("CosmosDB").GetValue <string>("Key"),
                    CollectionId     = Configuration.GetSection("CosmosDB").GetValue <string>("CollectionName"),
                    CosmosDBEndpoint = new Uri(Configuration.GetSection("CosmosDB").GetValue <string>("EndpointURI")),
                    DatabaseId       = Configuration.GetSection("CosmosDB").GetValue <string>("DatabaseName"),
                });

                var conversationState = new ConversationState(_myStorage);
                var userState         = new UserState(_myStorage);

                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var accessors = new PictureBotAccessors(conversationState, userState)
                {
                    PictureState        = conversationState.CreateProperty <PictureState>(PictureBotAccessors.PictureStateName),
                    DialogStateAccessor = conversationState.CreateProperty <DialogState>("DialogState"),
                };

                return(accessors);
            });
        }
    /// <summary>
    ///     Enables to attach Azure Cosmos DB to Hangfire
    /// </summary>
    /// <param name="configuration">The IGlobalConfiguration object</param>
    /// <param name="cosmosClient">An instance of CosmosClient</param>
    /// <param name="databaseName">The name of the database to connect with</param>
    /// <param name="containerName">The name of the container on the database</param>
    /// <param name="storageOptions">The CosmosDbStorage object to override any of the options</param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public static async Task <IGlobalConfiguration <CosmosDbStorage> > UseAzureCosmosDbStorageAsync(this IGlobalConfiguration configuration, CosmosClient cosmosClient, string databaseName, string containerName,
                                                                                                    CosmosDbStorageOptions?storageOptions = null,
                                                                                                    CancellationToken cancellationToken   = default)
    {
        if (configuration == null)
        {
            throw new ArgumentNullException(nameof(configuration));
        }

        CosmosDbStorage storage = await CosmosDbStorage.CreateAsync(cosmosClient, databaseName, containerName, storageOptions, cancellationToken);

        return(configuration.UseStorage(storage));
    }
        public async Task DeleteAsyncFromSingleCollection()
        {
            var storage = new CosmosDbStorage(CreateCosmosDbStorageOptions());
            var changes = new Dictionary <string, object>
            {
                { DocumentId, _itemToTest }
            };

            await storage.WriteAsync(changes, CancellationToken.None);

            var result = await Task.WhenAny(storage.DeleteAsync(new string[] { DocumentId }, CancellationToken.None)).ConfigureAwait(false);

            Assert.True(result.IsCompletedSuccessfully);
        }
        public void Database_Creation_Request_Options_Should_Be_Used()
        {
            var optionsWithConfigurator = new CosmosDbStorageOptions
            {
                AuthKey          = "test",
                CollectionId     = "testId",
                DatabaseId       = "testDb",
                CosmosDBEndpoint = new Uri("https://test.com"),
                DocumentCollectionRequestOptions = new RequestOptions {
                    OfferThroughput = 1000
                },
            };

            var storage = new CosmosDbStorage(optionsWithConfigurator);
        }
    /// <summary>
    ///     Enables to attach Azure Cosmos DB to Hangfire
    /// </summary>
    /// <param name="configuration">The IGlobalConfiguration object</param>
    /// <param name="cosmosClient">An instance of CosmosClient</param>
    /// <param name="databaseName">The name of the database to connect with</param>
    /// <param name="containerName">The name of the collection on the database</param>
    /// <param name="storageOptions">The CosmosDbStorage object to override any of the options</param>
    /// <returns></returns>
    public static IGlobalConfiguration <CosmosDbStorage> UseAzureCosmosDbStorage(this IGlobalConfiguration configuration, CosmosClient cosmosClient, string databaseName, string containerName, CosmosDbStorageOptions?storageOptions = null)
    {
        if (configuration == null)
        {
            throw new ArgumentNullException(nameof(configuration));
        }
        if (cosmosClient is null)
        {
            throw new ArgumentNullException(nameof(cosmosClient));
        }

        CosmosDbStorage storage = CosmosDbStorage.Create(cosmosClient, databaseName, containerName, storageOptions);

        return(configuration.UseStorage(storage));
    }
Exemple #27
0
        private bool InitializeSkill(DialogContext dc)
        {
            if (dc.ActiveDialog.State.ContainsKey(ActiveSkillStateKey))
            {
                var skill = dc.ActiveDialog.State[ActiveSkillStateKey] as SkillService;

                var cosmosDbOptions = _cosmosDbOptions;
                cosmosDbOptions.CollectionId = skill.Name;
                var cosmosDbStorage   = new CosmosDbStorage(cosmosDbOptions);
                var conversationState = new ConversationState(cosmosDbStorage);

                try
                {
                    var skillType = Type.GetType(skill.Assembly);
                    _activatedSkill = (IBot)Activator.CreateInstance(skillType, conversationState, $"{skill.Name}State", skill.Configuration);
                }
                catch (Exception e)
                {
                    var message = $"Skill ({skill.Name}) Type could not be created.";
                    throw new InvalidOperationException(message, e);
                }

                _inProcAdapter = new InProcAdapter
                {
                    OnTurnError = async(context, exception) =>
                    {
                        await dc.Context.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : exception.Message));

                        await context.SendActivityAsync(context.Activity.CreateReply($"Sorry, something went wrong trying to communicate with the skill. Please try again."));

                        await dc.Context.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"Skill Error: {exception.Message} | {exception.StackTrace}"));

                        _telemetryClient.TrackException(exception);
                    },
                };

                _inProcAdapter.Use(new EventDebuggerMiddleware());
                _inProcAdapter.Use(new AutoSaveStateMiddleware(conversationState));

                skillInitialized = true;
            }
            else
            {
                // No active skill?
            }

            return(skillInitialized);
        }
        public async Task <HttpResponseMessage> AddOrder([System.Web.Mvc.Bind(Include = "Id,ProductId,Quantity,DateOrder,Status,TotalPrice")] Order order)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var result = await CosmosDbStorage <Order> .CreateItemAsync(order);

                    return(new HttpResponseMessage(HttpStatusCode.Created));
                }
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
Exemple #29
0
        public async Task <HttpResponseMessage> UpdatePromotion([System.Web.Mvc.Bind(Include = "PromotionId,PromotionName,StartPromo,EndPromo,CodePromo,PromoEnabled")] Promotion promo)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var result = await CosmosDbStorage <Promotion> .UpdateItemAsync(promo.PromotionId, promo);

                    return(new HttpResponseMessage(HttpStatusCode.OK));
                }
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
        public async Task <HttpResponseMessage> GetProduct(string id)
        {
            try
            {
                var result = await CosmosDbStorage <Product> .GetItemsAsync(d => d.Id == id);

                return(new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.Found,
                    Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "application/json")
                });
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }