Пример #1
0
        static Shared()
        {
            IConfigurationRoot configurationRoot = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
            string             endpoint          = configurationRoot["CosmosEndpoint"];
            string             masterKey         = configurationRoot["CosmosMasterKey"];

            CosmosClientOptions cosmosClientOptions = new CosmosClientOptions()
            {
                ApplicationName = "Cosmos DB Demos"
            };

            Client = new CosmosClient(endpoint, masterKey, cosmosClientOptions);
        }
Пример #2
0
        public void VerifyCorrectProtocolIsSet()
        {
            CosmosClientOptions cosmosClientOptions = new CosmosClientOptions {
                ConnectionMode = ConnectionMode.Gateway
            };

            Assert.AreEqual(Protocol.Https, cosmosClientOptions.ConnectionProtocol);

            cosmosClientOptions = new CosmosClientOptions {
                ConnectionMode = ConnectionMode.Direct
            };
            Assert.AreEqual(Protocol.Tcp, cosmosClientOptions.ConnectionProtocol);
        }
        public async Task Initialize()
        {
            CosmosClientOptions cosmosClientOptions = new CosmosClientOptions()
            {
                ConnectionMode  = ConnectionMode.Direct,
                ApplicationName = "CosmosStarter",
            };

            _cosmosClient = new CosmosClient(_cosmosConfig.Endpoint, _cosmosConfig.Key, cosmosClientOptions);

            await CreateDatabaseAsync();
            await CreateContainersAsync();
        }
        public CosmosRepository(CosmosDbSettings settings, CosmosClientOptions cosmosClientOptions = null)
        {
            Guard.ArgumentNotNull(settings, nameof(settings));
            Guard.IsNullOrWhiteSpace(settings.ContainerName, nameof(settings.ContainerName));
            Guard.IsNullOrWhiteSpace(settings.ConnectionString, nameof(settings.ConnectionString));
            Guard.IsNullOrWhiteSpace(settings.DatabaseName, nameof(settings.DatabaseName));

            _containerName = settings.ContainerName;
            _partitionKey = settings.PartitionKey;
            _databaseName = settings.DatabaseName;
            _connectionString = settings.ConnectionString;
            _cosmosClientOptions = cosmosClientOptions;
        }
Пример #5
0
        public void Setup()
        {
            var cosmosClientOptions = new CosmosClientOptions()
            {
                ApplicationRegion = "West US 2",
                //ApplicationRegion = "East US 2",
            };

            // Create a new instance of the Cosmos Client
            this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey, cosmosClientOptions);
            this.database     = this.cosmosClient.GetDatabase(databaseId);
            this.container    = this.database.GetContainer(containerId);
        }
Пример #6
0
        public static IServiceCollection AddCosmosProxy(this IServiceCollection services,
                                                        Action <CosmosProxyConfiguration, IConfiguration> configureOptions,
                                                        CosmosClientOptions clientOptions = null)
        {
            services
            .AddTransient <ICosmosProxy, CosmosProxy>()
            .AddSingleton(new CustomCosmosClientOptions {
                CosmosClientOptions = clientOptions
            })
            .AddOptions <CosmosProxyConfiguration>()
            .Configure(configureOptions);

            return(services);
        }
Пример #7
0
        private CosmosClient InitializeClient()
        {
            var options = new CosmosClientOptions
            {
                Serializer = new AuditCosmosSerializer()
            };

            if (CosmosClientOptionsAction != null)
            {
                CosmosClientOptionsAction.Invoke(options);
            }
            CosmosClient = new CosmosClient(EndpointBuilder?.Invoke(), AuthKeyBuilder?.Invoke(), options);
            return(CosmosClient);
        }
