public DependencyUpdaterTests() { var services = new ServiceCollection(); StateManager = new MockReliableStateManager(); SubscriptionActor = new Mock <ISubscriptionActor>(MockBehavior.Strict); Env = new Mock <IHostingEnvironment>(MockBehavior.Strict); services.AddSingleton(Env.Object); services.AddSingleton <IReliableStateManager>(StateManager); services.AddLogging(); services.AddDbContext <BuildAssetRegistryContext>( options => { options.UseInMemoryDatabase("BuildAssetRegistry"); }); services.AddSingleton <Func <ActorId, ISubscriptionActor> >( id => { ActorId = id; return(SubscriptionActor.Object); }); Provider = services.BuildServiceProvider(); Scope = Provider.CreateScope(); _context = new Lazy <BuildAssetRegistryContext>(GetContext); }
public void When_Custom_Json_Handler_Is_Registered_Exception_Should_Not_Be_Thrown() { ServiceCollection services = new ServiceCollectionBuilder().PrepareServiceCollection(s => { s.ResetDapperCustomTypeHandlers(); s.RegisterDapperCustomTypeHandlers(Assembly.GetExecutingAssembly()); }); ServiceProvider serviceProvider = services.BuildServiceProvider(); using (IServiceScope scope = serviceProvider.CreateScope()) { var scopedServices = scope.ServiceProvider; ITestObjectRepository testObjectRepository = scopedServices.GetRequiredService <ITestObjectRepository>(); TestJsonObject testObject = CreateTestJsonObject(); // Assert Assert.DoesNotThrowAsync(async() => await testObjectRepository.SaveTestJsonObject(testObject)); } }
Task IAsyncLifetime.InitializeAsync() { var contentTypeResolver = new Infrastructure.AssemblyContentTypeLocator(new System.Reflection.Assembly[] { typeof(TestPageContent).Assembly }); var services = new ServiceCollection(); services.AddSingleton <IContentMetadataManager, ContentMetadataManager>(); services.AddSingleton <Infrastructure.IContentTypeLocator>(contentTypeResolver); serviceProvider = services.BuildServiceProvider(); serviceScope = serviceProvider.CreateScope(); metadataManager = serviceScope.ServiceProvider.GetRequiredService <IContentMetadataManager>(); var metadataProvider = metadataManager.GetMetadata <TestContent>(); if (!metadataProvider.TryGetField("Html", out field)) { throw new System.Exception(); } return(Task.CompletedTask); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureServices(services => { _provider = services.BuildServiceProvider(); services.AddMvc(options => { options.Filters.Remove(new AutoValidateAntiforgeryTokenAttribute()); }); using var scope = _provider.CreateScope(); var scopedServices = scope.ServiceProvider; var context = scopedServices.GetRequiredService <DiveContext>(); context.Database.EnsureDeleted(); context.Database.EnsureCreated(); TestContextUtilities.InitializeDatabase(context); }); base.ConfigureWebHost(builder); }
protected WorkflowsUnitTestBase(ITestOutputHelper testOutputHelper, Action <IServiceCollection>?configureServices = default) { _tempFolder = new TemporaryFolder(); TestOutputHelper = testOutputHelper; var services = new ServiceCollection() .AddElsa(options => options .AddConsoleActivities(Console.In, new XunitConsoleForwarder(testOutputHelper))); configureServices?.Invoke(services); ServiceProvider = services.BuildServiceProvider(); ServiceScope = ServiceProvider.CreateScope(); WorkflowRunner = ServiceScope.ServiceProvider.GetRequiredService <IWorkflowRunner>(); WorkflowBuilderAndStarter = ServiceScope.ServiceProvider.GetRequiredService <IBuildsAndStartsWorkflow>(); WorkflowStarter = ServiceScope.ServiceProvider.GetRequiredService <IStartsWorkflow>(); WorkflowResumer = ServiceScope.ServiceProvider.GetRequiredService <IResumesWorkflow>(); WorkflowBlueprintMaterializer = ServiceScope.ServiceProvider.GetRequiredService <IWorkflowBlueprintMaterializer>(); WorkflowBuilder = ServiceScope.ServiceProvider.GetRequiredService <IWorkflowBuilder>(); WorkflowRegistry = ServiceScope.ServiceProvider.GetRequiredService <IWorkflowRegistry>(); BookmarkFinder = ServiceScope.ServiceProvider.GetRequiredService <IBookmarkFinder>(); WorkflowExecutionLog = ServiceScope.ServiceProvider.GetRequiredService <IWorkflowExecutionLog>(); WorkflowStorageService = ServiceScope.ServiceProvider.GetRequiredService <IWorkflowStorageService>(); }
private void RemoveFeeds(object interval) { if (!Monitor.TryEnter(removeLock)) { return; } try { using var scope = ServiceProvider.CreateScope(); var feedAggregateDataProvider = scope.ServiceProvider.GetService <FeedAggregateDataProvider>(); Log.DebugFormat("Start of removing old news"); feedAggregateDataProvider.RemoveFeedAggregate(DateTime.UtcNow.Subtract((TimeSpan)interval)); } catch (Exception ex) { Log.Error(ex); } finally { Monitor.Exit(removeLock); } }
protected virtual IList <SettingNavigation> CreateSettingNavigations() { var navigations = new List <SettingNavigation>(); using (var scope = ServiceProvider.CreateScope()) { var providers = DigniteSettingOptions .DigniteDefinitionProviders .Select(p => scope.ServiceProvider.GetRequiredService(p) as IDigniteSettingDefinitionProvider) .ToList(); foreach (var provider in providers) { var settings = new Dictionary <string, Volo.Abp.Settings.SettingDefinition>(); var context = new DigniteSettingDefinitionContext(settings); provider.Define(context); context.Navigation.AddSettingDefinitions(settings); navigations.Add(context.Navigation); } } return(navigations); }
//Show difference between registrations //Show difference between async/sync main private static void Main(string[] args) { IConfigurationRoot configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .AddCommandLine(args) .Build(); IServiceCollection spBuilder = new ServiceCollection() .AddLogging(loggingBuilder => loggingBuilder.AddConsole().AddConfiguration(configuration)) .AddScoped <DIUserClass>() .AddScoped <ITestService, TestService>() //Using ImplementationFactory method .AddSingleton <IConfiguration>(sp => new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .AddCommandLine(args) .Build()); ServiceProvider serviceProvider = spBuilder.BuildServiceProvider(); Console.WriteLine("You now have access to a complete IServiceProvider (IOC) through variable serviceProvider"); using IServiceScope scope = serviceProvider.CreateScope(); scope.ServiceProvider .GetRequiredService <DIUserClass>() .ExecuteAsync() .GetAwaiter(); //Need to dispose the ServiceProvider to let the ILogger flush its content before main thread exits. //But since we are using 'using' it will be handled automatically //Try doing the same without using and the logger will not be able to finish its flush in proper time }
/// <summary> /// Вызвать метод рабочего класса. /// <para></para> /// Данный метод не возвращает исключений. Его нужно испльзовать как внешюю точку доступа. /// </summary> /// <param name="requestModel"></param> /// <returns></returns> public CallOpenApiWorkerMethodResponse CallWorkerMethod(CallOpenApiWorkerMethod requestModel) { if (requestModel == null) { return(new CallOpenApiWorkerMethodResponse { IsSucceeded = false, ExcepionData = ExcepionData.Create(new Exception("request is null onjcet")) }); } var parameters = new JsWorkerMethodCallParametersFromSerialized(requestModel.SerializedParameters); try { var jsContext = GetContext(); using var scope = ServiceProvider.CreateScope(); var result = Components .GetJsWorker(requestModel.WorkerName, jsContext) .HandleCall(requestModel.MethodName, scope.ServiceProvider, parameters, jsContext, Logger); return(new CallOpenApiWorkerMethodResponse { IsSucceeded = true, ResponseJson = ZooSerializer.Serialize(result.Result) }); } catch (Exception ex) { Logger.LogError(ex, "CallWorkerMethod.Error"); return(new CallOpenApiWorkerMethodResponse { IsSucceeded = false, ExcepionData = ExcepionData.Create(ex) }); } }
/// <summary>Handles Lambda Function invocations.</summary> /// <param name="input">The input to the Function.</param> /// <param name="context">The context of this execution of the Function.</param> /// <returns> /// A task which, when resolved, results in the output from the Function. /// </returns> /// <exception cref="InvalidOperationException">The handler is misconfigured.</exception> /// <exception cref="ArgumentNullException"><paramref name="context"/> is <see langword="null"/>.</exception> public async Task <TOut> HandleAsync(TIn input, ILambdaContext context) { if (context is null) { throw new ArgumentNullException(nameof(context)); } using var scope = ServiceProvider.CreateScope(); var logger = scope.ServiceProvider.GetLogger(GetType()); using var handlingScope = logger?.Handling(context); using var cts = new CancellationTokenSource(context.RemainingTime - CancellationLeadTime); await using var warningRegistration = cts.Token.RegisterWarning(logger); await using var @finally = warningRegistration.ConfigureAwait(false); try { return(await HandleCoreAsync( input, context, scope.ServiceProvider, cts.Token).ConfigureAwait(false)); } catch (TaskCanceledException tce) when(tce.CancellationToken == cts.Token) { // note(cosborn) Other timeouts can go into the catch-all handler. _ = warningRegistration.Unregister(); logger?.Canceled(tce); throw; } catch (Exception e) { // note(cosborn) Log a nice message if we can. logger?.UnhandledException(GetType(), e); throw; } }
public void SetUp() { if (!HostUtilities.TryGetJetCatalogType(out var jetCatalogType)) { Assert.Ignore("ADOX.Catalog could not be found - running from .NET Core?"); } _tempDataDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); Directory.CreateDirectory(_tempDataDirectory); AppDomain.CurrentDomain.SetData("DataDirectory", _tempDataDirectory); var csb = new OleDbConnectionStringBuilder(IntegrationTestOptions.Jet.ConnectionString); csb.DataSource = DatabaseFilename = HostUtilities.ReplaceDataDirectory(csb.DataSource); try { RecreateDatabase(jetCatalogType, csb.ConnectionString); } catch (Exception ex) { try { Directory.Delete(_tempDataDirectory); } catch { // Ignore errors } TestContext.Error.WriteLine(ex.ToString()); Assert.Ignore(ex.Message); } ServiceScope = ServiceProvider.CreateScope(); Processor = ServiceScope.ServiceProvider.GetRequiredService <JetProcessor>(); }
public async Task Using_XmlCustomSettings_Xml_Data_Saved_In_DataBase_Should_Be_Properly_Restored1() { ServiceCollection services = new ServiceCollectionBuilder().PrepareServiceCollection(s => { s.ResetDapperCustomTypeHandlers(); s.RegisterDapperCustomTypeHandlers(Assembly.GetExecutingAssembly(), options => { options.XmlWriterSettings = new XmlWriterSettings { Indent = false, OmitXmlDeclaration = false }; }); }); ServiceProvider serviceProvider = services.BuildServiceProvider(); using (IServiceScope scope = serviceProvider.CreateScope()) { var scopedServices = scope.ServiceProvider; ITestObjectRepository testObjectRepository = scopedServices.GetRequiredService <ITestObjectRepository>(); TestXmlObject testObject = CreateFullTestObject(); // Act await testObjectRepository.SaveTestXmlObject(testObject); TestXmlObject retrievedTestObject = await testObjectRepository.GetTestXmlObject(testObject.Id); // Assert retrievedTestObject.Should().NotBeNull(); retrievedTestObject.Should().BeEquivalentTo(testObject); retrievedTestObject.Content.Should().BeEquivalentTo(testObject.Content); } }
private static int Main(string[] args) { if (args.Length != 3) { Console.WriteLine("Invalid number of arguments"); return(1); } RegisterServices(); var scope = _serviceProvider.CreateScope(); var app = scope.ServiceProvider.GetRequiredService <App>(); try { switch (args[0]?.ToLower()) { case "compress": app.Compress(args[1], args[2]); break; case "decompress": app.Decompress(args[1], args[2]); break; default: Console.WriteLine("Invalid command"); return(1); } } catch { return(1); } DisposeServices(); return(0); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureServices(services => { ServiceProvider serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); services.AddDbContext <ApplicationDbContext>(optionsAction => { optionsAction.UseInMemoryDatabase(nameof(ApplicationDbContext)); optionsAction.UseInternalServiceProvider(serviceProvider); }); services.AddAntiforgery(setupAction => { setupAction.Cookie.Name = AntiForgeryTokenExtractor.AntiForgeryCookieName; setupAction.FormFieldName = AntiForgeryTokenExtractor.AntiForgeryFieldName; }); ServiceProvider sp = services.BuildServiceProvider(); using var scope = sp.CreateScope(); using (var appContext = scope.ServiceProvider.GetRequiredService <EmployeeContext>()) { try { appContext.Database.EnsureCreated(); } catch (Exception ex) { //Log errors or do anything you think it's needed throw; } } }); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureServices(services => { ServiceProvider serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); services.AddDbContext <ApplicationDbContext>(optionsAction => { optionsAction.UseInMemoryDatabase(nameof(ApplicationDbContext)); optionsAction.UseInternalServiceProvider(serviceProvider); }); services.AddDefaultIdentity <IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false) .AddEntityFrameworkStores <ApplicationDbContext>(); services.AddAntiforgery(setupAction => { setupAction.Cookie.Name = AntiForgeryTokenExtractor.AntiForgeryCookieName; setupAction.FormFieldName = AntiForgeryTokenExtractor.AntiForgeryFieldName; }); ServiceProvider sp = services.BuildServiceProvider(); using IServiceScope scope = sp.CreateScope(); using ApplicationDbContext appContext = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>(); try { appContext.Database.EnsureCreated(); } catch (Exception ex) { throw new Exception(ex.Message); } }); }
protected override async Task HandleMessage(string content) { try { var post = Reddit.parsePost(content); var urlMethodType = Reddit.isKnown(post); if (urlMethodType == Reddit.UrlMethodType.Unknown) { return; } using var scope = ServiceProvider.CreateScope(); var image = scope.ServiceProvider.GetRequiredService <Image.Image>(); var downloader = scope.ServiceProvider.GetRequiredService <IDownloader>(); var createImage = Reddit.getPayload(post); var download = Reddit.getDownloadPost(post); await image.createImageIfNotExistsAsync(createImage); if (urlMethodType == Reddit.UrlMethodType.Http) { await downloader.downloadHttp(download); } else { await downloader.downloadProcess(download); } } catch (Exception e) { //TODO: REMOVE THIS IN THE FUTURE //I'll leave this for now to get which payloads are throwing errors _logger.LogError(e, content); } }
public async Task Invoice_created_event_handler_should_be_called_the_same_number_of_times_as_added_invoices(int count) { // Arrange ServiceCollection services = TestHelper.PrepareServiceCollection(); services.AddSingleton <Counter>(); // Replace the registered event class ServiceDescriptor serviceDescriptor = services.FirstOrDefault(d => d.ServiceType == typeof(INotificationHandler <InvoiceCreatedEvent>)); services.Remove(serviceDescriptor); services.AddScoped <INotificationHandler <InvoiceCreatedEvent>, FakeInvoiceCreatedEventHandler>(); ServiceProvider serviceProvider = services.BuildServiceProvider(); using (IServiceScope scope = serviceProvider.CreateScope()) { var scopedServices = scope.ServiceProvider; IMessageManager messageManager = scopedServices.GetRequiredService <IMessageManager>(); // empty repository var invoiceRepository = scopedServices.GetRequiredService <IInvoiceRepository>(); Counter counter = scopedServices.GetRequiredService <Counter>(); // Act for (int i = 0; i < count; i++) { CreateInvoiceCommandResponse createInvoiceResponse = await messageManager.SendCommand( new CreateInvoiceCommand(new Invoice(id: Guid.NewGuid(), number: "J/01/2019", creationDate: DateTime.Now))); } // Assert counter.Get().Should().Be(count); } }
public async Task <int> Migrate(Argument @event) { if (@event?.Name == null) { return(0); } LambdaLogger.Log($"Migrate called with argument {@event.Name} and index {@event.Index}"); using (var scope = _serviceProvider.CreateScope()) { try { var ret = await scope.ServiceProvider.GetRequiredService <IArgumentProcessor>().Process(@event); LambdaLogger.Log($"Return {ret} when migrate called with argument {@event.Name} and index {@event.Index}."); return(ret); } catch (Exception ex) { LambdaLogger.Log($"Exception occurred for {@event.Name} with index {@event.Index} of : {ex}"); throw; } } }
public virtual void IterationSetup() { _requestScope = _serviceProvider.CreateScope(); _viewEngineResult = _viewEngine.GetView(null, ViewPath, true); _viewEngineResult.EnsureSuccessful(null); _actionContext = new ActionContext( new DefaultHttpContext() { RequestServices = _requestScope.ServiceProvider }, _routeData, _actionDescriptor); _tempData = _tempDataDictionaryFactory.GetTempData(_actionContext.HttpContext); _viewDataDictionary = new ViewDataDictionary( _requestScope.ServiceProvider.GetRequiredService <IModelMetadataProvider>(), _actionContext.ModelState); _viewDataDictionary.Model = Model; _executor = _requestScope.ServiceProvider.GetRequiredService <BenchmarkViewExecutor>(); }
private void Clear() { while (true) { try { var date = DateTime.UtcNow.AddDays(-NotifyServiceCfg.StoreMessagesDays); using var scope = ServiceProvider.CreateScope(); using var dbContext = scope.ServiceProvider.GetService <DbContextManager <NotifyDbContext> >().Get(NotifyServiceCfg.ConnectionStringName); using var tx = dbContext.Database.BeginTransaction(); var info = dbContext.NotifyInfo.Where(r => r.ModifyDate < date && r.State == 4).ToList(); var queue = dbContext.NotifyQueue.Where(r => r.CreationDate < date).ToList(); dbContext.NotifyInfo.RemoveRange(info); dbContext.NotifyQueue.RemoveRange(queue); dbContext.SaveChanges(); tx.Commit(); log.InfoFormat("Clear notify messages: notify_info({0}), notify_queue ({1})", info.Count, queue.Count); } catch (ThreadAbortException) { // ignore } catch (Exception err) { log.Error(err); } if (stop.WaitOne(TimeSpan.FromHours(8))) { break; } } }
public async Task All_created_invoices_should_be_able_to_get_by_passing_their_id(int count) { ServiceProvider serviceProvider = TestHelper.PrepareServiceProvider(); using (IServiceScope scope = serviceProvider.CreateScope()) { var scopedServices = scope.ServiceProvider; IMessageManager messageManager = scopedServices.GetRequiredService <IMessageManager>(); // Arrange // empty repository var invoiceRepository = scopedServices.GetRequiredService <IInvoiceRepository>(); List <CreateInvoiceCommandResponse> createInvoiceResponses = new List <CreateInvoiceCommandResponse>(); // Act for (int i = 0; i < count; i++) { CreateInvoiceCommandResponse createInvoiceResponse = await messageManager.SendCommand( new CreateInvoiceCommand(new Invoice(id: Guid.NewGuid(), number: "JK/02/2019", creationDate: DateTime.Now))); createInvoiceResponses.Add(createInvoiceResponse); } // Assert foreach (var createdInvoice in createInvoiceResponses) { GetInvoiceQueryResponse queryResponse = await messageManager.SendCommand(new GetInvoiceQuery(createdInvoice.Id)); queryResponse.Invoice.Should().NotBeNull(); queryResponse.Invoice.Id.ToString().Should().BeEquivalentTo(createdInvoice.Id.ToString()); } } }
public async Task Null_Json_Data_Saved_In_DataBase_Should_Be_Restored_As_Null_Object() { ServiceCollection services = new ServiceCollectionBuilder().PrepareServiceCollection(s => { s.ResetDapperCustomTypeHandlers(); s.RegisterDapperCustomTypeHandlers(Assembly.GetExecutingAssembly()); }); ServiceProvider serviceProvider = services.BuildServiceProvider(); using (IServiceScope scope = serviceProvider.CreateScope()) { var scopedServices = scope.ServiceProvider; ITestObjectRepository testObjectRepository = scopedServices.GetRequiredService <ITestObjectRepository>(); TestJsonObject testObject = new TestJsonObject { FirstName = "John", LastName = "Doe", StartWork = new DateTime(2018, 06, 01), Content = null }; // Act await testObjectRepository.SaveTestJsonObject(testObject); TestJsonObject retrievedTestObject = await testObjectRepository.GetTestJsonObject(testObject.Id); // Assert retrievedTestObject.Should().NotBeNull(); retrievedTestObject.Should().BeEquivalentTo(testObject); retrievedTestObject.Content.Should().BeEquivalentTo(testObject.Content); } }
private static void SetupDatabase(IServiceCollection services) { ServiceProvider serviceProvider = services.BuildServiceProvider(); using IServiceScope serviceScope = serviceProvider.CreateScope(); TodoDbContext todoDbContext = serviceScope.ServiceProvider.GetRequiredService <TodoDbContext>(); ILogger logger = serviceProvider.GetRequiredService <ILogger <TestWebApplicationFactory> >(); string databaseName = todoDbContext.Database.GetDbConnection().Database; logger.LogInformation("About to setup test database {TestDatabaseName} ...", databaseName); try { RunMigrations(databaseName, todoDbContext, logger); } catch (Exception exception) { logger.LogError("Failed to run migrations against test database {TestDatabaseName}", exception, databaseName); throw; } logger.LogInformation("Test database {TestDatabaseName} has been successfully setup", databaseName); }
private async Task <TrackerJobResult> RemoveUserStoresAsync(string userId) { var serviceScope = ServiceProvider.CreateScope(); var data = serviceScope.ServiceProvider.GetRequiredService <TokyoDbContext>(); var statusMessages = new List <string>(); var userStore = await data.TrackerStores.SingleOrDefaultAsync(t => t.TrackerStoreId == userId); if (userStore != null) { data.TrackerStores.Remove(userStore); await data.SaveChangesAsync(); statusMessages.Add($"Deleted {userStore.TrackerStoreId}"); // TODO check null ref } else { Logger.LogWarning($"User store of user {userId} could not be found."); } serviceScope.Dispose(); return(new TrackerJobResult() { Success = true, StatusMessage = $"{string.Join(", ", statusMessages)}.", Name = Name }); }
private StringLocalizerCacheItem CreateStringLocalizerCacheItem(LocalizationResource resource) { foreach (var globalContributor in AbpLocalizationOptions.GlobalContributors) { resource.Contributors.Add((ILocalizationResourceContributor)Activator.CreateInstance(globalContributor)); } using (var scope = ServiceProvider.CreateScope()) { var context = new LocalizationResourceInitializationContext(resource, scope.ServiceProvider); foreach (var contributor in resource.Contributors) { contributor.Initialize(context); } } return(new StringLocalizerCacheItem( new AbpDictionaryBasedStringLocalizer( resource, resource.BaseResourceTypes.Select(Create).ToList() ) )); }
public SqlServerMigrationsFixture() : base() { var services = new ServiceCollection() .AddFluentMigratorCore() .ConfigureRunner(run => run.AddSqlServer2016() .WithGlobalCommandTimeout(TimeSpan.FromMilliseconds(10000))) .AddScoped <IDbConnection>(sp => GetContext().Database.GetDbConnection()) .AddScoped <SqlServerTestingProcessor>() .AddScoped <IMigrationProcessor>(sp => sp.GetRequiredService <SqlServerTestingProcessor>()) .Configure <FluentMigratorLoggerOptions>(cfg => { cfg.ShowElapsedTime = true; cfg.ShowSql = true; }) .Configure <SelectingProcessorAccessorOptions>(cfg => { cfg.ProcessorId = "SqlServer-Test"; }); _serviceProvider = services.BuildServiceProvider(); _scope = _serviceProvider.CreateScope(); var runner = _scope.ServiceProvider.GetRequiredService <IMigrationRunner>(); runner.Up(Activator.CreateInstance <TMigration>()); }
public override async Task <Stream> GetOrNullAsync(string name, CancellationToken cancellationToken = default) { var blobInfoStoreType = Configuration.GetConfigurationOrDefault( DigniteAbpBlobContainerConfigurationNames.BlobInfoStore, typeof(NullBlobInfoStore) ); using (var scope = ServiceProvider.CreateScope()) { var blobInfoStore = scope.ServiceProvider .GetRequiredService(blobInfoStoreType) .As <IBlobInfoStore>(); var blobInfo = await blobInfoStore.FindAsync(ContainerName, name, cancellationToken); // authorization handlers await CheckDeletingPermissionAsync(blobInfo); // if (blobInfo != null) { if (!blobInfo.ReferBlobName.IsNullOrEmpty()) { return(await base.GetOrNullAsync(blobInfo.ReferBlobName, cancellationToken)); } else { return(await base.GetOrNullAsync(name, cancellationToken)); } } else { return(await base.GetOrNullAsync(name, cancellationToken)); } } }
static IEnumerable <Task> GetTasks(ServiceProvider serviceProvider, CancellationToken token) { foreach (var iter in Enumerable.Range(0, 1000)) { using (var scope = serviceProvider.CreateScope()) { var service = scope.ServiceProvider.GetRequiredService <IStorageServiceClient>(); yield return(service .CreateGroup("client" + iter, CancellationToken.None) .ContinueWith(t => { var response = t.Result; if (response.IsSuccessStatusCode) { Console.WriteLine($"date time: {DateTime.Now}, status code: {response.StatusCode}, response text: {response.Content}"); } else { Console.WriteLine($"date time: {DateTime.Now}, status code: {response.StatusCode}, error: {response.Error?.Content}"); } })); } } }
public void RegisterSendMethod() { var cron = Configuration["core:notify:cron"] ?? "0 0 5 ? * *"; // 5am every day using var scope = ServiceProvider.CreateScope(); var scopeClass = scope.ServiceProvider.GetService <StudioNotifyServiceSenderScope>(); var(_, _, _, _, tenantExtra, coreBaseSettings) = scopeClass; if (Configuration["core:notify:tariff"] != "false") { if (tenantExtra.Enterprise) { WorkContext.RegisterSendMethod(SendEnterpriseTariffLetters, cron); } else if (tenantExtra.Opensource) { WorkContext.RegisterSendMethod(SendOpensourceTariffLetters, cron); } else if (tenantExtra.Saas) { if (coreBaseSettings.Personal) { WorkContext.RegisterSendMethod(SendLettersPersonal, cron); } else { WorkContext.RegisterSendMethod(SendSaasTariffLetters, cron); } } } if (!coreBaseSettings.Personal) { WorkContext.RegisterSendMethod(SendMsgWhatsNew, "0 0 * ? * *"); // every hour } }
/// <summary> /// Executes a given action, asynchronously, within scoped request pipeline. /// I.E. the action is executed as if it were an incoming external request, /// except that the request is self-authenticated (see <see cref="IAuthorizationService.OnAuthenticatedAsync(ISelfUser)"/>). /// </summary> /// <param name="action">The action to be executed.</param> /// <returns>A <see cref="Task"/> that will complete when the operation has completed.</returns> internal protected async Task SelfExecuteRequest(Func <IServiceProvider, Task> action) { if (action == null) { throw new ArgumentNullException(nameof(action)); } using (var serviceScope = ServiceProvider.CreateScope()) { await serviceScope.ServiceProvider.GetRequiredService <IAuthorizationService>() .OnAuthenticatedAsync(serviceScope.ServiceProvider.GetRequiredService <IDiscordClient>() .CurrentUser); try { await action.Invoke(serviceScope.ServiceProvider); } catch (Exception ex) { Log.Error(ex, $"An error occurred executing {action.Method.Name} upon {action.Target.GetType().FullName}"); throw; } } }