/// <summary> /// This method creates a Polly retry policy when there is cosmos exception with code Unauthorized. /// </summary> /// <returns>The AsyncRetryPolicy</returns> private AsyncRetryPolicy GetCosmosRetryPolicy() { return(Policy.Handle <CosmosException>(e => e.StatusCode == HttpStatusCode.Unauthorized) .RetryAsync(Constants.RetryCount, async(exception, retryCount) => { try { await SemaphoreSlim.WaitAsync().ConfigureAwait(false); logger.LogInformation("Read the cosmos key from KeyVault."); // Get the latest cosmos key. Microsoft.Azure.KeyVault.Models.SecretBundle cosmosKeySecret = await keyVaultConnection.Client.GetSecretAsync(keyVaultConnection.Address, Constants.CosmosKey).ConfigureAwait(false); CosmosConfig config = new CosmosConfig(); CosmosClientOptions options = new CosmosClientOptions { RequestTimeout = TimeSpan.FromSeconds(config.Timeout), MaxRetryAttemptsOnRateLimitedRequests = config.Retries, MaxRetryWaitTimeOnRateLimitedRequests = TimeSpan.FromSeconds(config.Timeout), }; services.AddSingleton <CosmosClient>(new CosmosClient(configuration[Constants.CosmosUrl], cosmosKeySecret.Value)); logger.LogInformation("Refresh cosmos connection with upadated secret."); await dal.Reconnect(new Uri(configuration[Constants.CosmosUrl]), cosmosKeySecret.Value, configuration[Constants.CosmosDatabase], configuration[Constants.CosmosCollection], services.BuildServiceProvider().GetService <CosmosClient>()).ConfigureAwait(false); } finally { // release the semaphore SemaphoreSlim.Release(); } })); }
public static CmsBuilder ConfigureCosmosDB(this CmsBuilder builder, Func <StorageConfiguration> storageConfigFunc) { var Configuration = builder.Configuration; var services = builder.Services; services.Configure <CosmosConfig>(Configuration.GetSection(nameof(CosmosConfig))); StorageConfiguration storageConfig = storageConfigFunc(); services.AddTransient <CosmosService>(); if (storageConfig.ReadCmsItems) { services.AddTransient <IReadCmsItem, CosmosWrapperService>(); } if (storageConfig.WriteCmsItems) { services.AddTransient <IWriteCmsItem, CosmosWrapperService>(); } var cosmosConfig = new CosmosConfig(); Configuration.GetSection(nameof(CosmosConfig)).Bind(cosmosConfig); var cosmosConfigOptions = Options.Create <CosmosConfig>(cosmosConfig); var cosmosService = new CosmosService(cosmosConfigOptions, Options.Create(new CmsConfiguration())); cosmosService.InitializeContainer(); return(builder); }
EquinoxContext ConfigureStore() { // This is the allocation limit passed internally to a System.Caching.MemoryCache instance // The primary objects held in the cache are the Folded State of Event-sourced aggregates // see https://docs.microsoft.com/en-us/dotnet/framework/performance/caching-in-net-framework-applications for more information var cacheMb = 50; // AZURE COSMOSDB: Events are stored in an Azure CosmosDb Account (using the SQL API) // Provisioning Steps: // 1) Set the 3x environment variables EQUINOX_COSMOS_CONNECTION, EQUINOX_COSMOS_DATABASE, EQUINOX_COSMOS_CONTAINER // 2) Provision a container using the following command sequence: // dotnet tool install -g Equinox.Cli // Equinox.Cli init -ru 1000 cosmos -s $env:EQUINOX_COSMOS_CONNECTION -d $env:EQUINOX_COSMOS_DATABASE -c $env:EQUINOX_COSMOS_CONTAINER const string connVar = "EQUINOX_COSMOS_CONNECTION"; var conn = Configuration.GetValue <string>(connVar); const string dbVar = "EQUINOX_COSMOS_DATABASE"; var db = Configuration.GetValue <string>(dbVar); const string containerVar = "EQUINOX_COSMOS_CONTAINER"; var container = Configuration.GetValue <string>(containerVar); if (conn == null || db == null || container == null) { throw new Exception( $"Event Storage subsystem requires the following Environment Variables to be specified: {connVar} {dbVar}, {containerVar}"); } var connMode = Equinox.Cosmos.ConnectionMode.Direct; var config = new CosmosConfig(connMode, conn, db, container, cacheMb); return(new CosmosContext(config)); }
private CosmosContext ConfigureStore(IConfigurationSection configuration) { const string connVar = "CosmosConnection"; var conn = configuration[connVar]; const string dbVar = "CosmosDb"; var db = configuration[dbVar]; const string collVar = "CosmosCollection"; var coll = configuration[collVar]; if (conn == null || db == null || coll == null) { throw new Exception( $"Event Storage subsystem requires the following Environment Variables to be specified: {connVar} {dbVar}, {collVar}"); } const string timeoutVar = "CosmosTimeout"; var timeout = configuration.GetValue <int>(timeoutVar); const string groupNameVar = "ConsumerGroupName"; string groupName = configuration[groupNameVar]; const string leaseSuffixVar = "LeaseContainerSuffix"; string leaseSuffix = configuration[leaseSuffixVar]; var connMode = Equinox.Cosmos.ConnectionMode.Direct; var cosmosConfig = new CosmosConfig(connMode, conn, db, coll, timeout); var config = new CosmosChangeFeedConfig(groupName, leaseSuffix, cosmosConfig); return(new CosmosContext(config)); }
private void ConfigureApplication() { IConfiguration Configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build(); cosmosConfig = new CosmosConfig(); Configuration.Bind("connectionSettings", cosmosConfig); }
private static CosmosDbService InitializeCosmosClientInstance(CosmosConfig cosmosConfig) { Microsoft.Azure.Cosmos.Fluent.CosmosClientBuilder clientBuilder = new Microsoft.Azure.Cosmos.Fluent.CosmosClientBuilder(cosmosConfig.ConnectionString); Microsoft.Azure.Cosmos.CosmosClient client = clientBuilder .WithConnectionModeDirect() .Build(); CosmosDbService cosmosDbService = new CosmosDbService(client, cosmosConfig.DatabaseName, cosmosConfig.ContainerName); return(cosmosDbService); }
private static void InitCosmosConfig() { AntiForgeryConfig.UniqueClaimTypeIdentifier = "name"; MvcApplication.CosmosConfig = new CosmosConfig() { DatabaseId = ConfigurationManager.AppSettings["Cosmos.DatabaseId"], EndPointUrl = ConfigurationManager.AppSettings["Cosmos.EndPointUrl"], AuthorizationKey = ConfigurationManager.AppSettings["Cosmos.AuthorizationKey"], ExpenseCollectionId = ConfigurationManager.AppSettings["Cosmos.ExpenseCollectionId"] }; }
/// <summary> /// Initializes a new instance of the <see cref="CosmosDbRepository"/> class. /// </summary> /// <param name="configuration">The configuration.</param> public CosmosDbRepository(IOptions <CosmosConfig> configuration) { _configuration = configuration.Value; var clientOptions = new CosmosClientOptions { MaxRetryAttemptsOnRateLimitedRequests = 3, MaxRetryWaitTimeOnRateLimitedRequests = new TimeSpan(0, 0, 30), ConnectionMode = ConnectionMode.Gateway }; _cosmosClient = new CosmosClient(_configuration.EndpointUri, _configuration.AccountKey, clientOptions); }
private static CosmosDbService InitializeCosmosClientInstance(CosmosConfig cosmosConfig) { Microsoft.Azure.Cosmos.Fluent.CosmosClientBuilder clientBuilder = new Microsoft.Azure.Cosmos.Fluent.CosmosClientBuilder(cosmosConfig.ConnectionString); Microsoft.Azure.Cosmos.CosmosClient client = clientBuilder .WithConnectionModeDirect() .Build(); CosmosDbService cosmosDbService = new CosmosDbService(client, cosmosConfig.DatabaseName, cosmosConfig.ContainerName); //Microsoft.Azure.Cosmos.DatabaseResponse database = await client.CreateDatabaseIfNotExistsAsync(databaseName); //await database.Database.CreateContainerIfNotExistsAsync(containerName, "/id"); return(cosmosDbService); }
static EquinoxContext ConfigureStore() { #if (cosmos || eventStore) // This is the allocation limit passed internally to a System.Caching.MemoryCache instance // The primary objects held in the cache are the Folded State of Event-sourced aggregates // see https://docs.microsoft.com/en-us/dotnet/framework/performance/caching-in-net-framework-applications for more information var cacheMb = 50; #endif #if eventStore // EVENTSTORE: see https://eventstore.org/ // Requires a Commercial HA Cluster, which can be simulated by 1) installing the OSS Edition from Choocolatey 2) running it in cluster mode // # requires admin privilege // cinst eventstore-oss -y # where cinst is an invocation of the Chocolatey Package Installer on Windows // # run as a single-node cluster to allow connection logic to use cluster mode as for a commercial cluster // & $env:ProgramData\chocolatey\bin\EventStore.ClusterNode.exe --gossip-on-single-node --discover-via-dns 0 --ext-http-port=30778 var esConfig = new EventStoreConfig("localhost", "admin", "changeit", cacheMb); return(new EventStoreContext(esConfig)); #endif #if cosmos // AZURE COSMOSDB: Events are stored in an Azure CosmosDb Account (using the SQL API) // Provisioning Steps: // 1) Set the 3x environment variables EQUINOX_COSMOS_CONNECTION, EQUINOX_COSMOS_DATABASE, EQUINOX_COSMOS_COLLECTION // 2) Provision a collection using the following command sequence: // dotnet tool install -g Equinox.Cli // Equinox.Cli init -ru 1000 cosmos -s $env:EQUINOX_COSMOS_CONNECTION -d $env:EQUINOX_COSMOS_DATABASE -c $env:EQUINOX_COSMOS_COLLECTION const string connVar = "EQUINOX_COSMOS_CONNECTION"; var conn = Environment.GetEnvironmentVariable(connVar); const string dbVar = "EQUINOX_COSMOS_DATABASE"; var db = Environment.GetEnvironmentVariable(dbVar); const string collVar = "EQUINOX_COSMOS_COLLECTION"; var coll = Environment.GetEnvironmentVariable(collVar); if (conn == null || db == null || coll == null) { throw new Exception( $"Event Storage subsystem requires the following Environment Variables to be specified: {connVar} {dbVar}, {collVar}"); } var connMode = Equinox.Cosmos.ConnectionMode.DirectTcp; var config = new CosmosConfig(connMode, conn, db, coll, cacheMb); return(new CosmosContext(config)); #endif #if (!cosmos && !eventStore) return(new MemoryStoreContext(new Equinox.MemoryStore.VolatileStore())); #endif #if (!memoryStore && !cosmos && !eventStore) //return new MemoryStoreContext(new Equinox.MemoryStore.VolatileStore()); #endif }
public override void Configure(IFunctionsHostBuilder builder) { var connectionString = Environment.GetEnvironmentVariable("APP_CONFIG_CONNECTION"); var settings = builder .BindSettings <AppSettings>(connectionString); var cosmosConfig = new CosmosConfig( settings.CosmosSettings.DatabaseName, settings.CosmosSettings.EndpointUri, settings.CosmosSettings.PrimaryKey, settings.CosmosSettings.RequestTimeoutInSeconds ); builder.Services .AddLazyCache() .InjectCosmosStore <LogQuery, OrchestrationLog>(cosmosConfig) .InjectCosmosStore <ResourceHistoryQuery <ProductHistory>, ProductHistory>(cosmosConfig) .InjectCosmosStore <ResourceHistoryQuery <PriceScheduleHistory>, PriceScheduleHistory>(cosmosConfig) .Inject <IOrderCloudIntegrationsFunctionToken>() .AddSingleton <ICMSClient>(new CMSClient(new CMSClientConfig() { BaseUrl = settings.CMSSettings.BaseUrl })) .InjectOrderCloud <IOrderCloudClient>(new OrderCloudClientConfig() { ApiUrl = settings.OrderCloudSettings.ApiUrl, AuthUrl = settings.OrderCloudSettings.ApiUrl, ClientId = settings.OrderCloudSettings.MiddlewareClientID, ClientSecret = settings.OrderCloudSettings.MiddlewareClientSecret, Roles = new[] { ApiRole.FullAccess } }) .AddSingleton <IFlurlClientFactory, PerBaseUrlFlurlClientFactory>() .Inject <IOrchestrationCommand>() .Inject <ISupplierSyncCommand>() .Inject <ISyncCommand>() .Inject <IProductTemplateCommand>() .Inject <ISendgridService>(); }
async static Task Main(string[] args) { string currentDirectory = Environment.CurrentDirectory; IConfigurationRoot config = new ConfigurationBuilder() .SetBasePath(currentDirectory) .AddJsonFile("appsettings.json", true) .Build(); CosmosConfig cosmosConfig = config.GetSection("CosmosConfig").Get <CosmosConfig>(); SendGridConfig sendGridConfig = config.GetSection("SendGridConfig").Get <SendGridConfig>(); SendGridClient sgc = new SendGridClient(sendGridConfig.ApiKey); CosmosDbService cosmosDbService = InitializeCosmosClientInstance(cosmosConfig); EmailTemplateUploader emailTemplateUploader = new EmailTemplateUploader( sgc, cosmosDbService ); await emailTemplateUploader.Migrate(); }
static async Task Main(string[] args) { var services = new ServiceCollection(); var builder = new ConfigurationBuilder(); var settings = new AppSettings(); builder.AddAzureAppConfiguration(Environment.GetEnvironmentVariable("APP_CONFIG_CONNECTION")); var config = builder.Build(); config.Bind(settings); var cosmosConfig = new CosmosConfig( settings.CosmosSettings.DatabaseName, settings.CosmosSettings.EndpointUri, settings.CosmosSettings.PrimaryKey, settings.CosmosSettings.RequestTimeoutInSeconds, settings.CosmosSettings.MaxConnectionLimit, settings.CosmosSettings.IdleTcpConnectionTimeoutInMinutes, settings.CosmosSettings.OpenTcpConnectionTimeoutInSeconds, settings.CosmosSettings.MaxTcpConnectionsPerEndpoint, settings.CosmosSettings.MaxRequestsPerTcpConnection, settings.CosmosSettings.EnableTcpConnectionEndpointRediscovery ); _provider = services .AddSingleton(settings) .AddSingleton <ICosmosBulkOperations>(new CosmosBulkOperations(cosmosConfig)) .BuildServiceProvider(); Trace.AutoFlush = true; Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); Trace.WriteLine("Entering Main"); var editor = _provider.GetService <ICosmosBulkOperations>(); var migration = new one_big_bucket_option_13oct2020(editor); await migration.Run(); }
public CosmosDbAndInMemoryPlayerService(IMemoryCache memoryCache, IOptions <CosmosConfig> config) : base(memoryCache) { _cosmosClient = CloudStorageAccount.Parse(config.Value.ConnectionString); _config = config.Value; }
public CosmosDbGameRepository(IOptions <CosmosConfig> config) { _cosmosClient = CloudStorageAccount.Parse(config.Value.ConnectionString); _config = config.Value; }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { var cosmosConfig = new CosmosConfig( _settings.CosmosSettings.DatabaseName, _settings.CosmosSettings.EndpointUri, _settings.CosmosSettings.PrimaryKey, _settings.CosmosSettings.RequestTimeoutInSeconds ); var cosmosContainers = new List <ContainerInfo>() { new ContainerInfo() { Name = "salesorderdetail", PartitionKey = "/PartitionKey" }, new ContainerInfo() { Name = "purchaseorderdetail", PartitionKey = "/PartitionKey" }, new ContainerInfo() { Name = "lineitemdetail", PartitionKey = "/PartitionKey" }, new ContainerInfo() { Name = "rmas", PartitionKey = "/PartitionKey" }, new ContainerInfo() { Name = "shipmentdetail", PartitionKey = "/PartitionKey" }, new ContainerInfo() { Name = "productdetail", PartitionKey = "/PartitionKey" } }; var avalaraConfig = new AvalaraConfig() { BaseApiUrl = _settings.AvalaraSettings.BaseApiUrl, AccountID = _settings.AvalaraSettings.AccountID, LicenseKey = _settings.AvalaraSettings.LicenseKey, CompanyCode = _settings.AvalaraSettings.CompanyCode, CompanyID = _settings.AvalaraSettings.CompanyID }; var currencyConfig = new BlobServiceConfig() { ConnectionString = _settings.StorageAccountSettings.ConnectionString, Container = _settings.StorageAccountSettings.BlobContainerNameExchangeRates }; var assetConfig = new BlobServiceConfig() { ConnectionString = _settings.StorageAccountSettings.ConnectionString, Container = "assets", AccessType = BlobContainerPublicAccessType.Container }; var flurlClientFactory = new PerBaseUrlFlurlClientFactory(); var smartyStreetsUsClient = new ClientBuilder(_settings.SmartyStreetSettings.AuthID, _settings.SmartyStreetSettings.AuthToken).BuildUsStreetApiClient(); var orderCloudClient = new OrderCloudClient(new OrderCloudClientConfig { ApiUrl = _settings.OrderCloudSettings.ApiUrl, AuthUrl = _settings.OrderCloudSettings.ApiUrl, ClientId = _settings.OrderCloudSettings.MiddlewareClientID, ClientSecret = _settings.OrderCloudSettings.MiddlewareClientSecret, Roles = new[] { ApiRole.FullAccess } }); AvalaraCommand avalaraCommand = null; VertexCommand vertexCommand = null; TaxJarCommand taxJarCommand = null; switch (_settings.EnvironmentSettings.TaxProvider) { case TaxProvider.Avalara: avalaraCommand = new AvalaraCommand(avalaraConfig, _settings.EnvironmentSettings.Environment.ToString()); break; case TaxProvider.Taxjar: taxJarCommand = new TaxJarCommand(_settings.TaxJarSettings); break; case TaxProvider.Vertex: vertexCommand = new VertexCommand(_settings.VertexSettings); break; default: break; } services.AddMvc(o => { o.Filters.Add(new ordercloud.integrations.library.ValidateModelAttribute()); o.EnableEndpointRouting = false; }) .ConfigureApiBehaviorOptions(o => o.SuppressModelStateInvalidFilter = true) .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddNewtonsoftJson(options => { options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); options.SerializerSettings.Converters.Add(new StringEnumConverter()); }); services .AddCors(o => o.AddPolicy("integrationcors", builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); })) .AddSingleton <ISimpleCache, LazyCacheService>() // Replace LazyCacheService with RedisService if you have multiple server instances. .AddOrderCloudUserAuth() .AddOrderCloudWebhookAuth(opts => opts.HashKey = _settings.OrderCloudSettings.WebhookHashKey) .InjectCosmosStore <LogQuery, OrchestrationLog>(cosmosConfig) .InjectCosmosStore <ReportTemplateQuery, ReportTemplate>(cosmosConfig) .AddCosmosDb(_settings.CosmosSettings.EndpointUri, _settings.CosmosSettings.PrimaryKey, _settings.CosmosSettings.DatabaseName, cosmosContainers) .Inject <IPortalService>() .Inject <ISmartyStreetsCommand>() .Inject <ICheckoutIntegrationCommand>() .Inject <IShipmentCommand>() .Inject <IOrderCommand>() .Inject <IPaymentCommand>() .Inject <IOrderSubmitCommand>() .Inject <IEnvironmentSeedCommand>() .Inject <IHSProductCommand>() .Inject <ILineItemCommand>() .Inject <IMeProductCommand>() .Inject <IDiscountDistributionService>() .Inject <IHSCatalogCommand>() .Inject <ISendgridService>() .Inject <IHSSupplierCommand>() .Inject <ICreditCardCommand>() .Inject <ISupportAlertService>() .Inject <ISupplierApiClientHelper>() .AddSingleton <ISendGridClient>(x => new SendGridClient(_settings.SendgridSettings.ApiKey)) .AddSingleton <IFlurlClientFactory>(x => flurlClientFactory) .AddSingleton <DownloadReportCommand>() .Inject <IRMARepo>() .Inject <IZohoClient>() .AddSingleton <IZohoCommand>(z => new ZohoCommand(new ZohoClient( new ZohoClientConfig() { ApiUrl = "https://books.zoho.com/api/v3", AccessToken = _settings.ZohoSettings.AccessToken, ClientId = _settings.ZohoSettings.ClientId, ClientSecret = _settings.ZohoSettings.ClientSecret, OrganizationID = _settings.ZohoSettings.OrgID }, flurlClientFactory), orderCloudClient)) .AddSingleton <IOrderCloudIntegrationsExchangeRatesClient, OrderCloudIntegrationsExchangeRatesClient>() .AddSingleton <IAssetClient>(provider => new AssetClient(new OrderCloudIntegrationsBlobService(assetConfig), _settings)) .AddSingleton <IExchangeRatesCommand>(provider => new ExchangeRatesCommand(new OrderCloudIntegrationsBlobService(currencyConfig), flurlClientFactory, provider.GetService <ISimpleCache>())) .AddSingleton <ITaxCodesProvider>(provider => { return(_settings.EnvironmentSettings.TaxProvider switch { TaxProvider.Avalara => avalaraCommand, TaxProvider.Taxjar => taxJarCommand, TaxProvider.Vertex => new NotImplementedTaxCodesProvider(), _ => avalaraCommand // Avalara is default }); })
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { var cosmosConfig = new CosmosConfig( _settings.CosmosSettings.DatabaseName, _settings.CosmosSettings.EndpointUri, _settings.CosmosSettings.PrimaryKey, _settings.CosmosSettings.RequestTimeoutInSeconds ); var cosmosContainers = new List <ContainerInfo>() { new ContainerInfo() { Name = "rmas", PartitionKey = "PartitionKey" } }; var avalaraConfig = new AvalaraConfig() { BaseApiUrl = _settings.AvalaraSettings.BaseApiUrl, AccountID = _settings.AvalaraSettings.AccountID, LicenseKey = _settings.AvalaraSettings.LicenseKey, CompanyCode = _settings.AvalaraSettings.CompanyCode, CompanyID = _settings.AvalaraSettings.CompanyID }; var currencyConfig = new BlobServiceConfig() { ConnectionString = _settings.BlobSettings.ConnectionString, Container = _settings.BlobSettings.ContainerNameExchangeRates }; var assetConfig = new BlobServiceConfig() { ConnectionString = _settings.BlobSettings.ConnectionString, Container = "assets", AccessType = BlobContainerPublicAccessType.Container }; var flurlClientFactory = new PerBaseUrlFlurlClientFactory(); var smartyStreetsUsClient = new ClientBuilder(_settings.SmartyStreetSettings.AuthID, _settings.SmartyStreetSettings.AuthToken).BuildUsStreetApiClient(); services .Configure <KestrelServerOptions>(options => { options.AllowSynchronousIO = true; }) .Configure <IISServerOptions>(options => { options.AllowSynchronousIO = true; }) .AddSingleton <ISimpleCache, OrderCloud.Common.Services.LazyCacheService>() // Replace LazyCacheService with RedisService if you have multiple server instances. .ConfigureServices() .AddOrderCloudUserAuth() .AddOrderCloudWebhookAuth(opts => opts.HashKey = _settings.OrderCloudSettings.WebhookHashKey) .InjectCosmosStore <LogQuery, OrchestrationLog>(cosmosConfig) .InjectCosmosStore <ReportTemplateQuery, ReportTemplate>(cosmosConfig) .AddCosmosDb(_settings.CosmosSettings.EndpointUri, _settings.CosmosSettings.PrimaryKey, _settings.CosmosSettings.DatabaseName, cosmosContainers) .Inject <IPortalService>() .Inject <ISmartyStreetsCommand>() .Inject <ICheckoutIntegrationCommand>() .Inject <IShipmentCommand>() .Inject <IOrderCommand>() .Inject <IPaymentCommand>() .Inject <IOrderSubmitCommand>() .Inject <IEnvironmentSeedCommand>() .Inject <IHSProductCommand>() .Inject <ILineItemCommand>() .Inject <IMeProductCommand>() .Inject <IHSCatalogCommand>() .Inject <ISendgridService>() .Inject <IHSSupplierCommand>() .Inject <ICreditCardCommand>() .Inject <ISupportAlertService>() .Inject <IUserContextProvider>() .Inject <ISupplierApiClientHelper>() .AddSingleton <ISendGridClient>(x => new SendGridClient(_settings.SendgridSettings.ApiKey)) .AddSingleton <IFlurlClientFactory>(x => flurlClientFactory) .AddSingleton <DownloadReportCommand>() .Inject <IRMARepo>() .Inject <IZohoClient>() .AddSingleton <IZohoCommand>(z => new ZohoCommand(new ZohoClient( new ZohoClientConfig() { ApiUrl = "https://books.zoho.com/api/v3", AccessToken = _settings.ZohoSettings.AccessToken, ClientId = _settings.ZohoSettings.ClientId, ClientSecret = _settings.ZohoSettings.ClientSecret, OrganizationID = _settings.ZohoSettings.OrgID }, flurlClientFactory), new OrderCloudClient(new OrderCloudClientConfig { ApiUrl = _settings.OrderCloudSettings.ApiUrl, AuthUrl = _settings.OrderCloudSettings.ApiUrl, ClientId = _settings.OrderCloudSettings.MiddlewareClientID, ClientSecret = _settings.OrderCloudSettings.MiddlewareClientSecret, Roles = new[] { ApiRole.FullAccess } }))) .AddSingleton <IOrderCloudIntegrationsExchangeRatesClient, OrderCloudIntegrationsExchangeRatesClient>() .AddSingleton <IAssetClient>(provider => new AssetClient(new OrderCloudIntegrationsBlobService(assetConfig), _settings)) .AddSingleton <IExchangeRatesCommand>(provider => new ExchangeRatesCommand(new OrderCloudIntegrationsBlobService(currencyConfig), flurlClientFactory, provider.GetService <ISimpleCache>())) .AddSingleton <IAvalaraCommand>(x => new AvalaraCommand( avalaraConfig, new AvaTaxClient("four51_headstart", "v1", "four51_headstart", new Uri(avalaraConfig.BaseApiUrl) ).WithSecurity(_settings.AvalaraSettings.AccountID, _settings.AvalaraSettings.LicenseKey), _settings.EnvironmentSettings.Environment.ToString())) .AddSingleton <IEasyPostShippingService>(x => new EasyPostShippingService(new EasyPostConfig() { APIKey = _settings.EasyPostSettings.APIKey })) .AddSingleton <ISmartyStreetsService>(x => new SmartyStreetsService(_settings.SmartyStreetSettings, smartyStreetsUsClient)) .AddSingleton <IOrderCloudIntegrationsCardConnectService>(x => new OrderCloudIntegrationsCardConnectService(_settings.CardConnectSettings, _settings.EnvironmentSettings.Environment.ToString(), flurlClientFactory)) .AddSingleton <IOrderCloudClient>(provider => new OrderCloudClient(new OrderCloudClientConfig { ApiUrl = _settings.OrderCloudSettings.ApiUrl, AuthUrl = _settings.OrderCloudSettings.ApiUrl, ClientId = _settings.OrderCloudSettings.MiddlewareClientID, ClientSecret = _settings.OrderCloudSettings.MiddlewareClientSecret, Roles = new[] { ApiRole.FullAccess } })) .AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Headstart API", Version = "v1" }); c.CustomSchemaIds(x => x.FullName); }); var serviceProvider = services.BuildServiceProvider(); services .AddApplicationInsightsTelemetry(new ApplicationInsightsServiceOptions { EnableAdaptiveSampling = false, // retain all data InstrumentationKey = _settings.ApplicationInsightsSettings.InstrumentationKey }); ServicePointManager.DefaultConnectionLimit = int.MaxValue; FlurlHttp.Configure(settings => settings.Timeout = TimeSpan.FromSeconds(_settings.FlurlSettings.TimeoutInSeconds == 0 ? 30 : _settings.FlurlSettings.TimeoutInSeconds)); // This adds retry logic for any api call that fails with a transient error (server errors, timeouts, or rate limiting requests) // Will retry up to 3 times using exponential backoff and jitter, a mean of 3 seconds wait time in between retries // https://github.com/App-vNext/Polly/wiki/Retry-with-jitter#more-complex-jitter var delay = Backoff.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: TimeSpan.FromSeconds(3), retryCount: 3); var policy = HttpPolicyExtensions .HandleTransientHttpError() .OrResult(response => response.StatusCode == HttpStatusCode.TooManyRequests) .WaitAndRetryAsync(delay); FlurlHttp.Configure(settings => settings.HttpClientFactory = new PollyFactory(policy)); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { var cosmosConfig = new CosmosConfig( _settings.CosmosSettings.DatabaseName, _settings.CosmosSettings.EndpointUri, _settings.CosmosSettings.PrimaryKey, _settings.CosmosSettings.RequestTimeoutInSeconds ); var cosmosContainers = new List <ContainerInfo>() { new ContainerInfo() { Name = "rmas", PartitionKey = "PartitionKey" } }; var avalaraConfig = new AvalaraConfig() { BaseApiUrl = _settings.AvalaraSettings.BaseApiUrl, AccountID = _settings.AvalaraSettings.AccountID, LicenseKey = _settings.AvalaraSettings.LicenseKey, CompanyCode = _settings.AvalaraSettings.CompanyCode, CompanyID = _settings.AvalaraSettings.CompanyID }; var currencyConfig = new BlobServiceConfig() { ConnectionString = _settings.BlobSettings.ConnectionString, Container = _settings.BlobSettings.ContainerNameExchangeRates }; var middlewareErrorsConfig = new BlobServiceConfig() { ConnectionString = _settings.BlobSettings.ConnectionString, Container = "unhandled-errors-log" }; var flurlClientFactory = new PerBaseUrlFlurlClientFactory(); var smartyStreetsUsClient = new ClientBuilder(_settings.SmartyStreetSettings.AuthID, _settings.SmartyStreetSettings.AuthToken).BuildUsStreetApiClient(); services .AddLazyCache() .OrderCloudIntegrationsConfigureWebApiServices(_settings, middlewareErrorsConfig, corsPolicyName: "headstarcors") .InjectCosmosStore <LogQuery, OrchestrationLog>(cosmosConfig) .InjectCosmosStore <ReportTemplateQuery, ReportTemplate>(cosmosConfig) .AddCosmosDb(_settings.CosmosSettings.EndpointUri, _settings.CosmosSettings.PrimaryKey, _settings.CosmosSettings.DatabaseName, cosmosContainers) .Inject <IPortalService>() .Inject <ISmartyStreetsCommand>() .Inject <ICheckoutIntegrationCommand>() .Inject <IShipmentCommand>() .Inject <IOrderCommand>() .Inject <IPaymentCommand>() .Inject <IOrderSubmitCommand>() .Inject <IEnvironmentSeedCommand>() .Inject <IHSProductCommand>() .Inject <ILineItemCommand>() .Inject <IMeProductCommand>() .Inject <IHSCatalogCommand>() .Inject <ISendgridService>() .Inject <IHSSupplierCommand>() .Inject <ICreditCardCommand>() .Inject <ISupportAlertService>() .Inject <IOrderCalcService>() .Inject <ISupplierApiClientHelper>() .AddSingleton <ICMSClient>(new CMSClient(new CMSClientConfig() { BaseUrl = _settings.CMSSettings.BaseUrl })) .AddSingleton <ISendGridClient>(x => new SendGridClient(_settings.SendgridSettings.ApiKey)) .AddSingleton <IFlurlClientFactory>(x => flurlClientFactory) .AddSingleton <DownloadReportCommand>() .Inject <IRMARepo>() .Inject <IZohoClient>() .AddSingleton <IZohoCommand>(z => new ZohoCommand(new ZohoClient( new ZohoClientConfig() { ApiUrl = "https://books.zoho.com/api/v3", AccessToken = _settings.ZohoSettings.AccessToken, ClientId = _settings.ZohoSettings.ClientId, ClientSecret = _settings.ZohoSettings.ClientSecret, OrganizationID = _settings.ZohoSettings.OrgID }, flurlClientFactory), new OrderCloudClient(new OrderCloudClientConfig { ApiUrl = _settings.OrderCloudSettings.ApiUrl, AuthUrl = _settings.OrderCloudSettings.ApiUrl, ClientId = _settings.OrderCloudSettings.MiddlewareClientID, ClientSecret = _settings.OrderCloudSettings.MiddlewareClientSecret, Roles = new[] { ApiRole.FullAccess } }))) .AddSingleton <IOrderCloudIntegrationsExchangeRatesClient, OrderCloudIntegrationsExchangeRatesClient>() .AddSingleton <IExchangeRatesCommand>(provider => new ExchangeRatesCommand(currencyConfig, flurlClientFactory, provider.GetService <IAppCache>())) .AddSingleton <IAvalaraCommand>(x => new AvalaraCommand( avalaraConfig, new AvaTaxClient("four51_headstart", "v1", "four51_headstart", new Uri(avalaraConfig.BaseApiUrl) ).WithSecurity(_settings.AvalaraSettings.AccountID, _settings.AvalaraSettings.LicenseKey))) .AddSingleton <IEasyPostShippingService>(x => new EasyPostShippingService(new EasyPostConfig() { APIKey = _settings.EasyPostSettings.APIKey })) .AddSingleton <ISmartyStreetsService>(x => new SmartyStreetsService(_settings.SmartyStreetSettings, smartyStreetsUsClient)) .AddSingleton <IOrderCloudIntegrationsCardConnectService>(x => new OrderCloudIntegrationsCardConnectService(_settings.CardConnectSettings, flurlClientFactory)) .AddSingleton <IOrderCloudClient>(provider => new OrderCloudClient(new OrderCloudClientConfig { ApiUrl = _settings.OrderCloudSettings.ApiUrl, AuthUrl = _settings.OrderCloudSettings.ApiUrl, ClientId = _settings.OrderCloudSettings.MiddlewareClientID, ClientSecret = _settings.OrderCloudSettings.MiddlewareClientSecret, Roles = new[] { ApiRole.FullAccess } })) .AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Headstart API", Version = "v1" }); c.CustomSchemaIds(x => x.FullName); }) .AddAuthentication(); var serviceProvider = services.BuildServiceProvider(); services .AddAuthenticationScheme <OrderCloudIntegrationsAuthOptions, OrderCloudIntegrationsAuthHandler>("OrderCloudIntegrations", opts => opts.OrderCloudClient = serviceProvider.GetService <IOrderCloudClient>()) .AddAuthenticationScheme <OrderCloudWebhookAuthOptions, OrderCloudWebhookAuthHandler>("OrderCloudWebhook", opts => opts.HashKey = _settings.OrderCloudSettings.WebhookHashKey) .AddApplicationInsightsTelemetry(new ApplicationInsightsServiceOptions { EnableAdaptiveSampling = false, // retain all data InstrumentationKey = _settings.ApplicationInsightsSettings.InstrumentationKey }); ServicePointManager.DefaultConnectionLimit = int.MaxValue; FlurlHttp.Configure(settings => settings.Timeout = TimeSpan.FromSeconds(_settings.FlurlSettings.TimeoutInSeconds)); }
public override void Configure(IFunctionsHostBuilder builder) { var connectionString = Environment.GetEnvironmentVariable("APP_CONFIG_CONNECTION"); var settings = new AppSettings(); var config = new ConfigurationBuilder() .AddEnvironmentVariables() .AddAzureAppConfiguration(connectionString) .Build(); config.Bind(settings); var cosmosConfig = new CosmosConfig( settings.CosmosSettings.DatabaseName, settings.CosmosSettings.EndpointUri, settings.CosmosSettings.PrimaryKey, settings.CosmosSettings.RequestTimeoutInSeconds ); var cosmosContainers = new List <ContainerInfo>() { new ContainerInfo() { Name = "salesorderdetail", PartitionKey = "/PartitionKey" }, new ContainerInfo() { Name = "purchaseorderdetail", PartitionKey = "/PartitionKey" }, new ContainerInfo() { Name = "lineitemdetail", PartitionKey = "/PartitionKey" }, new ContainerInfo() { Name = "rmas", PartitionKey = "/PartitionKey" }, new ContainerInfo() { Name = "shipmentdetail", PartitionKey = "/PartitionKey" }, new ContainerInfo() { Name = "productdetail", PartitionKey = "/PartitionKey" } }; // https://github.com/Polly-Contrib/Polly.Contrib.WaitAndRetry#wait-and-retry-with-jittered-back-off var delay = Backoff.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: TimeSpan.FromSeconds(30), retryCount: 3); var policy = HttpPolicyExtensions .HandleTransientHttpError() .OrResult(response => response.StatusCode == HttpStatusCode.TooManyRequests) .WaitAndRetryAsync(delay); var flurlClientFactory = new PerBaseUrlFlurlClientFactory(); FlurlHttp.Configure(settings => settings.HttpClientFactory = new PollyFactory(policy)); builder.Services .InjectOrderCloud <IOrderCloudClient>(new OrderCloudClientConfig() { ApiUrl = settings.OrderCloudSettings.ApiUrl, AuthUrl = settings.OrderCloudSettings.ApiUrl, ClientId = settings.OrderCloudSettings.MiddlewareClientID, ClientSecret = settings.OrderCloudSettings.MiddlewareClientSecret, Roles = new[] { ApiRole.FullAccess } }) .AddCosmosDb(settings.CosmosSettings.EndpointUri, settings.CosmosSettings.PrimaryKey, settings.CosmosSettings.DatabaseName, cosmosContainers) .AddSingleton <IFlurlClientFactory, PerBaseUrlFlurlClientFactory>() .AddSingleton <IOrderCloudIntegrationsCardConnectService>(x => new OrderCloudIntegrationsCardConnectService(settings.CardConnectSettings, settings.EnvironmentSettings.Environment.ToString(), flurlClientFactory)) .Inject <IHSCatalogCommand>() .Inject <IHSBuyerLocationCommand>() .AddSingleton <PaymentCaptureJob>() .AddSingleton <SendRecentOrdersJob>() .AddSingleton <ReceiveRecentSalesOrdersJob>() .AddSingleton <ReceiveProductDetailsJob>() .AddSingleton <ReceiveRecentPurchaseOrdersJob>() .AddSingleton <ReceiveRecentLineItemsJob>() .AddSingleton <ReceiveRecentOrdersAndShipmentsJob>() .AddSingleton(x => new ZohoClientConfig { ApiUrl = "https://books.zoho.com/api/v3", AccessToken = settings.ZohoSettings.AccessToken, ClientId = settings.ZohoSettings.ClientId, ClientSecret = settings.ZohoSettings.ClientSecret, OrganizationID = settings.ZohoSettings.OrgID }) .Inject <IZohoClient>() .Inject <IZohoCommand>() .AddSingleton <ISendGridClient>(x => new SendGridClient(settings.SendgridSettings.ApiKey)) .Inject <ISendgridService>() .Inject <ISalesOrderDetailDataRepo>() .Inject <IPurchaseOrderDetailDataRepo>() .Inject <ILineItemDetailDataRepo>() .Inject <IOrdersAndShipmentsDataRepo>() .AddSingleton(settings) .AddMvcCore().AddNewtonsoftJson(o => { o.SerializerSettings.ContractResolver = new DefaultContractResolver(); o.SerializerSettings.Converters.Add(new StringEnumConverter()); o.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }) .Services.Replace(ServiceDescriptor.Singleton(typeof(IConfiguration), config)); }
public override void Configure(IFunctionsHostBuilder builder) { // We need to get the app directory this way. Using Environment.CurrentDirectory doesn't work in Azure ExecutionContextOptions executioncontextoptions = builder.Services.BuildServiceProvider() .GetService <IOptions <ExecutionContextOptions> >().Value; string currentDirectory = executioncontextoptions.AppDirectory; IConfigurationBuilder configBuilder = new ConfigurationBuilder() .SetBasePath(currentDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); IConfigurationRoot config = configBuilder.Build(); // DI doesn't work in startup PollyHttpPolicies pollyHttpPolicies = new PollyHttpPolicies(new PollyHttpPoliciesConfig()); Dictionary <HttpClientConfigName, ApiConfig> httpClientConfigs = config.GetSection("Apis").Get <Dictionary <HttpClientConfigName, ApiConfig> >(); foreach (KeyValuePair <HttpClientConfigName, ApiConfig> httpClientConfig in httpClientConfigs) { IAsyncPolicy <HttpResponseMessage> retryPolicy = httpClientConfig.Value.IsExternal ? pollyHttpPolicies.ExternalHttpRetryPolicy : pollyHttpPolicies.InternalHttpRetryPolicy; builder.Services.AddHttpClient(httpClientConfig.Key.ToString(), c => { c.BaseAddress = new Uri(httpClientConfig.Value.BaseAddress); c.Timeout = httpClientConfig.Value.Timeout ?? new TimeSpan(0, 0, 0, 15); foreach (KeyValuePair <string, string> header in httpClientConfig.Value.Headers) { c.DefaultRequestHeaders.Add(header.Key, header.Value); } c.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); c.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate")); }).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { MaxConnectionsPerServer = httpClientConfig.Value.MaxConnectionsPerServer ?? 15, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }).AddPolicyHandler(retryPolicy); } IConfigurationSection emailConfigSettings = config.GetSection("EmailConfig"); builder.Services.Configure <EmailConfig>(emailConfigSettings); IConfigurationSection serviceBusConfigSettings = config.GetSection("ServiceBusConfig"); builder.Services.Configure <ServiceBusConfig>(serviceBusConfigSettings); ServiceBusConfig serviceBusConfig = serviceBusConfigSettings.Get <ServiceBusConfig>(); IConfigurationSection sendGridConfigSettings = config.GetSection("SendGridConfig"); builder.Services.Configure <SendGridConfig>(sendGridConfigSettings); var sendGridConfig = config.GetSection("SendGridConfig").Get <SendGridConfig>(); builder.Services.AddSingleton <ISendGridClient>(new SendGridClient(sendGridConfig.ApiKey)); builder.Services.AddTransient <IHttpClientWrapper, HttpClientWrapper>(); builder.Services.AddMediatR(typeof(SendEmailHandler).Assembly); builder.Services.AddAutoMapper(typeof(AddressDetailsProfile).Assembly); builder.Services.AddSingleton <IQueueClient>(new QueueClient(serviceBusConfig.ConnectionString, serviceBusConfig.MessageQueueName)); builder.Services.AddSingleton <IMessageFactory, MessageFactory>(); //builder.Services.AddSingleton<IConnectSendGridService, SendGridService>(); builder.Services.AddSingleton <ISendEmailService, SendEmailService>(); builder.Services.AddSingleton <IConnectUserService, ConnectUserService>(); builder.Services.AddSingleton <IConnectRequestService, ConnectRequestService>(); builder.Services.AddSingleton <IConnectGroupService, ConnectGroupService>(); builder.Services.AddTransient <IJobFilteringService, JobFilteringService>(); builder.Services.AddSingleton <IConnectAddressService, ConnectAddressService>(); builder.Services.AddSingleton <IConnectSendGridService, ConnectSendGridService>(); builder.Services.AddSingleton <IDistanceCalculator, DistanceCalculator>(); builder.Services.AddSingleton <IPurgeService, PurgeService>(); builder.Services.AddDbContext <ApplicationDbContext>(options => options.UseInMemoryDatabase(databaseName: "CommunicationService.AzureFunction")); builder.Services.AddTransient <IRepository, Repository>(); CosmosConfig cosmosConfig = config.GetSection("CosmosConfig").Get <CosmosConfig>(); builder.Services.AddSingleton <ICosmosDbService>(InitializeCosmosClientInstance(cosmosConfig)); InterUserMessageConfig interUserMessageConfig = config.GetSection("InterUserMessageConfig").Get <InterUserMessageConfig>(); builder.Services.AddSingleton <IInterUserMessageRepository>(InitializeCosmosClientInstance(interUserMessageConfig)); IConfigurationSection linkConfigSettings = config.GetSection("LinkConfig"); builder.Services.Configure <LinkConfig>(linkConfigSettings); LinkConfig linkConfig = config.GetSection("LinkConfig").Get <LinkConfig>(); builder.Services.AddSingleton <ILinkRepository>(InitializeCosmosClientInstance(linkConfig)); SendGridManagement.EmailTemplateUploader emailTemplateUploader = new SendGridManagement.EmailTemplateUploader(new SendGridClient(sendGridConfig.ApiKey), InitializeCosmosClientInstance(cosmosConfig)); builder.Services.AddSingleton <IPollyMemoryCacheProvider, PollyMemoryCacheProvider>(); builder.Services.AddMemCache(); builder.Services.AddSingleton(x => x.GetService <IMemDistCacheFactory <LocationDetails> >().GetCache(new TimeSpan(30, 0, 0, 0), ResetTimeFactory.OnMidday)); builder.Services.AddSingleton(x => x.GetService <IMemDistCacheFactory <Template> >().GetCache(new TimeSpan(30, 0, 0, 0), ResetTimeFactory.OnMidday)); builder.Services.AddSingleton(x => x.GetService <IMemDistCacheFactory <UnsubscribeGroup> >().GetCache(new TimeSpan(30, 0, 0, 0), ResetTimeFactory.OnMidday)); emailTemplateUploader.Migrate().ConfigureAwait(false); }
public CosmosWrapperService(CosmosService cosmosService, IOptions <CosmosConfig> cosmosConfig) { _cosmosService = cosmosService; this.cosmosConfig = cosmosConfig.Value; }
public CosmosService(IOptions <CosmosConfig> cosmosConfig, IOptions <CmsConfiguration> cmsConfiguration) { this.cosmosConfig = cosmosConfig.Value; this.cmsConfiguration = cmsConfiguration.Value; }
public CosmosDbContext(CosmosConfig cosmosConfig) { this._cosmosConfig = cosmosConfig; }
/// <summary> /// Creates a Cosmos DB database and a container with the specified partition key. /// </summary> /// <returns></returns> private static async Task <CosmosDbService> InitializeCosmosClientInstanceAsync(CosmosConfig cosmosConfig) { var clientBuilder = new Microsoft.Azure.Cosmos.Fluent.CosmosClientBuilder(cosmosConfig.Account, cosmosConfig.Key); var client = clientBuilder .WithConnectionModeDirect() .Build(); var cosmosDbService = new CosmosDbService(client, cosmosConfig.DatabaseName, cosmosConfig.ContainerName); var database = await client.CreateDatabaseIfNotExistsAsync(cosmosConfig.DatabaseName); await database.Database.CreateContainerIfNotExistsAsync(cosmosConfig.ContainerName, "/pk"); return(cosmosDbService); }