Пример #8
0
        public static async Task <int> Main(string[] args)
        {
            var rootCommand = new RootCommand("Utility tool for querying CosmosDB")
            {
                new Option(
                    "--uri",
                    "The CosmosDB URI")
                {
                    Argument = new Argument <string> ()
                },
                new Option(
                    "--key",
                    "The CosmosDB Key")
                {
                    Argument = new Argument <string> ()
                },
                new Option(
                    "--db",
                    "The CosmosDB Database")
                {
                    Argument = new Argument <string> ()
                },
                new Option(
                    "--container",
                    "The CosmosDB container")
                {
                    Argument = new Argument <string> ()
                },
                new Option(
                    "--query",
                    "The CosmosDB query")
                {
                    Argument = new Argument <string> ()
                },
            };

            rootCommand.Handler = CommandHandler.Create <string, string, string, string, string>((Uri, Key, Db, Container, Query) =>
            {
                CosmosClientOptions options = new CosmosClientOptions()
                {
                    AllowBulkExecution = true
                };
                var Client   = new CosmosClient(Uri, Key, options);
                var Database = Client.GetDatabase(Db);

                return(RunQueryAsync(Query, Database.GetContainer(Container)));
            });

            return(rootCommand.InvokeAsync(args).Result);
        }
Пример #9
0
        public static async Task SetupCosmosDbAsync()
        {
            var cosmosClientOptions = new CosmosClientOptions()
            {
                MaxRetryAttemptsOnRateLimitedRequests = 9
            };

            // Create the Cosmon client
            cosmosClient = new CosmosClient(EndpointUri, PrimaryKey, cosmosClientOptions);

            await CreateCosmosDatabaseAsync();

            await CreateCosmosDatabaseContainerAsync();
        }
Пример #10
0
        public CosmosAccountFacade(string accountName, string key, ILogger logger)
        {
            var options = new CosmosClientOptions
            {
                AllowBulkExecution = true
            };

            _accountName = accountName;
            _client      = new CosmosClient(
                $"https://{_accountName}.documents.azure.com:443/",
                key,
                options);
            _logger = logger.AddContext("account", accountName);
        }
        public ToDoItemRepository(ApplicationSettings settings)
        {
            CosmosClientOptions options = new CosmosClientOptions()
            {
                SerializerOptions = new CosmosSerializationOptions()
                {
                    PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase
                }
            };

            _cosmosClient  = new CosmosClient(settings.CosmosConnectionString, options);
            _databaseName  = settings.CosmosDatabaseName;
            _containerName = settings.CosmosContainerName;
        }
Пример #12
0
        public async Task VerifyPkRangeCacheRefreshOnTimeoutsAsync()
        {
            int pkRangeCalls = 0;
            HttpClientHandlerHelper httpHandlerHelper = new();
            List <string>           ifNoneMatchValues = new();

            httpHandlerHelper.RequestCallBack = (request, cancellationToken) =>
            {
                if (!request.RequestUri.ToString().EndsWith("pkranges"))
                {
                    return(null);
                }

                ifNoneMatchValues.Add(request.Headers.IfNoneMatch.ToString());

                pkRangeCalls++;

                // Cause timeout on the init
                if (pkRangeCalls == 1)
                {
                    return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.RequestTimeout)));
                }

                return(null);
            };

            CosmosClientOptions clientOptions = new CosmosClientOptions()
            {
                HttpClientFactory = () => new HttpClient(httpHandlerHelper),
            };

            CosmosClient resourceClient = TestCommon.CreateCosmosClient(clientOptions);

            string dbName        = Guid.NewGuid().ToString();
            string containerName = nameof(PartitionKeyRangeCacheTests);

            Database db = await resourceClient.CreateDatabaseIfNotExistsAsync(dbName);

            Container container = await db.CreateContainerIfNotExistsAsync(
                containerName,
                "/pk",
                400);

            ToDoActivity toDoActivity = ToDoActivity.CreateRandomToDoActivity();
            await container.CreateItemAsync <ToDoActivity>(toDoActivity);

            Assert.AreEqual(3, pkRangeCalls);

            Assert.AreEqual(2, ifNoneMatchValues.Count(x => string.IsNullOrEmpty(x)), "First call is a 408");
        }
