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); }
public override void Configure(IFunctionsHostBuilder builder) { var regionName = Environment.GetEnvironmentVariable(Constants.EnvironmentVariables.RegionName); if (string.IsNullOrWhiteSpace(regionName)) { // Default to EastUS2 if the environment variable is missing/empty. regionName = Regions.EastUS2; } // Register the CosmosClient as a Singleton // Optimize for preferred geo-region builder.Services.AddSingleton((s) => { CosmosClientBuilder configurationBuilder = new CosmosClientBuilder(Configuration[Constants.CosmosDb.Connection]) .WithApplicationRegion(regionName); return(configurationBuilder.Build()); }); // Load configuration from Azure App Configuration ConfigurationBuilder.AddAzureAppConfiguration(options => { // Use ".Connect(...)" for connection string, or use ".ConnectWithManagedIdentity(...) for managed identity" options.Connect(Environment.GetEnvironmentVariable("AzureAppConfigConnectionString")) // Load all keys that start with `EnterpriseServerless:` .Select("EnterpriseServerless:*") // Configure to reload configuration if the registered 'Sentinel' key is modified .ConfigureRefresh(refreshOptions => refreshOptions.Register(key: "EnterpriseServerless:Sentinel", label: LabelFilter.Null, refreshAll: true) .SetCacheExpiration(TimeSpan.FromSeconds(30)) ) // Indicate to load feature flags .UseFeatureFlags(); ConfigurationRefresher = options.GetRefresher(); }); Configuration = ConfigurationBuilder.Build(); builder.Services.AddLogging(); builder.Services.AddSingleton(Configuration); builder.Services.AddSingleton(ConfigurationRefresher); builder.Services.AddFeatureManagement(Configuration); builder.Services.AddSingleton <IStartCallService, StartCallService>(); builder.Services.AddSingleton <ICallLoggingService, CallLoggingService>(); builder.Services.AddSingleton <IMediaFileService, MediaFileService>(); builder.Services.AddSingleton <IPostCallService, PostCallService>(); }
public static CosmosClient CreateMockCosmosClient( Action <CosmosClientBuilder> customizeClientBuilder = null, Cosmos.ConsistencyLevel?accountConsistencyLevel = null, bool enableTelemetry = false) { DocumentClient documentClient = accountConsistencyLevel.HasValue ? new MockDocumentClient(accountConsistencyLevel.Value) : new MockDocumentClient(); CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder("http://localhost", MockCosmosUtil.RandomInvalidCorrectlyFormatedAuthKey); customizeClientBuilder?.Invoke(cosmosClientBuilder); if (enableTelemetry) { cosmosClientBuilder.WithTelemetryEnabled(); } return(cosmosClientBuilder.Build(documentClient)); }
public void HttpClientFactoryBuildsConnectionPolicy() { string endpoint = AccountEndpoint; string key = Guid.NewGuid().ToString(); CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder( accountEndpoint: endpoint, authKeyOrResourceToken: key) .WithHttpClientFactory(this.HttpClientFactoryDelegate); CosmosClient cosmosClient = cosmosClientBuilder.Build(new MockDocumentClient()); CosmosClientOptions clientOptions = cosmosClient.ClientOptions; Assert.AreEqual(clientOptions.HttpClientFactory, this.HttpClientFactoryDelegate); ConnectionPolicy policy = clientOptions.GetConnectionPolicy(); Assert.AreEqual(policy.HttpClientFactory, this.HttpClientFactoryDelegate); }
public override void Configure(IFunctionsHostBuilder builder) { // Register the Cosmos DB client as a Singleton. builder.Services.AddSingleton((s) => { var connectionString = configuration["CosmosDBConnection"]; var cosmosDbConnectionString = new CosmosDbConnectionString(connectionString); if (string.IsNullOrEmpty(connectionString)) { throw new ArgumentNullException("Please specify a value for CosmosDBConnection in the local.settings.json file or your Azure Functions Settings."); } CosmosClientBuilder configurationBuilder = new CosmosClientBuilder(cosmosDbConnectionString.ServiceEndpoint.OriginalString, cosmosDbConnectionString.AuthKey).WithBulkExecution(true); return(configurationBuilder .Build()); }); }
public async Task ReadManyExceptionsTest(HttpStatusCode statusCode) { RequestHandler[] requestHandlers = new RequestHandler[1]; requestHandlers[0] = new CustomHandler(statusCode); CosmosClientBuilder builder = TestCommon.GetDefaultConfiguration(); builder.AddCustomHandlers(requestHandlers); CosmosClient client = builder.Build(); Database database = await client.CreateDatabaseAsync(Guid.NewGuid().ToString()); Container container = await database.CreateContainerAsync(Guid.NewGuid().ToString(), "/pk"); for (int i = 0; i < 5; i++) { await container.CreateItemAsync( ToDoActivity.CreateRandomToDoActivity("pk" + i, i.ToString())); } List <(string, PartitionKey)> itemList = new List <(string, PartitionKey)>(); for (int i = 0; i < 5; i++) { itemList.Add(("IncorrectId" + i, new PartitionKey("pk" + i))); // wrong ids } using (ResponseMessage responseMessage = await container.ReadManyItemsStreamAsync(itemList)) { Assert.AreEqual(responseMessage.StatusCode, statusCode); } try { await container.ReadManyItemsAsync <ToDoActivity>(itemList); Assert.Fail("Typed API should throw"); } catch (CosmosException ex) { Assert.AreEqual(ex.StatusCode, statusCode); } await database.DeleteAsync(); client.Dispose(); }
public CosmosClient CreateClient( string connectionString, string currentRegion = null) { if (string.IsNullOrEmpty(connectionString)) { throw new ArgumentNullException(nameof(connectionString)); } CosmosClientBuilder clientBuilder = new CosmosClientBuilder(connectionString); if (!string.IsNullOrEmpty(currentRegion)) { clientBuilder.WithApplicationRegion(currentRegion); } return(clientBuilder.Build()); }
public static IServiceCollection AddCosmosDbMovieService(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } ICosmosDbMovieService Factory(IServiceProvider sp) { var logger = sp.GetService <ILogger <CosmosDbMovieService> >(); var options = sp.GetService <IOptions <CosmosDbClientSettings> >(); var cosmosSettings = options.Value; if (string.IsNullOrEmpty(cosmosSettings.EndPointUrl)) { throw new ArgumentException("Please specify a valid endpoint in the appSettings.json file or your Azure Functions Settings."); } if (string.IsNullOrEmpty(cosmosSettings.AuthorizationKey)) { throw new ArgumentException("Please specify a valid AuthorizationKey in the appSettings.json file or your Azure Functions Settings."); } var clientBuilder = new CosmosClientBuilder(cosmosSettings.EndPointUrl, cosmosSettings.AuthorizationKey); var client = clientBuilder.Build(); var cosmosDbMovieService = new CosmosDbMovieService(logger, client, cosmosSettings.DatabaseName, cosmosSettings.ContainerName); async void Handler(object sender, EventArgs args) { InitializeDatabase -= Handler; var databaseResponse = await client.CreateDatabaseIfNotExistsAsync(cosmosSettings.DatabaseName); await databaseResponse.Database.CreateContainerIfNotExistsAsync(cosmosSettings.ContainerName, "/MovieId"); } InitializeDatabase += Handler; InitializeDatabase(null, EventArgs.Empty); // raise event to initialize return(cosmosDbMovieService); } services.AddSingleton(Factory); return(services); }
public override void Configure(IFunctionsHostBuilder builder) { // Add a new HttpClientFactory that can be injected into the functions. // We add resilience and transient fault-handling capabilities to the HttpClient instances that the factory creates // by adding a Polly Retry policy with a very brief back-off starting at quarter-of-a-second to two seconds. // We want the HTTP requests that are sent to the downstream Logic App service to wait before attempting to try // sending the message, giving it some "breathing room" in case the service is overwhelmed. We chose to make // the time between retries relatively brief so as not to disrupt Cosmos DB message processing for too long, but // enough time to hopefully allow the downstream service to recover. // See the following for more information: // https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-http-call-retries-exponential-backoff-polly builder.Services.AddHttpClient(NamedHttpClients.LogicAppClient, client => { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); }) .AddTransientHttpErrorPolicy(policyBuilder => policyBuilder.WaitAndRetryAsync(new[] { TimeSpan.FromMilliseconds(250), TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(1000), TimeSpan.FromMilliseconds(2000) })); // Register the Cosmos DB client as a Singleton. builder.Services.AddSingleton((s) => { var connectionString = configuration["CosmosDBConnection"]; var cosmosDbConnectionString = new CosmosDbConnectionString(connectionString); if (string.IsNullOrEmpty(connectionString)) { throw new ArgumentNullException("Please specify a value for CosmosDBConnection in the local.settings.json file or your Azure Functions Settings."); } CosmosClientBuilder configurationBuilder = new CosmosClientBuilder(cosmosDbConnectionString.ServiceEndpoint.OriginalString, cosmosDbConnectionString.AuthKey); return(configurationBuilder .Build()); }); // Create Azure Storage queue client reference and create any queues that do not yet exist, through the // CreateKnownAzureQueues method. builder.Services.Configure <AzureStorageSettings>(configuration); StorageQueuesHelper.CreateKnownAzureQueues(configuration["ColdStorageAccount"]); builder.Services.AddTransient <IQueueResolver, QueueResolver>(); }
private static Lazy <CosmosClient> SetupClient(ICosmosContainerOptions options) { var csb = ValidatInput(options.ConnectionString, options.DatabaseId, options.ContainerId); var cacheKey = $"{options.DatabaseId}_{options.UseGatewayMode}_{ToSHA256(csb.Key)}"; return(new Lazy <CosmosClient>(() => { CosmosClient client = null; bool fromCache = false; if (_clientCache.ContainsKey(cacheKey)) { client = _clientCache[cacheKey]; if (client != null) { fromCache = true; } } if (!fromCache) { var builder = new CosmosClientBuilder(options.ConnectionString); builder .WithThrottlingRetryOptions(TimeSpan.FromSeconds(30), 10); if (options.UseGatewayMode) { builder.WithConnectionModeGateway(options.ConcurrentConnections); } foreach (var region in options.AzureRegions ?? new List <string>()) { builder.WithApplicationRegion(region); } client = builder.Build(); _clientCache[cacheKey] = client; } CreateDatabaseIfNotExistsAsync(client, options).GetAwaiter().GetResult(); return client; })); }
public async Task QueryActivityIdTests() { RequestHandler[] requestHandlers = new RequestHandler[1]; requestHandlers[0] = new CustomHandler(); CosmosClientBuilder builder = TestCommon.GetDefaultConfiguration(); builder.AddCustomHandlers(requestHandlers); CosmosClient cosmosClient = builder.Build(); Database database = await cosmosClient.CreateDatabaseAsync(Guid.NewGuid().ToString()); Container container = await database.CreateContainerAsync(Guid.NewGuid().ToString(), "/pk", throughput : 12000); // Create items for (int i = 0; i < 500; i++) { await container.CreateItemAsync <ToDoActivity>(ToDoActivity.CreateRandomToDoActivity()); } QueryRequestOptions queryRequestOptions = new QueryRequestOptions { MaxItemCount = 50 }; FeedIterator <ToDoActivity> feedIterator = container.GetItemQueryIterator <ToDoActivity>( "select * from c", null, queryRequestOptions); while (feedIterator.HasMoreResults) { await feedIterator.ReadNextAsync(); } await database.DeleteAsync(); cosmosClient.Dispose(); }
public void VerifyHttpClientHandlerIsSet() { string endpoint = AccountEndpoint; string key = "425Mcv8CXQqzRNCgFNjIhT424GK99CKJvASowTnq15Vt8LeahXTcN5wt3342vQ=="; IWebProxy webProxy = new TestWebProxy(); CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder( accountEndpoint: endpoint, authKeyOrResourceToken: key); cosmosClientBuilder.WithConnectionModeGateway( maxConnectionLimit: null, webProxy: webProxy); CosmosClient cosmosClient = cosmosClientBuilder.Build(); CosmosHttpClient cosmosHttpClient = cosmosClient.DocumentClient.httpClient; HttpClientHandler handler = (HttpClientHandler)cosmosHttpClient.HttpMessageHandler; Assert.IsTrue(object.ReferenceEquals(webProxy, handler.Proxy)); }
public static IServiceCollection AddDataAccessDependencies(this IServiceCollection serviceCollection, IConfiguration configuration) { _ = configuration ?? throw new ArgumentNullException(nameof(configuration)); serviceCollection.Configure <CosmosConfiguration>(cc => configuration.Bind("CosmosConfiguration", cc)); serviceCollection.AddSingleton <IAzureServiceTokenProviderWrapper, AzureServiceTokenProviderWrapper>(); serviceCollection.AddSingleton((sp) => { var options = sp.GetRequiredService <IOptions <CosmosConfiguration> >(); var cosmosConfiguration = options.Value; var cosmosClientBuilder = new CosmosClientBuilder(cosmosConfiguration.EndpointLocation, cosmosConfiguration.PrimaryKey); return(cosmosClientBuilder .Build()); }); serviceCollection.AddSingleton(typeof(ICosmosClientWrapper <>), typeof(CosmosClientWrapper <>)); serviceCollection.AddSingleton(typeof(IDataRepository <>), typeof(DataRepository <>)); return(serviceCollection); }
public static CosmosClient CreateMockCosmosClient( bool useCustomSerializer = false, Action <CosmosClientBuilder> customizeClientBuilder = null) { DocumentClient documentClient = new MockDocumentClient(); CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder("http://localhost", Guid.NewGuid().ToString()); cosmosClientBuilder.WithConnectionModeDirect(); customizeClientBuilder?.Invoke(cosmosClientBuilder); if (useCustomSerializer) { cosmosClientBuilder.WithSerializerOptions( new CosmosSerializationOptions() { IgnoreNullValues = true, }); } return(cosmosClientBuilder.Build(documentClient)); }
public static CosmosClient CreateMockCosmosClient( Action <CosmosClientBuilder> customizeClientBuilder = null, Cosmos.ConsistencyLevel?accountConsistencyLevel = null) { DocumentClient documentClient; if (accountConsistencyLevel.HasValue) { documentClient = new MockDocumentClient(accountConsistencyLevel.Value); } else { documentClient = new MockDocumentClient(); } CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder("http://localhost", MockCosmosUtil.RandomInvalidCorrectlyFormatedAuthKey); customizeClientBuilder?.Invoke(cosmosClientBuilder); return(cosmosClientBuilder.Build(documentClient)); }
/// <summary> /// Protected Constructor /// </summary> /// <param name="settings"></param> /// <param name="connectionPolicy"></param> /// <param name="logger"></param> protected CosmosDbContextBase( IOptions <CosmosDbConfiguration> settings, ConnectionPolicy connectionPolicy = null, ILogger logger = null) { Guard.ForNullOrDefault(settings.Value, nameof(settings)); Guard.ForNullOrDefault(settings.Value.EndPointUrl, nameof(settings.Value.EndPointUrl)); Guard.ForNullOrDefault(settings.Value.PrimaryKey, nameof(settings.Value.PrimaryKey)); _logger = logger; Configuration = settings.Value; var serviceEndPoint = new Uri(settings.Value.EndPointUrl); if (Configuration.DangerousAcceptAnyServerCertificateValidator) { CosmosClientOptions cosmosClientOptions = new CosmosClientOptions() { HttpClientFactory = () => { HttpMessageHandler httpMessageHandler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator }; return(new HttpClient(httpMessageHandler)); }, ConnectionMode = Microsoft.Azure.Cosmos.ConnectionMode.Gateway }; CosmosClient = new CosmosClient(serviceEndPoint.AbsoluteUri, settings.Value.PrimaryKey, cosmosClientOptions); } else { CosmosClientBuilder configurationBuilder = new CosmosClientBuilder(serviceEndPoint.AbsoluteUri, settings.Value.PrimaryKey); CosmosClient = configurationBuilder.Build(); } // DocumentClient = new DocumentClient(serviceEndPoint, settings.Value.PrimaryKey,connectionPolicy ?? ConnectionPolicy.Default); // EnsureDatabaseCreated(Configuration.DatabaseName).Wait(); }
public override void Configure(IFunctionsHostBuilder builder) { // Register the CosmosClient as a Singleton builder.Services.AddSingleton((s) => { string endpoint = configuration["EndPointUrl"]; if (string.IsNullOrEmpty(endpoint)) { throw new ArgumentNullException("Please specify a valid endpoint in the appSettings.json file or your Azure Functions Settings."); } 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 file or your Azure Functions Settings."); } CosmosClientBuilder configurationBuilder = new CosmosClientBuilder(endpoint, authKey); return(configurationBuilder .Build()); }); }
/// <summary> /// Protected Constructor /// </summary> /// <param name="settings"></param> /// <param name="connectionPolicy"></param> /// <param name="logger"></param> protected CosmosDbContextBase( IOptions <CosmosDbConfiguration <T> > settings, ConnectionPolicy connectionPolicy = null, ILogger logger = null) { Guard.ForNullOrDefault(settings.Value, nameof(settings)); Guard.ForNullOrDefault(settings.Value.EndPointUrl, nameof(settings.Value.EndPointUrl)); Guard.ForNullOrDefault(settings.Value.PrimaryKey, nameof(settings.Value.PrimaryKey)); Guard.ForNullOrDefault(settings.Value.DatabaseName, nameof(settings.Value.EndPointUrl)); Logger = logger; Configuration = settings.Value; var serviceEndPoint = new Uri(settings.Value.EndPointUrl); CosmosClientBuilder configurationBuilder = new CosmosClientBuilder(serviceEndPoint.AbsoluteUri, settings.Value.PrimaryKey); CosmosClient = configurationBuilder.Build(); DocumentClient = new DocumentClient(serviceEndPoint, settings.Value.PrimaryKey, connectionPolicy ?? ConnectionPolicy.Default); EnsureDatabaseCreated(Configuration.DatabaseName).Wait(); }
public static CosmosClient CreateMockCosmosClient( bool useCustomSerializer = false, bool?isClientTelemetryEnabled = null, Action <CosmosClientBuilder> customizeClientBuilder = null) { MockDocumentClient documentClient = new MockDocumentClient(); CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder("http://localhost", Convert.ToBase64String(Guid.NewGuid().ToByteArray())); cosmosClientBuilder.WithConnectionModeDirect(); customizeClientBuilder?.Invoke(cosmosClientBuilder); if (useCustomSerializer) { cosmosClientBuilder.WithSerializerOptions( new CosmosSerializationOptions() { IgnoreNullValues = true, }); } if (isClientTelemetryEnabled.HasValue && isClientTelemetryEnabled.Value) { cosmosClientBuilder.WithTelemetryEnabled(); } documentClient.dummyHeaderNames = new string[100]; for (int i = 0; i < documentClient.dummyHeaderNames.Length; i++) { documentClient.dummyHeaderNames[i] = Guid.NewGuid().ToString(); } documentClient.dummyHeaderNames[0] = HttpConstants.HttpHeaders.ActivityId; documentClient.dummyHeaderNames[1] = HttpConstants.HttpHeaders.SessionToken; documentClient.dummyHeaderNames[2] = HttpConstants.HttpHeaders.ConsistencyLevel; documentClient.dummyHeaderNames[3] = HttpConstants.HttpHeaders.XDate; return(cosmosClientBuilder.Build(documentClient)); }
/// <inheritdoc /> public CosmosClient CreateCosmosClient(CosmosDataStoreConfiguration configuration) { EnsureArg.IsNotNull(configuration, nameof(configuration)); var host = configuration.Host; var key = configuration.Key; if (string.IsNullOrWhiteSpace(host) && string.IsNullOrWhiteSpace(key)) { _logger.LogWarning("No connection string provided, attempting to connect to local emulator."); host = CosmosDbLocalEmulator.Host; key = CosmosDbLocalEmulator.Key; } _logger.LogInformation("Creating CosmosClient instance for {DatabaseId}, Host: {Host}", configuration.DatabaseId, host); IEnumerable <RequestHandler> requestHandlers = _requestHandlerFactory.Invoke(); var builder = new CosmosClientBuilder(host, key) .WithConnectionModeDirect(enableTcpConnectionEndpointRediscovery: true) .WithCustomSerializer(new FhirCosmosSerializer()) .WithThrottlingRetryOptions(TimeSpan.FromSeconds(configuration.RetryOptions.MaxWaitTimeInSeconds), configuration.RetryOptions.MaxNumberOfRetries) .AddCustomHandlers(requestHandlers.ToArray()); if (configuration.PreferredLocations?.Any() == true) { builder.WithApplicationPreferredRegions(configuration.PreferredLocations?.ToArray()); } if (configuration.DefaultConsistencyLevel != null) { builder.WithConsistencyLevel(configuration.DefaultConsistencyLevel.Value); } return(builder.Build()); }
private static CosmosClient CreateCosmosClient(string connectionString, CosmosOptions cosmosOptions) { GuardEmptyString(connectionString, "cosmosDbConnectionString"); cosmosOptions.Guard(); var builder = new CosmosClientBuilder(connectionString); // ConnectionPolicy のDefault値は、SDKのConnectionPolicy.csで設定されています。 // ## Connection Mode について // Default で ConnectionMode.Direct/Protocol.Tcp で接続されます。 // もしGateway(ConnectionMode.Gateway/Protocol.Https) を使いたければ、以下メソッドを呼ぶ // builder.UseConnectionModeGateway(maxConnectionLimit: ??); // Default: CamelCase Serialize/Deserialize and ignore Readonly property // TODO: 設定変更用のconfigは未実装 //var settings = JsonSerializerSettingsFactory.CreateForReadonlyIgnoreAndCamelCase(); var settings = JsonSerializerSettingsFactory.CreateForCamelCase(); builder.WithCustomSerializer(new CustomizableCaseJsonSerializer(settings)); if (cosmosOptions.ThrottlingRetryOptions != null) { builder.WithThrottlingRetryOptions( cosmosOptions.ThrottlingRetryOptions.MaxRetryWaitTimeOnThrottledRequests, cosmosOptions.ThrottlingRetryOptions.MaxRetryAttemptsOnThrottledRequests); } // multi-master support if (!string.IsNullOrEmpty(cosmosOptions.CurrentRegion)) { builder.WithApplicationRegion(cosmosOptions.CurrentRegion); } return(builder.Build()); }
public static CosmosClient CreateMockCosmosClient( Action <CosmosClientBuilder> customizeClientBuilder = null, Cosmos.ConsistencyLevel?accountConsistencyLevel = null) { DocumentClient documentClient; if (accountConsistencyLevel.HasValue) { documentClient = new MockDocumentClient(accountConsistencyLevel.Value); } else { documentClient = new MockDocumentClient(); } CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder("http://localhost", Guid.NewGuid().ToString()); if (customizeClientBuilder != null) { customizeClientBuilder(cosmosClientBuilder); } return(cosmosClientBuilder.Build(documentClient)); }
public void VerifyCosmosConfigurationPropertiesGetUpdated() { string endpoint = AccountEndpoint; string key = MockCosmosUtil.RandomInvalidCorrectlyFormatedAuthKey; string region = Regions.WestCentralUS; ConnectionMode connectionMode = ConnectionMode.Gateway; TimeSpan requestTimeout = TimeSpan.FromDays(1); int maxConnections = 9001; string userAgentSuffix = "testSuffix"; RequestHandler preProcessHandler = new TestHandler(); ApiType apiType = ApiType.Sql; int maxRetryAttemptsOnThrottledRequests = 9999; TimeSpan maxRetryWaitTime = TimeSpan.FromHours(6); bool enableTcpConnectionEndpointRediscovery = true; CosmosSerializationOptions cosmosSerializerOptions = new CosmosSerializationOptions() { IgnoreNullValues = true, PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase, }; TimeSpan idleTcpConnectionTimeout = new TimeSpan(0, 10, 0); TimeSpan openTcpConnectionTimeout = new TimeSpan(0, 0, 5); int maxRequestsPerTcpConnection = 30; int maxTcpConnectionsPerEndpoint = 65535; Cosmos.PortReuseMode portReuseMode = Cosmos.PortReuseMode.PrivatePortPool; IWebProxy webProxy = new TestWebProxy(); Cosmos.ConsistencyLevel consistencyLevel = Cosmos.ConsistencyLevel.ConsistentPrefix; CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder( accountEndpoint: endpoint, authKeyOrResourceToken: key); CosmosClient cosmosClient = cosmosClientBuilder.Build(new MockDocumentClient()); CosmosClientOptions clientOptions = cosmosClient.ClientOptions; Assert.AreEqual(endpoint, cosmosClient.Endpoint.OriginalString, "AccountEndpoint did not save correctly"); Assert.AreEqual(key, cosmosClient.AccountKey, "AccountKey did not save correctly"); //Verify the default values are different from the new values Assert.AreNotEqual(region, clientOptions.ApplicationRegion); Assert.IsNull(clientOptions.ApplicationPreferredRegions); Assert.AreNotEqual(connectionMode, clientOptions.ConnectionMode); Assert.AreNotEqual(maxConnections, clientOptions.GatewayModeMaxConnectionLimit); Assert.AreNotEqual(requestTimeout, clientOptions.RequestTimeout); Assert.AreNotEqual(userAgentSuffix, clientOptions.ApplicationName); Assert.AreNotEqual(apiType, clientOptions.ApiType); Assert.IsFalse(clientOptions.AllowBulkExecution); Assert.AreEqual(0, clientOptions.CustomHandlers.Count); Assert.IsNull(clientOptions.SerializerOptions); Assert.IsNotNull(clientOptions.Serializer); Assert.IsNull(clientOptions.WebProxy); Assert.IsFalse(clientOptions.LimitToEndpoint); Assert.IsTrue(clientOptions.EnableTcpConnectionEndpointRediscovery); Assert.IsNull(clientOptions.HttpClientFactory); Assert.AreNotEqual(consistencyLevel, clientOptions.ConsistencyLevel); Assert.IsFalse(clientOptions.EnablePartitionLevelFailover); //Verify GetConnectionPolicy returns the correct values for default ConnectionPolicy policy = clientOptions.GetConnectionPolicy(clientId: 0); Assert.AreEqual(ConnectionMode.Direct, policy.ConnectionMode); Assert.AreEqual(Protocol.Tcp, policy.ConnectionProtocol); Assert.AreEqual(clientOptions.GatewayModeMaxConnectionLimit, policy.MaxConnectionLimit); Assert.AreEqual(clientOptions.RequestTimeout, policy.RequestTimeout); Assert.IsNull(policy.IdleTcpConnectionTimeout); Assert.IsNull(policy.OpenTcpConnectionTimeout); Assert.IsNull(policy.MaxRequestsPerTcpConnection); Assert.IsNull(policy.MaxTcpConnectionsPerEndpoint); Assert.IsTrue(policy.EnableEndpointDiscovery); Assert.IsTrue(policy.EnableTcpConnectionEndpointRediscovery); Assert.IsNull(policy.HttpClientFactory); Assert.AreNotEqual(Cosmos.ConsistencyLevel.Session, clientOptions.ConsistencyLevel); Assert.IsFalse(policy.EnablePartitionLevelFailover); cosmosClientBuilder.WithApplicationRegion(region) .WithConnectionModeGateway(maxConnections, webProxy) .WithRequestTimeout(requestTimeout) .WithApplicationName(userAgentSuffix) .AddCustomHandlers(preProcessHandler) .WithApiType(apiType) .WithThrottlingRetryOptions(maxRetryWaitTime, maxRetryAttemptsOnThrottledRequests) .WithBulkExecution(true) .WithSerializerOptions(cosmosSerializerOptions) .WithConsistencyLevel(consistencyLevel) .WithPartitionLevelFailoverEnabled(); cosmosClient = cosmosClientBuilder.Build(new MockDocumentClient()); clientOptions = cosmosClient.ClientOptions; //Verify all the values are updated Assert.AreEqual(region, clientOptions.ApplicationRegion); Assert.IsNull(clientOptions.ApplicationPreferredRegions); Assert.AreEqual(connectionMode, clientOptions.ConnectionMode); Assert.AreEqual(maxConnections, clientOptions.GatewayModeMaxConnectionLimit); Assert.AreEqual(requestTimeout, clientOptions.RequestTimeout); Assert.AreEqual(userAgentSuffix, clientOptions.ApplicationName); Assert.AreEqual(preProcessHandler, clientOptions.CustomHandlers[0]); Assert.AreEqual(apiType, clientOptions.ApiType); Assert.AreEqual(maxRetryAttemptsOnThrottledRequests, clientOptions.MaxRetryAttemptsOnRateLimitedRequests); Assert.AreEqual(maxRetryWaitTime, clientOptions.MaxRetryWaitTimeOnRateLimitedRequests); Assert.AreEqual(cosmosSerializerOptions.IgnoreNullValues, clientOptions.SerializerOptions.IgnoreNullValues); Assert.AreEqual(cosmosSerializerOptions.PropertyNamingPolicy, clientOptions.SerializerOptions.PropertyNamingPolicy); Assert.AreEqual(cosmosSerializerOptions.Indented, clientOptions.SerializerOptions.Indented); Assert.IsTrue(object.ReferenceEquals(webProxy, clientOptions.WebProxy)); Assert.IsTrue(clientOptions.AllowBulkExecution); Assert.AreEqual(consistencyLevel, clientOptions.ConsistencyLevel); Assert.IsTrue(clientOptions.EnablePartitionLevelFailover); //Verify GetConnectionPolicy returns the correct values policy = clientOptions.GetConnectionPolicy(clientId: 0); Assert.AreEqual(region, policy.PreferredLocations[0]); Assert.AreEqual(ConnectionMode.Gateway, policy.ConnectionMode); Assert.AreEqual(Protocol.Https, policy.ConnectionProtocol); Assert.AreEqual(maxConnections, policy.MaxConnectionLimit); Assert.AreEqual(requestTimeout, policy.RequestTimeout); Assert.IsTrue(policy.UserAgentSuffix.Contains(userAgentSuffix)); Assert.IsTrue(policy.UseMultipleWriteLocations); Assert.AreEqual(maxRetryAttemptsOnThrottledRequests, policy.RetryOptions.MaxRetryAttemptsOnThrottledRequests); Assert.AreEqual((int)maxRetryWaitTime.TotalSeconds, policy.RetryOptions.MaxRetryWaitTimeInSeconds); Assert.AreEqual((Documents.ConsistencyLevel)consistencyLevel, clientOptions.GetDocumentsConsistencyLevel()); Assert.IsTrue(policy.EnablePartitionLevelFailover); IReadOnlyList <string> preferredLocations = new List <string>() { Regions.AustraliaCentral, Regions.AustraliaCentral2 }; //Verify Direct Mode settings cosmosClientBuilder = new CosmosClientBuilder( accountEndpoint: endpoint, authKeyOrResourceToken: key); cosmosClientBuilder.WithConnectionModeDirect( idleTcpConnectionTimeout, openTcpConnectionTimeout, maxRequestsPerTcpConnection, maxTcpConnectionsPerEndpoint, portReuseMode, enableTcpConnectionEndpointRediscovery) .WithApplicationPreferredRegions(preferredLocations); cosmosClient = cosmosClientBuilder.Build(new MockDocumentClient()); clientOptions = cosmosClient.ClientOptions; //Verify all the values are updated Assert.AreEqual(idleTcpConnectionTimeout, clientOptions.IdleTcpConnectionTimeout); Assert.AreEqual(openTcpConnectionTimeout, clientOptions.OpenTcpConnectionTimeout); Assert.AreEqual(maxRequestsPerTcpConnection, clientOptions.MaxRequestsPerTcpConnection); Assert.AreEqual(maxTcpConnectionsPerEndpoint, clientOptions.MaxTcpConnectionsPerEndpoint); Assert.AreEqual(portReuseMode, clientOptions.PortReuseMode); Assert.IsTrue(clientOptions.EnableTcpConnectionEndpointRediscovery); CollectionAssert.AreEqual(preferredLocations.ToArray(), clientOptions.ApplicationPreferredRegions.ToArray()); //Verify GetConnectionPolicy returns the correct values policy = clientOptions.GetConnectionPolicy(clientId: 0); Assert.AreEqual(idleTcpConnectionTimeout, policy.IdleTcpConnectionTimeout); Assert.AreEqual(openTcpConnectionTimeout, policy.OpenTcpConnectionTimeout); Assert.AreEqual(maxRequestsPerTcpConnection, policy.MaxRequestsPerTcpConnection); Assert.AreEqual(maxTcpConnectionsPerEndpoint, policy.MaxTcpConnectionsPerEndpoint); Assert.AreEqual(portReuseMode, policy.PortReuseMode); Assert.IsTrue(policy.EnableTcpConnectionEndpointRediscovery); CollectionAssert.AreEqual(preferredLocations.ToArray(), policy.PreferredLocations.ToArray()); }
public void VerifyCosmosConfigurationPropertiesGetUpdated() { string endpoint = AccountEndpoint; string key = Guid.NewGuid().ToString(); string region = CosmosRegions.WestCentralUS; ConnectionMode connectionMode = ConnectionMode.Gateway; TimeSpan requestTimeout = TimeSpan.FromDays(1); int maxConnections = 9001; string userAgentSuffix = "testSuffix"; CosmosRequestHandler preProcessHandler = new TestHandler(); ApiType apiType = ApiType.Sql; int maxRetryAttemptsOnThrottledRequests = 9999; TimeSpan maxRetryWaitTime = TimeSpan.FromHours(6); CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder( accountEndPoint: endpoint, accountKey: key); CosmosClient cosmosClient = cosmosClientBuilder.Build(new MockDocumentClient()); CosmosClientConfiguration configuration = cosmosClient.Configuration; Assert.AreEqual(endpoint, configuration.AccountEndPoint.OriginalString, "AccountEndPoint did not save correctly"); Assert.AreEqual(key, configuration.AccountKey, "AccountKey did not save correctly"); //Verify the default values are different from the new values Assert.AreNotEqual(region, configuration.CurrentRegion); Assert.AreNotEqual(connectionMode, configuration.ConnectionMode); Assert.AreNotEqual(maxConnections, configuration.MaxConnectionLimit); Assert.AreNotEqual(requestTimeout, configuration.RequestTimeout); Assert.AreNotEqual(userAgentSuffix, configuration.UserAgentSuffix); Assert.AreNotEqual(apiType, configuration.ApiType); Assert.IsNull(configuration.CustomHandlers); //Verify GetConnectionPolicy returns the correct values for default ConnectionPolicy policy = configuration.GetConnectionPolicy(); Assert.AreEqual(ConnectionMode.Direct, policy.ConnectionMode); Assert.AreEqual(Protocol.Tcp, policy.ConnectionProtocol); Assert.AreEqual(configuration.MaxConnectionLimit, policy.MaxConnectionLimit); Assert.AreEqual(configuration.RequestTimeout, policy.RequestTimeout); cosmosClientBuilder.UseCurrentRegion(region) .UseConnectionModeGateway(maxConnections) .UseRequestTimeout(requestTimeout) .UseUserAgentSuffix(userAgentSuffix) .AddCustomHandlers(preProcessHandler) .UseApiType(apiType) .UseThrottlingRetryOptions(maxRetryWaitTime, maxRetryAttemptsOnThrottledRequests); cosmosClient = cosmosClientBuilder.Build(new MockDocumentClient()); configuration = cosmosClient.Configuration; //Verify all the values are updated Assert.AreEqual(region, configuration.CurrentRegion); Assert.AreEqual(connectionMode, configuration.ConnectionMode); Assert.AreEqual(maxConnections, configuration.MaxConnectionLimit); Assert.AreEqual(requestTimeout, configuration.RequestTimeout); Assert.AreEqual(userAgentSuffix, configuration.UserAgentSuffix); Assert.AreEqual(preProcessHandler, configuration.CustomHandlers[0]); Assert.AreEqual(apiType, configuration.ApiType); Assert.AreEqual(maxRetryAttemptsOnThrottledRequests, configuration.MaxRetryAttemptsOnThrottledRequests); Assert.AreEqual(maxRetryWaitTime, configuration.MaxRetryWaitTimeOnThrottledRequests); //Verify GetConnectionPolicy returns the correct values policy = configuration.GetConnectionPolicy(); Assert.AreEqual(region, policy.PreferredLocations[0]); Assert.AreEqual(ConnectionMode.Gateway, policy.ConnectionMode); Assert.AreEqual(Protocol.Https, policy.ConnectionProtocol); Assert.AreEqual(maxConnections, policy.MaxConnectionLimit); Assert.AreEqual(requestTimeout, policy.RequestTimeout); Assert.AreEqual(userAgentSuffix, policy.UserAgentSuffix); Assert.IsTrue(policy.UseMultipleWriteLocations); Assert.AreEqual(maxRetryAttemptsOnThrottledRequests, policy.RetryOptions.MaxRetryAttemptsOnThrottledRequests); Assert.AreEqual((int)maxRetryWaitTime.TotalSeconds, policy.RetryOptions.MaxRetryWaitTimeInSeconds); }
// Async main requires c# 7.1 which is set in the csproj with the LangVersion attribute // <Main> public static async Task Main(string[] args) { IConfigurationRoot configuration = new ConfigurationBuilder() .AddJsonFile("appSettings.json") .Build(); 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"); } // Connecting to Emulator. Change if you want a live account CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(endpoint, authKey); cosmosClientBuilder.AddCustomHandlers( new LoggingHandler(), new ConcurrencyHandler(), new ThrottlingHandler() ); CosmosClient client = cosmosClientBuilder.Build(); DatabaseResponse databaseResponse = await client.CreateDatabaseIfNotExistsAsync("mydb"); Database database = databaseResponse.Database; ContainerResponse containerResponse = await database.CreateContainerIfNotExistsAsync("mycoll", "/id"); Container container = containerResponse.Container; Item item = new Item() { Id = Guid.NewGuid().ToString(), Name = "Test Item", Description = "Some random test item", Completed = false }; // Create await container.CreateItemAsync <Item>(item, new PartitionKey(item.Id)); item.Completed = true; // Replace await container.ReplaceItemAsync <Item>(item, item.Id, new PartitionKey(item.Id)); // Querying FeedIterator <Item> query = container.GetItemQueryIterator <Item>(new QueryDefinition("SELECT * FROM c"), requestOptions: new QueryRequestOptions() { MaxConcurrency = 1 }); List <Item> results = new List <Item>(); while (query.HasMoreResults) { FeedResponse <Item> response = await query.ReadNextAsync(); results.AddRange(response.ToList()); } // Read Item ItemResponse <Item> cosmosItemResponse = await container.ReadItemAsync <Item>(item.Id, new PartitionKey(item.Id)); ItemRequestOptions itemRequestOptions = new ItemRequestOptions() { IfMatchEtag = cosmosItemResponse.ETag }; // Concurrency List <Task <ItemResponse <Item> > > tasks = new List <Task <ItemResponse <Item> > > { UpdateItemForConcurrency(container, itemRequestOptions, item), UpdateItemForConcurrency(container, itemRequestOptions, item) }; try { await Task.WhenAll(tasks); } catch (CosmosException ex) { // Verify that our custom handler caught the scenario Debug.Assert(999.Equals(ex.SubStatusCode)); } // Delete await container.DeleteItemAsync <Item>(item.Id, new PartitionKey(item.Id)); }
// Async main requires c# 7.1 which is set in the csproj with the LangVersion attribute // <Main> public static async Task Main(string[] args) { IConfigurationRoot configuration = new ConfigurationBuilder() .AddJsonFile("appSettings.json") .Build(); 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"); } // Connecting to Emulator. Change if you want a live account CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(endpoint, authKey); // Declare a JSON schema to use with the schema validation handler var myContainerSchema = JSchema.Parse(@"{ 'type': 'object', 'properties': { 'name': {'type': 'string'} }, 'required': ['name'] }"); cosmosClientBuilder.AddCustomHandlers( new LoggingHandler(), new ConcurrencyHandler(), new ThrottlingHandler(), new SchemaValidationHandler((database: "mydb", container: "mycoll2", schema: myContainerSchema)) ); CosmosClient client = cosmosClientBuilder.Build(); DatabaseResponse databaseResponse = await client.CreateDatabaseIfNotExistsAsync("mydb"); Database database = databaseResponse.Database; ContainerResponse containerResponse = await database.CreateContainerIfNotExistsAsync("mycoll", "/id"); Container container = containerResponse.Container; Item item = new Item() { Id = Guid.NewGuid().ToString(), Name = "Test Item", Description = "Some random test item", Completed = false }; // Create await container.CreateItemAsync <Item>(item, new PartitionKey(item.Id)); item.Completed = true; // Replace await container.ReplaceItemAsync <Item>(item, item.Id, new PartitionKey(item.Id)); // Querying List <Item> results = new List <Item>(); using (FeedIterator <Item> query = container.GetItemQueryIterator <Item>(new QueryDefinition("SELECT * FROM c"), requestOptions: new QueryRequestOptions() { MaxConcurrency = 1 })) { while (query.HasMoreResults) { FeedResponse <Item> response = await query.ReadNextAsync(); results.AddRange(response.ToList()); } } // Read Item ItemResponse <Item> cosmosItemResponse = await container.ReadItemAsync <Item>(item.Id, new PartitionKey(item.Id)); ItemRequestOptions itemRequestOptions = new ItemRequestOptions() { IfMatchEtag = cosmosItemResponse.ETag }; // Concurrency List <Task <ItemResponse <Item> > > tasks = new List <Task <ItemResponse <Item> > > { UpdateItemForConcurrency(container, itemRequestOptions, item), UpdateItemForConcurrency(container, itemRequestOptions, item) }; try { await Task.WhenAll(tasks); } catch (CosmosException ex) { // Verify that our custom handler caught the scenario Debug.Assert(999.Equals(ex.SubStatusCode)); } // Delete await container.DeleteItemAsync <Item>(item.Id, new PartitionKey(item.Id)); // Schema validation containerResponse = await database.CreateContainerIfNotExistsAsync("mycoll2", "/id"); container = containerResponse.Container; // Insert an item with invalid schema var writeSucceeded = true; try { await container.CreateItemAsync(new { id = "12345" }); } catch (InvalidItemSchemaException) { writeSucceeded = false; } Debug.Assert(!writeSucceeded); // Insert an item with valid schema try { await container.CreateItemAsync(new { id = "12345", name = "Youri" }); writeSucceeded = true; } catch (InvalidItemSchemaException) { writeSucceeded = false; } Debug.Assert(writeSucceeded); // Update an item with invalid schema try { await container.ReplaceItemAsync(new { id = "12345" }, "12345"); writeSucceeded = true; } catch (InvalidItemSchemaException) { writeSucceeded = false; } Debug.Assert(!writeSucceeded); // Update an item with valid schema try { await container.ReplaceItemAsync(new { id = "12345", name = "Vladimir" }, "12345"); writeSucceeded = true; } catch (InvalidItemSchemaException) { writeSucceeded = false; } Debug.Assert(writeSucceeded); }
public void VerifyCosmosConfigurationPropertiesGetUpdated() { string endpoint = AccountEndpoint; string key = Guid.NewGuid().ToString(); string region = Regions.WestCentralUS; ConnectionMode connectionMode = ConnectionMode.Gateway; TimeSpan requestTimeout = TimeSpan.FromDays(1); int maxConnections = 9001; string userAgentSuffix = "testSuffix"; RequestHandler preProcessHandler = new TestHandler(); ApiType apiType = ApiType.Sql; int maxRetryAttemptsOnThrottledRequests = 9999; TimeSpan maxRetryWaitTime = TimeSpan.FromHours(6); CosmosSerializationOptions cosmosSerializerOptions = new CosmosSerializationOptions() { IgnoreNullValues = true, PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase, }; TimeSpan idleTcpConnectionTimeout = new TimeSpan(0, 10, 0); TimeSpan openTcpConnectionTimeout = new TimeSpan(0, 0, 5); int maxRequestsPerTcpConnection = 30; int maxTcpConnectionsPerEndpoint = 65535; CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder( accountEndpoint: endpoint, accountKey: key); CosmosClient cosmosClient = cosmosClientBuilder.Build(new MockDocumentClient()); CosmosClientOptions clientOptions = cosmosClient.ClientOptions; Assert.AreEqual(endpoint, cosmosClient.Endpoint.OriginalString, "AccountEndpoint did not save correctly"); Assert.AreEqual(key, cosmosClient.AccountKey, "AccountKey did not save correctly"); //Verify the default values are different from the new values Assert.AreNotEqual(region, clientOptions.ApplicationRegion); Assert.AreNotEqual(connectionMode, clientOptions.ConnectionMode); Assert.AreNotEqual(maxConnections, clientOptions.GatewayModeMaxConnectionLimit); Assert.AreNotEqual(requestTimeout, clientOptions.RequestTimeout); Assert.AreNotEqual(userAgentSuffix, clientOptions.ApplicationName); Assert.AreNotEqual(apiType, clientOptions.ApiType); Assert.AreEqual(0, clientOptions.CustomHandlers.Count); Assert.IsNull(clientOptions.SerializerOptions); Assert.IsNull(clientOptions.Serializer); //Verify GetConnectionPolicy returns the correct values for default ConnectionPolicy policy = clientOptions.GetConnectionPolicy(); Assert.AreEqual(ConnectionMode.Direct, policy.ConnectionMode); Assert.AreEqual(Protocol.Tcp, policy.ConnectionProtocol); Assert.AreEqual(clientOptions.GatewayModeMaxConnectionLimit, policy.MaxConnectionLimit); Assert.AreEqual(clientOptions.RequestTimeout, policy.RequestTimeout); Assert.IsNull(policy.IdleTcpConnectionTimeout); Assert.IsNull(policy.OpenTcpConnectionTimeout); Assert.IsNull(policy.MaxRequestsPerTcpConnection); Assert.IsNull(policy.MaxTcpConnectionsPerEndpoint); cosmosClientBuilder.WithApplicationRegion(region) .WithConnectionModeGateway(maxConnections) .WithRequestTimeout(requestTimeout) .WithApplicationName(userAgentSuffix) .AddCustomHandlers(preProcessHandler) .WithApiType(apiType) .WithThrottlingRetryOptions(maxRetryWaitTime, maxRetryAttemptsOnThrottledRequests) .WithSerializerOptions(cosmosSerializerOptions); cosmosClient = cosmosClientBuilder.Build(new MockDocumentClient()); clientOptions = cosmosClient.ClientOptions; //Verify all the values are updated Assert.AreEqual(region, clientOptions.ApplicationRegion); Assert.AreEqual(connectionMode, clientOptions.ConnectionMode); Assert.AreEqual(maxConnections, clientOptions.GatewayModeMaxConnectionLimit); Assert.AreEqual(requestTimeout, clientOptions.RequestTimeout); Assert.AreEqual(userAgentSuffix, clientOptions.ApplicationName); Assert.AreEqual(preProcessHandler, clientOptions.CustomHandlers[0]); Assert.AreEqual(apiType, clientOptions.ApiType); Assert.AreEqual(maxRetryAttemptsOnThrottledRequests, clientOptions.MaxRetryAttemptsOnRateLimitedRequests); Assert.AreEqual(maxRetryWaitTime, clientOptions.MaxRetryWaitTimeOnRateLimitedRequests); Assert.AreEqual(cosmosSerializerOptions.IgnoreNullValues, clientOptions.SerializerOptions.IgnoreNullValues); Assert.AreEqual(cosmosSerializerOptions.PropertyNamingPolicy, clientOptions.SerializerOptions.PropertyNamingPolicy); Assert.AreEqual(cosmosSerializerOptions.Indented, clientOptions.SerializerOptions.Indented); //Verify GetConnectionPolicy returns the correct values policy = clientOptions.GetConnectionPolicy(); Assert.AreEqual(region, policy.PreferredLocations[0]); Assert.AreEqual(ConnectionMode.Gateway, policy.ConnectionMode); Assert.AreEqual(Protocol.Https, policy.ConnectionProtocol); Assert.AreEqual(maxConnections, policy.MaxConnectionLimit); Assert.AreEqual(requestTimeout, policy.RequestTimeout); Assert.IsTrue(policy.UserAgentSuffix.Contains(userAgentSuffix)); Assert.IsTrue(policy.UseMultipleWriteLocations); Assert.AreEqual(maxRetryAttemptsOnThrottledRequests, policy.RetryOptions.MaxRetryAttemptsOnThrottledRequests); Assert.AreEqual((int)maxRetryWaitTime.TotalSeconds, policy.RetryOptions.MaxRetryWaitTimeInSeconds); //Verify Direct Mode settings cosmosClientBuilder = new CosmosClientBuilder( accountEndpoint: endpoint, accountKey: key); cosmosClientBuilder.WithConnectionModeDirect( idleTcpConnectionTimeout, openTcpConnectionTimeout, maxRequestsPerTcpConnection, maxTcpConnectionsPerEndpoint ); cosmosClient = cosmosClientBuilder.Build(new MockDocumentClient()); clientOptions = cosmosClient.ClientOptions; //Verify all the values are updated Assert.AreEqual(idleTcpConnectionTimeout, clientOptions.IdleTcpConnectionTimeout); Assert.AreEqual(openTcpConnectionTimeout, clientOptions.OpenTcpConnectionTimeout); Assert.AreEqual(maxRequestsPerTcpConnection, clientOptions.MaxRequestsPerTcpConnection); Assert.AreEqual(maxTcpConnectionsPerEndpoint, clientOptions.MaxTcpConnectionsPerEndpoint); //Verify GetConnectionPolicy returns the correct values policy = clientOptions.GetConnectionPolicy(); Assert.AreEqual(idleTcpConnectionTimeout, policy.IdleTcpConnectionTimeout); Assert.AreEqual(openTcpConnectionTimeout, policy.OpenTcpConnectionTimeout); Assert.AreEqual(maxRequestsPerTcpConnection, policy.MaxRequestsPerTcpConnection); Assert.AreEqual(maxTcpConnectionsPerEndpoint, policy.MaxTcpConnectionsPerEndpoint); }
public void WithUnrecognizedApplicationRegionThrows() { string notAValidAzureRegion = Guid.NewGuid().ToString(); { CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder( accountEndpoint: AccountEndpoint, authKeyOrResourceToken: MockCosmosUtil.RandomInvalidCorrectlyFormatedAuthKey) .WithApplicationRegion(notAValidAzureRegion); ArgumentException argumentException = Assert.ThrowsException <ArgumentException>(() => cosmosClientBuilder.Build(new MockDocumentClient())); Assert.IsTrue(argumentException.Message.Contains(notAValidAzureRegion), $"Expected error message to contain {notAValidAzureRegion} but got: {argumentException.Message}"); } { CosmosClientOptions cosmosClientOptions = new CosmosClientOptions() { ApplicationRegion = notAValidAzureRegion }; ArgumentException argumentException = Assert.ThrowsException <ArgumentException>(() => new CosmosClient(AccountEndpoint, MockCosmosUtil.RandomInvalidCorrectlyFormatedAuthKey, cosmosClientOptions)); Assert.IsTrue(argumentException.Message.Contains(notAValidAzureRegion), $"Expected error message to contain {notAValidAzureRegion} but got: {argumentException.Message}"); } }
/// <summary> /// DI Configure using Autofac container /// </summary> /// <param name="builder"></param> private void ConfigureAutofacContainer(ContainerBuilder builder) { builder.Register(activator => { var xeroConfig = new XeroConfiguration(); var config = activator.Resolve <IConfiguration>(); config.GetSection(nameof(XeroConfiguration)).Bind(xeroConfig); return(xeroConfig); }) .AsSelf() .SingleInstance(); // register azure storage account builder.Register(activator => { var storageAccount = activator.Resolve <StorageAccountProvider>().GetHost(); return(storageAccount); }) .AsSelf() .SingleInstance(); // register Cosmos DB builder.Register(activator => { var config = activator.Resolve <IConfiguration>(); var connectionString = config["CosmosDB:ConnectionString"]; var serializerOptions = new CosmosSerializationOptions() { IgnoreNullValues = true, Indented = false, PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase }; var cosmosClientBuilder = new CosmosClientBuilder(connectionString) .WithSerializerOptions(serializerOptions); return(cosmosClientBuilder.Build()); }) .AsSelf() .SingleInstance(); // Register all functions that resides in a given namespace // The function class itself will be created using autofac builder .RegisterAssemblyTypes(typeof(Startup).Assembly) .InNamespace(typeof(IAzFunc).Namespace ?? string.Empty) .AsSelf() // Azure Functions core code resolves a function class by itself. .InstancePerTriggerRequest(); // This will scope nested dependencies to each function execution builder .RegisterAssemblyTypes(typeof(Startup).Assembly) .InNamespace(typeof(IStorageEnitity).Namespace ?? string.Empty) .AsImplementedInterfaces() .SingleInstance(); // This will scope nested dependencies to each function execution builder .RegisterAssemblyTypes(typeof(AccountingApi).Assembly) .InNamespace(typeof(AccountingApi).Namespace ?? string.Empty) .AsSelf() .SingleInstance(); builder.RegisterType <TokenTable>() .As <ITokenStore>() .SingleInstance(); }