/// <summary> /// Initializes a new instance of the <see cref="Startup"/> class. /// </summary> /// <param name="config">The <see cref="IConfiguration"/>.</param> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param> public Startup(IConfiguration config, ILoggerFactory loggerFactory) { // Use JSON property names in validation; and determine whether unhandled exception details are to be included in the response. ValidationArgs.DefaultUseJsonNames = true; WebApiExceptionHandlerMiddleware.IncludeUnhandledExceptionInResponse = config.GetValue <bool>("BeefIncludeExceptionInInternalServerError"); // Add "page" and "page-size" to the supported paging query string parameters as defined by the CDR specification; and default the page size to 25 from config. WebApiQueryString.PagingArgsPageQueryStringNames.Add("page"); WebApiQueryString.PagingArgsTakeQueryStringNames.Add("page-size"); PagingArgs.DefaultTake = config.GetValue <int>("BeefDefaultPageSize"); // Configure the logger. _logger = loggerFactory.CreateLogger("Logging"); Logger.RegisterGlobal((largs) => WebApiStartup.BindLogger(_logger, largs)); // Configure the cache policies. CachePolicyManager.SetFromCachePolicyConfig(config.GetSection("BeefCaching").Get <CachePolicyConfig>()); CachePolicyManager.StartFlushTimer(CachePolicyManager.TenMinutes, CachePolicyManager.FiveMinutes); // Register the DocumentDb/CosmosDb client. CosmosDb.Register(() => { var cs = config.GetSection("CosmosDb"); return(new CosmosDb(new Microsoft.Azure.Cosmos.CosmosClient(cs.GetValue <string>("EndPoint"), cs.GetValue <string>("AuthKey")), cs.GetValue <string>("Database"))); }); // Register the ReferenceData provider. Beef.RefData.ReferenceDataManager.Register(new ReferenceDataProvider()); // Register the "customised" execution context. Beef.ExecutionContext.Register(() => new ExecutionContext()); }
/// <summary> /// Initializes a new instance of the <see cref="Startup"/> class. /// </summary> /// <param name="config">The <see cref="IConfiguration"/>.</param> public Startup(IConfiguration config) { // Use JSON property names in validation. ValidationArgs.DefaultUseJsonNames = true; // Load the cache policies. CachePolicyManager.SetFromCachePolicyConfig(config.GetSection("BeefCaching").Get <CachePolicyConfig>()); CachePolicyManager.StartFlushTimer(CachePolicyManager.TenMinutes, CachePolicyManager.FiveMinutes); // Register the ReferenceData provider. Beef.RefData.ReferenceDataManager.Register(new ReferenceDataProvider()); #if (implement_database || implement_entityframework) // Register the database. Database.Register(() => new Database(WebApiStartup.GetConnectionString(config, "Database"))); #endif #if (implement_cosmos) // Register the DocumentDb/CosmosDb client. CosmosDb.Register(() => { var cs = config.GetSection("CosmosDb"); return(new CosmosDb(new Cosmos.CosmosClient(cs.GetValue <string>("EndPoint"), cs.GetValue <string>("AuthKey")), cs.GetValue <string>("Database"))); }); #endif // Default the page size. PagingArgs.DefaultTake = config.GetValue <int>("BeefDefaultPageSize"); }
public Startup(IConfiguration config) { // Use JSON property names in validation. ValidationArgs.DefaultUseJsonNames = true; // Load the cache policies. CachePolicyManager.SetFromCachePolicyConfig(config.GetSection("BeefCaching").Get <CachePolicyConfig>()); CachePolicyManager.StartFlushTimer(CachePolicyManager.TenMinutes, CachePolicyManager.FiveMinutes); // Register the ReferenceData provider. RefData.ReferenceDataManager.Register(new ReferenceDataProvider()); // Register the database. Database.Register(() => new Database(WebApiStartup.GetConnectionString(config, "BeefDemo"))); // Register the DocumentDb/CosmosDb client. CosmosDb.Register(() => { var cs = config.GetSection("CosmosDb"); return(new CosmosDb(new Cosmos.CosmosClient(cs.GetValue <string>("EndPoint"), cs.GetValue <string>("AuthKey")), cs.GetValue <string>("Database"))); }); // Register the test OData service. TestOData.Register(() => new TestOData(WebApiStartup.GetConnectionString(config, "TestOData"))); // Default the page size. PagingArgs.DefaultTake = config.GetValue <int>("BeefDefaultPageSize"); // Configure the Service Agents from the configuration and register. var sac = config.GetSection("BeefServiceAgents").Get <WebApiServiceAgentConfig>(); sac?.RegisterAll(); }
/// <summary> /// Initializes a new instance of the <see cref="Startup"/> class. /// </summary> /// <param name="config">The <see cref="IConfiguration"/>.</param> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param> public Startup(IConfiguration config, ILoggerFactory loggerFactory) { // Use JSON property names in validation; default the page size and determine whether unhandled exception details are to be included in the response. ValidationArgs.DefaultUseJsonNames = true; PagingArgs.DefaultTake = config.GetValue <int>("BeefDefaultPageSize"); WebApiExceptionHandlerMiddleware.IncludeUnhandledExceptionInResponse = config.GetValue <bool>("BeefIncludeExceptionInInternalServerError"); // Configure the logger. _logger = loggerFactory.CreateLogger("Logging"); Logger.RegisterGlobal((largs) => WebApiStartup.BindLogger(_logger, largs)); // Configure the cache policies. CachePolicyManager.SetFromCachePolicyConfig(config.GetSection("BeefCaching").Get <CachePolicyConfig>()); CachePolicyManager.StartFlushTimer(CachePolicyManager.TenMinutes, CachePolicyManager.FiveMinutes); #if (implement_database || implement_entityframework) // Register the database. Database.Register(() => new Database(WebApiStartup.GetConnectionString(config, "Database"))); #endif #if (implement_cosmos) // Register the DocumentDb/CosmosDb client. CosmosDb.Register(() => { var cs = config.GetSection("CosmosDb"); return(new CosmosDb(new Microsoft.Azure.Cosmos.CosmosClient(cs.GetValue <string>("EndPoint"), cs.GetValue <string>("AuthKey")), cs.GetValue <string>("Database"))); }); #endif // Register the ReferenceData provider. Beef.RefData.ReferenceDataManager.Register(new ReferenceDataProvider()); }
public ICosmosDb Build(IDocumentClient client) { if (string.IsNullOrWhiteSpace(Id)) { throw new InvalidOperationException("Id not specified"); } var documentDb = new CosmosDb(client, Id, _defaultThroughput, _collectionBuilders, _createOnMissing); return(documentDb); }
public static void AddDataDependencies(this IServiceCollection services, CosmosDb configuration) { CosmosClientBuilder clientBuilder = new CosmosClientBuilder($"AccountEndpoint={configuration.Account};AccountKey={configuration.Key};"); var client = clientBuilder.WithConnectionModeDirect().Build(); services.AddSingleton(client); services.AddTransient <IOwnerTwitchCredentialRepository, OwnerTwitchCredentialRepository>(); services.AddTransient <IGitHubCredentialRepository, GitHubCredentialRepository>(); services.AddTransient <ITwitchTeamMemberRepository, TwitchTeamMemberRepository>(); services.AddTransient <ITwitchTeamSettingsRepository, TwitchTeamSettingsRepository>(); services.AddTransient <ISingleStreamerSettingsRepository, SingleStreamerSettingsRepository>(); services.AddTransient <IGuildSettingsRepository, GuildSettingsRepository>(); services.AddTransient <ITranscriberRepository, TranscriberRepository>(); services.AddTransient <IFeaturedChatSettingsRepository, FeaturedChatSettingsRepository>(); }
public Startup(IConfiguration config) { // Use JSON property names in validation. ValidationArgs.DefaultUseJsonNames = true; // Load the cache policies. CachePolicyManager.SetFromCachePolicyConfig(config.GetSection("BeefCaching").Get <CachePolicyConfig>()); CachePolicyManager.StartFlushTimer(CachePolicyManager.TenMinutes, CachePolicyManager.FiveMinutes); // Register the ReferenceData provider. RefData.ReferenceDataManager.Register(new ReferenceDataProvider()); // Register the database. Database.Register(() => new Database(WebApiStartup.GetConnectionString(config, "BeefDemo"))); Beef.Data.Database.DatabaseInvoker.Default = new Beef.Data.Database.SqlRetryDatabaseInvoker(); // Register the DocumentDb/CosmosDb client. CosmosDb.Register(() => { var cs = config.GetSection("CosmosDb"); return(new CosmosDb(new Cosmos.CosmosClient(cs.GetValue <string>("EndPoint"), cs.GetValue <string>("AuthKey")), cs.GetValue <string>("Database"))); }); // Register the test OData services. TestOData.Register(() => new TestOData(new Uri(WebApiStartup.GetConnectionString(config, "TestOData")))); TripOData.Register(() => new TripOData(new Uri(WebApiStartup.GetConnectionString(config, "TripOData")))); // Default the page size. PagingArgs.DefaultTake = config.GetValue <int>("BeefDefaultPageSize"); // Configure the Service Agents from the configuration and register. var sac = config.GetSection("BeefServiceAgents").Get <WebApiServiceAgentConfig>(); sac?.RegisterAll(); // Set up the event publishing to event hubs. if (config.GetValue <bool>("EventHubPublishing")) { var ehc = EventHubClient.CreateFromConnectionString(config.GetValue <string>("EventHubConnectionString")); ehc.RetryPolicy = RetryPolicy.Default; var ehp = new EventHubPublisher(ehc); Event.Register((events) => ehp.Publish(events)); } }
public void Configure(IWebJobsBuilder builder) { var config = builder.GetConfiguration(typeof(Startup).Assembly, environmentVariablesPrefix: "Beef_"); // Load the cache policies. CachePolicyManager.SetFromCachePolicyConfig(config.GetSection("BeefCaching").Get <CachePolicyConfig>()); CachePolicyManager.StartFlushTimer(CachePolicyManager.TenMinutes, CachePolicyManager.FiveMinutes); // Register the ReferenceData provider. RefData.ReferenceDataManager.Register(new ReferenceDataProvider()); // Register the database. Database.Register(() => new Database(config.GetConnectionString("BeefDemo"))); // Register the DocumentDb/CosmosDb client. CosmosDb.Register(() => { var cs = config.GetSection("CosmosDb"); return(new CosmosDb(new Microsoft.Azure.Cosmos.CosmosClient(cs.GetValue <string>("EndPoint"), cs.GetValue <string>("AuthKey")), cs.GetValue <string>("Database"))); }); }
public void OpenCosmos() { var c = new CosmosDb(Config["endPointUrl"], Config["primaryKey"]); var acct = c.GetAccountByName("Test"); var transactions = new List <Transaction>(); transactions.Add(new Transaction() { Amount = 2, Name = "Hello 1", TransDate = new System.DateTime(2020, 02, 20), TransactionId = System.Guid.NewGuid() }); transactions.Add(new Transaction() { Amount = 3, Name = "Hello 2", TransDate = new System.DateTime(2020, 02, 21), TransactionId = System.Guid.NewGuid() }); acct.Transactions = transactions.ToArray(); c.UpsertAccount(acct); foreach (var name in new[] { "Autumn", "Lilly" }) { if (!c.AccountExists(name)) { var acct3 = c.GetAccountByName(name); var transactions3 = new List <Transaction>(); transactions3.Add(new Transaction() { Amount = 0, Name = "Initial", TransDate = DateTime.Today, TransactionId = System.Guid.NewGuid() }); acct3.Transactions = transactions3.ToArray(); c.UpsertAccount(acct3); } } var acct2 = c.GetAccountByName("Test"); Assert.AreEqual(acct2.Transactions.Length, acct.Transactions.Length); Assert.AreEqual(acct2.Balance(), 5); }
public async Task OneTimeSetUp() { TestSetUp.Reset(false); var config = AgentTester.Configuration.GetSection("CosmosDb"); _removeAfterUse = config.GetValue <bool>("RemoveAfterUse"); _cosmosDb = new CosmosDb(new Cosmos.CosmosClient(config.GetValue <string>("EndPoint"), config.GetValue <string>("AuthKey")), config.GetValue <string>("Database"), createDatabaseIfNotExists: true); var rc = await _cosmosDb.ReplaceOrCreateContainerAsync( new Cosmos.ContainerProperties { Id = "Items", PartitionKeyPath = "/_partitionKey", UniqueKeyPolicy = new Cosmos.UniqueKeyPolicy { UniqueKeys = { new Cosmos.UniqueKey { Paths = { "/serialNo"} } } } }, 400); await rc.ImportBatchAsync <RobotTest, Robot>("Data.yaml", "Robot"); var rdc = await _cosmosDb.ReplaceOrCreateContainerAsync( new Cosmos.ContainerProperties { Id = "RefData", PartitionKeyPath = "/_partitionKey", UniqueKeyPolicy = new Cosmos.UniqueKeyPolicy { UniqueKeys = { new Cosmos.UniqueKey { Paths = { "/type","/value/code" } } } } }, 400); await rdc.ImportValueRefDataBatchAsync <RobotTest>(ReferenceData.Current, "RefData.yaml"); }
public void OneTimeSetUp() { TestSetUp.RegisterSetUp(async(count, data) => { var config = AgentTester.Configuration.GetSection("CosmosDb"); _removeAfterUse = config.GetValue <bool>("RemoveAfterUse"); _cosmosDb = new CosmosDb(new Cosmos.CosmosClient(config.GetValue <string>("EndPoint"), config.GetValue <string>("AuthKey")), config.GetValue <string>("Database"), createDatabaseIfNotExists: true); var rc = await _cosmosDb.ReplaceOrCreateContainerAsync( new Cosmos.ContainerProperties { Id = "Person", PartitionKeyPath = "/_partitionKey" }, 400); await rc.ImportBatchAsync <PersonTest, Person>("Person.yaml", "Person"); var rdc = await _cosmosDb.ReplaceOrCreateContainerAsync( new Cosmos.ContainerProperties { Id = "RefData", PartitionKeyPath = "/_partitionKey", UniqueKeyPolicy = new Cosmos.UniqueKeyPolicy { UniqueKeys = { new Cosmos.UniqueKey { Paths = { "/type","/value/code" } } } } }, 400); await rdc.ImportValueRefDataBatchAsync <PersonTest>(ReferenceData.Current, "RefData.yaml"); return(true); }); AgentTester.StartupTestServer <Startup>(environmentVariablesPrefix: "AppName_"); AgentTester.DefaultExpectNoEvents = true; }
public IndexModel(CosmosDb db) { this.Db = db; }
private static async Task RunEtl(MigrateOptions options) { Guard.ArgumentNotNull(options, "You must supply \"migrate\" settings to migrate a specification between two environments"); CosmosDb sourceCosmosDb = new CosmosDb(options.SourceAccountKey, options.SourceAccountEndpoint, options.SourceDatabase ); CosmosDb destCosmosDb = new CosmosDb(options.TargetAccountKey, options.TargetAccountEndpoint, options.TargetDatabase ); List <Container> containers = new List <Container>(); containers.Add(new Container { Name = "publishedfunding", Query = "SELECT * FROM c WHERE c.content.current.specificationId = '{0}' OR c.content.specificationId = '{0}'", MaxThroughPut = options.MaxThroughPut, PartitionKey = "/content/partitionKey", HasPost = true }); containers.Add(new Container { Name = "specs", Query = "SELECT * FROM c WHERE c.content.current.specificationId = '{0}' OR c.content.specificationId = '{0}'", HasPreReqs = true, MaxThroughPut = options.MaxThroughPut, HasPost = true }); containers.Add(new Container { Name = "datasets", Query = "SELECT * FROM c WHERE c.content.Specification.id = '{0}'", HasPreReqs = true, MaxThroughPut = options.MaxThroughPut, HasPost = true }); containers.Add(new Container { Name = "calculationresults", Query = "SELECT * FROM c WHERE c.content.specificationId = '{0}'", MaxThroughPut = options.MaxThroughPut, PartitionKey = "/content/provider/id", HasPost = true }); containers.Add(new Container { Name = "calcs", Query = "SELECT * FROM c WHERE c.content.specificationId = '{0}'", MaxThroughPut = options.MaxThroughPut, HasPost = true }); containers.Add(new Container { Name = "providerdatasets", Query = "SELECT * FROM c WHERE c.content.specificationId = '{0}'", MaxThroughPut = options.MaxThroughPut, PartitionKey = "/content/providerId" }); List <(BlobContainer sourceContainer, BlobContainer destinationContainer)> blobs = new List <(BlobContainer sourceContainer, BlobContainer destinationContainer)>(); blobs.Add((new BlobContainer { Name = "source", AccountName = options.SourceStorageAccountName, AccountKey = options.SourceStorageAccountKey, Blobs = new string[] { $"{options.SourceSpecificationId}/{options.SourceSpecificationId}-preview.zip", $"{options.SourceSpecificationId}/{options.SourceSpecificationId}-release.zip", $"{options.SourceSpecificationId}/implementation.dll" } }, new BlobContainer { Name = "source", AccountName = options.TargetStorageAccountName, AccountKey = options.TargetStorageAccountKey })); blobs.Add((new BlobContainer { Name = "datasets", AccountName = options.SourceStorageAccountName, AccountKey = options.SourceStorageAccountKey }, new BlobContainer { Name = "datasets", AccountName = options.TargetStorageAccountName, AccountKey = options.TargetStorageAccountKey })); SpecificationMigration specificationMigration = new SpecificationMigration( sourceCosmosDb, destCosmosDb, containers, blobs, new Search(options.SearchKey, options.SearchName), "specs", @"SELECT * FROM c WHERE c.documentType = 'Specification' AND c.id = @specificationId" ); await specificationMigration.Run(options.SourceSpecificationId, options.UnpublishSpecificationId); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddMemoryCache(); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { //c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); c.SwaggerDoc("v1", new Info { Version = "beta", Title = "a2klab", Description = "Microservicios de desarrollo: Kestrel, Core 2.1, Swagger, Source: <a href='https://github.com/unarix/a2klab'>Github</a>", // Contact = new Contact // { // Name = "ntello", // Email = "*****@*****.**", // } }); var xmlFile = Assembly.GetExecutingAssembly().GetName().Name + ".xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); // ******************** // Setup CORS // ******************** var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); // corsBuilder.WithOrigins("https://rodocop.azurewebsites.net", // "https://localhost:5001", // "https://localhost:5002", // "https://localhost:5003", // "https://localhost:5004" // ); // Para una URL especifica. no agregar / al finals! corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); }); AppSettings conf = new AppSettings(); CosmosDb cosmo = new CosmosDb(); cosmo.Account = Configuration["Account"]; cosmo.ContainerName = Configuration["ContainerName"]; cosmo.DatabaseName = Configuration["DatabaseName"]; cosmo.Key = Configuration["Key"]; conf.CosmosDb = cosmo; //tratar de hacer el Singleton a la DB Cosmos try{ services.AddSingleton <ICosmosDBService>(InitializeCosmosClientInstanceAsync(conf).GetAwaiter().GetResult()); services.AddSingleton <IUsersDBService>(InitializeUsersClientInstanceAsync(conf).GetAwaiter().GetResult()); } catch (Exception ex) { // Nothing to do here. } }
public static async Task Initialize(TestContext context) { await CosmosDb.Initialize(); }
public RequestXmlController(CosmosDb cosmosDb) : base(cosmosDb) { }
public TransactionsModel(CosmosDb db) { this.Db = db; }
public RequestController(CosmosDb cosmosDb) { service = new RequestService(cosmosDb); }
public RequestService(CosmosDb cosmosDb) //: base(cosmosDb) { }
private static async Task <CosmosDBService> InitializeCosmosClientInstanceAsync(CosmosDb settings) { databaseName = settings.DatabaseName; containerName = settings.ContainerName; account = settings.Account; key = settings.Key; CosmosClient client = new CosmosClient(account, key); CosmosDBService cosmosDBService = new CosmosDBService(client, databaseName, containerName); DatabaseResponse database = await client.CreateDatabaseIfNotExistsAsync(databaseName); await database.Database.CreateContainerIfNotExistsAsync(containerName, "/__partitionKey"); return(cosmosDBService); }