Пример #13
0
        private CosmosClient GetCosmosClient(Uri cosmosUrl, string cosmosKey)
        {
            //Include validations for the required parameters.

            //Cosmosclient options
            var cosmosClientOptions = new CosmosClientOptions {
                RequestTimeout = TimeSpan.FromSeconds(60), MaxRetryAttemptsOnRateLimitedRequests = 10, MaxRetryWaitTimeOnRateLimitedRequests = TimeSpan.FromSeconds(60)
            };
            // Create new cosmos client.
            CosmosClient cosmosClient = new CosmosClient(cosmosUrl.AbsoluteUri, cosmosKey, cosmosClientOptions);


            return(cosmosClient);
        }
Пример #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TenantedCosmosWorkflowStoreFactory"/> class.
        /// </summary>
        /// <param name="containerFactory">
        /// The <see cref="ICosmosContainerSourceWithTenantLegacyTransition"/> that will be used to
        /// create underlying <see cref="Container"/> instances for the content stores.
        /// </param>
        /// <param name="optionsFactory">
        /// Gets Cosmos Client options with suitable serialization configuration.
        /// </param>
        /// <param name="logicalDatabaseName">
        /// The logical Cosmos database name to use when creating or retrieving containers.
        /// </param>
        /// <param name="logicalDefinitionContainerName">
        /// The logical name for the Cosmos container that holds workflow definitions.
        /// </param>
        /// <param name="definitionPartitionKeyPath">
        /// The partition key path for the workflow definition Cosmos container.
        /// </param>
        public TenantedCosmosWorkflowStoreFactory(
            ICosmosContainerSourceWithTenantLegacyTransition containerFactory,
            ICosmosOptionsFactory optionsFactory,
            string logicalDatabaseName,
            string logicalDefinitionContainerName,
            string definitionPartitionKeyPath)
        {
            this.containerFactory               = containerFactory;
            this.logicalDatabaseName            = logicalDatabaseName;
            this.logicalDefinitionContainerName = logicalDefinitionContainerName;
            this.definitionPartitionKeyPath     = definitionPartitionKeyPath;

            this.clientOptions = optionsFactory.CreateCosmosClientOptions();
        }
Пример #15
0
        static Shared()
        {
            var config           = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
            var connectionString = config["CosmosDbConnectionString"];
            var clientOptions    = new CosmosClientOptions
            {
                SerializerOptions = new CosmosSerializationOptions
                {
                    PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase
                }
            };

            Client = new CosmosClient(connectionString, clientOptions);
        }
Пример #16
0
        /// <summary>
        /// Main method for the sample.
        /// </summary>
        /// <param name="args">command line arguments.</param>
        public static async Task Main(string[] args)
        {
            BenchmarkOptions options = null;

            Parser.Default.ParseArguments <BenchmarkOptions>(args)
            .WithParsed <BenchmarkOptions>(e => options = e)
            .WithNotParsed <BenchmarkOptions>(e => Program.HandleParseError(e));

            ThreadPool.SetMinThreads(options.MinThreadPoolSize, options.MinThreadPoolSize);

            string accountKey = options.Key;

            options.Key = null; // Don't print

            using (var ct = new ConsoleColoeContext(ConsoleColor.Green))
            {
                Console.WriteLine($"{nameof(CosmosBenchmark)} started with arguments");
                Console.WriteLine("--------------------------------------------------------------------- ");
                Console.WriteLine(JsonConvert.SerializeObject(options, new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    Formatting        = Formatting.Indented,
                }));
                Console.WriteLine("--------------------------------------------------------------------- ");
                Console.WriteLine();
            }

            CosmosClientOptions clientOptions = new CosmosClientOptions()
            {
                ApplicationName = "cosmosdbdotnetbenchmark",
                RequestTimeout  = new TimeSpan(1, 0, 0),
                MaxRetryAttemptsOnRateLimitedRequests = 10,
                MaxRetryWaitTimeOnRateLimitedRequests = TimeSpan.FromSeconds(60),
            };

            using (var client = new CosmosClient(
                       options.EndPoint,
                       accountKey,
                       clientOptions))
            {
                var program = new Program(client);
                await program.RunAsync(options);

                Console.WriteLine("CosmosBenchmark completed successfully.");
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }
Пример #17
0
        private CosmosClientOptions BuildCosmosConfiguration()
        {
            var configuration = new CosmosClientOptions(_endPoint, _authKey)
            {
                ApplicationName = _userAgent,
                ConnectionMode  = ConnectionMode.Direct,
            };

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

            return(configuration);
        }
Пример #18
0
        private static CosmosClient InitializeCosmosClientInstance(IConfigurationSection configurationSection)
        {
            string account = configurationSection.GetSection("Account").Value;
            string key     = configurationSection.GetSection("Key").Value;
            CosmosClientOptions clientOptions = new CosmosClientOptions()
            {
                SerializerOptions = new CosmosSerializationOptions()
                {
                    IgnoreNullValues = true
                }
            };
            CosmosClient client = new CosmosClient(account, key, clientOptions);

            return(client);
        }
Пример #19
0
        public CosmosUtil()
        {
            string uri = Environment.GetEnvironmentVariable("AZURE_IOT_COSMOSDB_SQLDB_URI");
            string key = Environment.GetEnvironmentVariable("AZURE_IOT_COSMOSDB_SQLDB_KEY");

            IReadOnlyList <string> prefRegionsList = getPreferredRegions();

            Console.WriteLine("prefRegionsList: " + JsonConvert.SerializeObject(prefRegionsList));

            CosmosClientOptions options = new CosmosClientOptions {
                ApplicationPreferredRegions = prefRegionsList
            };

            this.client = new CosmosClient(uri, key, options);
        }
Пример #20
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddSingleton((c) => {
                var options             = new CosmosClientOptions();
                string preferredRegions = Environment.GetEnvironmentVariable("CosmosApplicationPreferredRegions");

                if (!string.IsNullOrEmpty(preferredRegions))
                {
                    var regions = preferredRegions.Split(';').ToList();
                    options.ApplicationPreferredRegions = regions;
                }

                return(new CosmosClient(Environment.GetEnvironmentVariable("CosmosDbConnectionString"), options));
            });
        }
        public SingletonCosmosClientWrapper([NotNull] ICosmosSingletonOptions options)
        {
            var configuration = new CosmosClientOptions(options.ServiceEndPoint, options.AuthKeyOrResourceToken)
            {
                ApplicationName = _userAgent,
                ConnectionMode  = ConnectionMode.Direct
            };

            if (options.Region != null)
            {
                configuration.ApplicationRegion = options.Region;
            }

            _options = configuration;
        }
        public DataController()
        {
            string endpointUrl      = ConfigurationManager.AppSettings["dbConnectionUrl"];
            string authorizationKey = ConfigurationManager.AppSettings["dbConnectionKey"];

            databaseId = ConfigurationManager.AppSettings["databaseId"];

            CosmosClientOptions options = new CosmosClientOptions();

            options.ConnectionMode = ConnectionMode.Gateway;

            client = new CosmosClient(endpointUrl, authorizationKey, options);

            database = client.CreateDatabaseIfNotExistsAsync(databaseId).Result;
        }
        public void HttpClientFactoryBuildsConnectionPolicy()
        {
            string endpoint = AccountEndpoint;
            CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(
                accountEndpoint: endpoint,
                authKeyOrResourceToken: MockCosmosUtil.RandomInvalidCorrectlyFormatedAuthKey)
                                                      .WithHttpClientFactory(this.HttpClientFactoryDelegate);
            CosmosClient        cosmosClient  = cosmosClientBuilder.Build(new MockDocumentClient());
            CosmosClientOptions clientOptions = cosmosClient.ClientOptions;

            Assert.AreEqual(clientOptions.HttpClientFactory, this.HttpClientFactoryDelegate);
            ConnectionPolicy policy = clientOptions.GetConnectionPolicy(clientId: 0);

            Assert.AreEqual(policy.HttpClientFactory, this.HttpClientFactoryDelegate);
        }
        /// <inheritdoc/>
        public DefaultCosmosClientProvider(
            CosmosClientOptions cosmosClientOptions,
            IOptions <RepositoryOptions> options)
        {
            _cosmosClientOptions = cosmosClientOptions
                                   ?? throw new ArgumentNullException(
                                             nameof(cosmosClientOptions), "Cosmos Client options are required.");

            _options = options?.Value
                       ?? throw new ArgumentNullException(
                                 nameof(options), "Repository options are required.");

            _lazyCosmosClient = new Lazy <CosmosClient>(
                () => new CosmosClient(_options.CosmosConnectionString, _cosmosClientOptions));
        }
 public CosmosRepo(ILogger logger)
 {
     this.logger = logger;
     if (dbClient == null)
     {
         CosmosClientOptions clientOptions = new CosmosClientOptions()
         {
             AllowBulkExecution            = true,
             ConnectionMode                = ConnectionMode.Gateway,
             GatewayModeMaxConnectionLimit = 300
         };
         dbClient = new CosmosClient("https://localhost:8081/", "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==", clientOptions);
     }
     this._container = GetDBContainerAsync().GetAwaiter().GetResult();
 }
        public async Task TestInitialize()
        {
            CosmosClientOptions clientOptions = new CosmosClientOptions();

            clientOptions.AllowBulkExecution = true;
            CosmosClient client = TestCommon.CreateCosmosClient(clientOptions);

            DatabaseResponse response = await client.CreateDatabaseIfNotExistsAsync(Guid.NewGuid().ToString());

            this.database = response.Database;

            ContainerResponse containerResponse = await this.database.CreateContainerAsync(Guid.NewGuid().ToString(), "/Status", 10000);

            this.container = containerResponse;
        }
Пример #27
0
        public PersonRepository(string endpoint, string authKey, string databaseId, string containerId)
        {
            var clientOptions = new CosmosClientOptions()
            {
                SerializerOptions = new CosmosSerializationOptions
                {
                    IgnoreNullValues     = true,
                    Indented             = false,
                    PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase,
                }
            };

            _cosmosClient    = new CosmosClient(endpoint, authKey, clientOptions);
            _cosmosContainer = _cosmosClient.GetContainer(databaseId, containerId);
        }
Пример #28
0
        // </Main>

        /// <summary>
        /// In scenarios where connection to the Emulator requires disabled SSL verification due to multiple environments.
        /// </summary>
        private static void ConnectToEmulatorWithSslDisabled(
            string endpoint,
            string authKey)
        {
            // For applications running in NET Standard 2.0 compatible frameworks
            {
                // <DisableSSLNETStandard20>
                CosmosClientOptions cosmosClientOptions = new CosmosClientOptions()
                {
                    HttpClientFactory = () =>
                    {
                        HttpMessageHandler httpMessageHandler = new HttpClientHandler()
                        {
                            ServerCertificateCustomValidationCallback = (req, cert, chain, errors) => true
                        };

                        return(new HttpClient(httpMessageHandler));
                    },
                    ConnectionMode = ConnectionMode.Gateway
                };


                CosmosClient client = new CosmosClient(endpoint, authKey, cosmosClientOptions);
                // </DisableSSLNETStandard20>
            }

            // For applications running in NET Standard 2.1+ compatible frameworks
            {
                // <DisableSSLNETStandard21>
                CosmosClientOptions cosmosClientOptions = new CosmosClientOptions()
                {
                    HttpClientFactory = () =>
                    {
                        HttpMessageHandler httpMessageHandler = new HttpClientHandler()
                        {
                            ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                        };

                        return(new HttpClient(httpMessageHandler));
                    },
                    ConnectionMode = ConnectionMode.Gateway
                };


                CosmosClient client = new CosmosClient(endpoint, authKey, cosmosClientOptions);
                // </DisableSSLNETStandard21>
            }
        }
        public async Task AadMockNegativeRefreshRetryTest()
        {
            int    getAadTokenCount = 0;
            string errorMessage     = "Test Failure" + Guid.NewGuid();

            void GetAadTokenCallBack(
                TokenRequestContext context,
                CancellationToken token)
            {
                getAadTokenCount++;
                throw new RequestFailedException(
                          408,
                          errorMessage);
            }

            (string endpoint, string authKey) = TestCommon.GetAccountInfo();
            LocalEmulatorTokenCredential simpleEmulatorTokenCredential = new LocalEmulatorTokenCredential(
                authKey,
                GetAadTokenCallBack);

            CosmosClientOptions clientOptions = new CosmosClientOptions()
            {
                TokenCredentialBackgroundRefreshInterval = TimeSpan.FromSeconds(60)
            };

            Assert.AreEqual(0, getAadTokenCount);
            using (CosmosClient aadClient = new CosmosClient(
                       endpoint,
                       simpleEmulatorTokenCredential,
                       clientOptions))
            {
                Assert.AreEqual(3, getAadTokenCount);
                await Task.Delay(TimeSpan.FromSeconds(1));

                try
                {
                    ResponseMessage responseMessage =
                        await aadClient.GetDatabase(Guid.NewGuid().ToString()).ReadStreamAsync();

                    Assert.Fail("Should throw auth error.");
                }
                catch (CosmosException ce) when(ce.StatusCode == HttpStatusCode.Unauthorized)
                {
                    Assert.IsNotNull(ce.Message);
                    Assert.IsTrue(ce.ToString().Contains(errorMessage));
                }
            }
        }
        public async Task BatchCustomSerializerUsedForPatchAsync()
        {
            CosmosClientOptions clientOptions = new CosmosClientOptions()
            {
                Serializer = new CosmosJsonDotNetSerializer(
                    new JsonSerializerSettings()
                {
                    DateFormatString = "yyyy--MM--dd hh:mm"
                })
            };

            CosmosClient customSerializationClient    = TestCommon.CreateCosmosClient(clientOptions);
            Container    customSerializationContainer = customSerializationClient.GetContainer(BatchTestBase.Database.Id, BatchTestBase.JsonContainer.Id);

            TestDoc testDoc = BatchTestBase.PopulateTestDoc(this.PartitionKey1);

            DateTime patchDate = new DateTime(2020, 07, 01, 01, 02, 03);
            List <PatchOperation> patchOperations = new List <PatchOperation>()
            {
                PatchOperation.CreateAddOperation("/date", patchDate)
            };

            BatchCore batch = (BatchCore) new BatchCore((ContainerInlineCore)customSerializationContainer, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                              .CreateItem(testDoc);

            batch = (BatchCore)batch.PatchItem(testDoc.Id, patchOperations);

            TransactionalBatchResponse batchResponse = await batch.ExecuteAsync();

            BatchSinglePartitionKeyTests.VerifyBatchProcessed(batchResponse, numberOfOperations: 2);

            Assert.AreEqual(HttpStatusCode.Created, batchResponse[0].StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, batchResponse[1].StatusCode);

            JsonSerializerSettings jsonSettings = new JsonSerializerSettings();

            jsonSettings.DateFormatString = "yyyy--MM--dd hh:mm";
            string dateJson = JsonConvert.SerializeObject(patchDate, jsonSettings);

            // regular container
            ItemResponse <dynamic> response = await BatchTestBase.JsonContainer.ReadItemAsync <dynamic>(
                testDoc.Id,
                BatchTestBase.GetPartitionKey(this.PartitionKey1));

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.IsNotNull(response.Resource);
            Assert.IsTrue(dateJson.Contains(response.Resource["date"].ToString()));
        }