public async Task <ICollection <Core.Entities.Organization> > SearchAsync(string name, string userEmail, bool?paid, int skip, int take) { using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var organizations = await GetDbSet(dbContext) .Where(e => name == null || e.Name.Contains(name)) .Where(e => userEmail == null || e.OrganizationUsers.Any(u => u.Email == userEmail)) .Where(e => paid == null || (paid == true && !string.IsNullOrWhiteSpace(e.GatewaySubscriptionId)) || (paid == false && e.GatewaySubscriptionId == null)) .OrderBy(e => e.CreationDate) .Skip(skip).Take(take) .ToListAsync(); return(Mapper.Map <List <Core.Entities.Organization> >(organizations)); } }
public async Task <ICollection <DataModel.OrganizationAbility> > GetManyAbilitiesAsync() { using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); return(await GetDbSet(dbContext) .Select(e => new DataModel.OrganizationAbility { Enabled = e.Enabled, Id = e.Id, Use2fa = e.Use2fa, UseEvents = e.UseEvents, UsersGetPremium = e.UsersGetPremium, Using2fa = e.Use2fa && e.TwoFactorProviders != null, UseSso = e.UseSso, UseKeyConnector = e.UseKeyConnector, }).ToListAsync()); } }
public async Task <Tuple <Collection, ICollection <SelectionReadOnly> > > GetByIdWithGroupsAsync(Guid id) { var collection = await base.GetByIdAsync(id); using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var collectionGroups = await(from cg in dbContext.CollectionGroups where cg.CollectionId == id select cg).ToListAsync(); var selectionReadOnlys = collectionGroups.Select(cg => new SelectionReadOnly { Id = cg.GroupId, ReadOnly = cg.ReadOnly, HidePasswords = cg.HidePasswords, }).ToList(); return(new Tuple <Collection, ICollection <SelectionReadOnly> >(collection, selectionReadOnlys)); } }
public async Task UpdateUserKeysAndCiphersAsync(User user, IEnumerable <Cipher> ciphers, IEnumerable <Folder> folders, IEnumerable <Send> sends) { using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); await UserUpdateKeys(user); var cipherEntities = Mapper.Map <List <EfModel.Cipher> >(ciphers); await dbContext.BulkCopyAsync(base.DefaultBulkCopyOptions, cipherEntities); var folderEntities = Mapper.Map <List <EfModel.Folder> >(folders); await dbContext.BulkCopyAsync(base.DefaultBulkCopyOptions, folderEntities); var sendEntities = Mapper.Map <List <EfModel.Send> >(sends); await dbContext.BulkCopyAsync(base.DefaultBulkCopyOptions, sendEntities); await dbContext.SaveChangesAsync(); } }
private List <TItem> GetItemsListAsync() { Logger.LogInformation($"ListBackgroundWorker.ExecuteAsync {this.GetType().Name} iteration ({IteratedCount}) executing"); using (var scope = ServiceScopeFactory.CreateScope()) { var service = scope.ServiceProvider.GetRequiredService <TListBackgroundService>() as IListBackgroundService <TItem>; if (service == null) { throw new InvalidOperationException($"Error resolve service {typeof(TListBackgroundService).Name} ListBackgroundWorker.ExecuteAsync {this.GetType().Name} iteration ({IteratedCount})"); } var task = Task.Run(() => service.GetItemsAsync()); task.Wait(); return(task.Result); } }
public async Task CreateManyAsync(IEnumerable <OrganizationUser> organizationUsers) { if (!organizationUsers.Any()) { return; } foreach (var organizationUser in organizationUsers) { organizationUser.SetNewId(); } using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var entities = Mapper.Map <List <EfModel.OrganizationUser> >(organizationUsers); await dbContext.AddRangeAsync(entities); } }
public async Task DeleteAsync(Guid organizationUserId) { using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var orgUser = await dbContext.FindAsync <EfModel.OrganizationUser>(organizationUserId); var sponsorships = dbContext.OrganizationSponsorships .Where(os => os.SponsoringOrganizationUserId != default && os.SponsoringOrganizationUserId.Value == organizationUserId); foreach (var sponsorship in sponsorships) { sponsorship.SponsoringOrganizationUserId = null; } dbContext.Remove(orgUser); await dbContext.SaveChangesAsync(); } }
public virtual async Task <List <T> > CreateMany(List <T> objs) { using (var scope = ServiceScopeFactory.CreateScope()) { var entities = new List <TEntity>(); foreach (var o in objs) { o.SetNewId(); var entity = Mapper.Map <TEntity>(o); entities.Add(entity); } var dbContext = GetDatabaseContext(scope); await GetDbSet(dbContext).AddRangeAsync(entities); await dbContext.SaveChangesAsync(); return(objs); } }
public async Task SoftDeleteByIdsOrganizationIdAsync(IEnumerable <Guid> ids, Guid organizationId) { using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var utcNow = DateTime.UtcNow; var ciphers = dbContext.Ciphers.Where(c => ids.Contains(c.Id) && c.OrganizationId == organizationId); await ciphers.ForEachAsync(cipher => { dbContext.Attach(cipher); cipher.DeletedDate = utcNow; cipher.RevisionDate = utcNow; }); await dbContext.SaveChangesAsync(); await OrganizationUpdateStorage(organizationId); await UserBumpAccountRevisionDateByOrganizationId(organizationId); } }
private void ExecuteItemMethodSafety(SemaphoreSlim semaphore, TItem item, long iterationId, CancellationToken stoppingToken) { Logger.LogInformation($"ListBackgroundWorker.ExecuteItemMethodSafety {this.GetType().Name} iteration ({iterationId}) start processing item: {JsonConvert.SerializeObject(item)}"); Interlocked.Increment(ref _lastIterationListItemsProcessedCount); Interlocked.Exchange(ref _lastIterationListItemExecuteDateTimeInBinnary, DateTime.Now.ToBinary()); try { var itemWatcher = new Stopwatch(); itemWatcher.Start(); using (var scope = ServiceScopeFactory.CreateScope()) { var service = scope.ServiceProvider.GetRequiredService <TListBackgroundService>() as IListBackgroundService <TItem>; if (service == null) { throw new InvalidOperationException($"ListBackgroundWorker.ExecuteItemMethodSafety {this.GetType().Name} iteration ({iterationId}) service {typeof(TListBackgroundService).Name}"); } var processTask = _defaultRetryPolicyAsync.ExecuteAsync(() => service.ProcessItemAsync(item, stoppingToken)); processTask.Wait(); } itemWatcher.Stop(); Interlocked.Increment(ref _lastIterationListItemsSuccessProcessedCount); Interlocked.Exchange(ref _lastIterationListItemsLastDurationInMilliseconds, itemWatcher.ElapsedMilliseconds); Interlocked.Add(ref _lastIterationListItemsSumDurationInMilliseconds, _lastIterationListItemsLastDurationInMilliseconds); Logger.LogInformation($"ListBackgroundWorker.ExecuteItemMethodSafety {this.GetType().Name} iteration ({iterationId}) finish processing item: {JsonConvert.SerializeObject(item)}"); } catch (Exception exc) { this.Logger.LogError(exception: exc, message: $"ListBackgroundWorker.ExecuteItemMethodSafety {this.GetType().Name} iteration ({iterationId}) fail, item: {JsonConvert.SerializeObject(item)}"); } finally { semaphore.Release(); } }
protected async Task <bool> AddToInboxAsync( string messageId, string eventName, Type eventType, byte[] eventBytes) { if (AbpDistributedEventBusOptions.Inboxes.Count <= 0) { return(false); } using (var scope = ServiceScopeFactory.CreateScope()) { foreach (var inboxConfig in AbpDistributedEventBusOptions.Inboxes.Values) { if (inboxConfig.EventSelector == null || inboxConfig.EventSelector(eventType)) { var eventInbox = (IEventInbox)scope.ServiceProvider.GetRequiredService(inboxConfig.ImplementationType); if (!messageId.IsNullOrEmpty()) { if (await eventInbox.ExistsByMessageIdAsync(messageId)) { continue; } } await eventInbox.EnqueueAsync( new IncomingEventInfo( GuidGenerator.Create(), messageId, eventName, eventBytes, Clock.Now ) ); } } } return(true); }
async Task UpdateGuildEntitiesAsync(GuildCreateEventArgs e) { m_logger.LogCritical($"UpdateGuildEntitiesAsync-Start: {e.Guild.Name}"); using var scope = ServiceScopeFactory.CreateScope(); var dbContext = scope.ServiceProvider.GetService <InciteDbContext>(); var guild = await dbContext.Guilds .FirstOrDefaultAsync(x => x.DiscordId == e.Guild.Id); if (guild == null) { guild = new Guild() { DiscordId = e.Guild.Id }; var everyoneRole = new Role() { DiscordId = e.Guild.EveryoneRole.Id, Guild = guild, Kind = RoleKind.Everyone }; dbContext.Guilds.Add(guild); dbContext.Roles.Add(everyoneRole); } if (guild.Options == null) { guild.Options = new GuildOptions() { CommandPrefix = '!' }; } m_commandPrefixCache.SetPrefix(guild, guild.Options.CommandPrefix); await CreateNewGuildMembersAsync(guild, e, dbContext); await dbContext.SaveChangesAsync(); m_logger.LogCritical($"UpdateGuildEntitiesAsync-Stop: {e.Guild.Name}"); }
public async Task <ApplicationMenu> GetAsync(string name) { var menu = new ApplicationMenu(name); using (var scope = ServiceScopeFactory.CreateScope()) { var context = new MenuConfigurationContext(menu, scope.ServiceProvider); foreach (var contributor in Options.MenuContributors) { await contributor.ConfigureMenuAsync(context); } await CheckPermissionsAsync(scope.ServiceProvider, menu); } NormalizeMenu(menu); return(menu); }
protected async Task UserBumpAccountRevisionDateByProviderUserIds(ICollection <Guid> providerUserIds) { using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var query = from pu in dbContext.ProviderUsers join u in dbContext.Users on pu.UserId equals u.Id where pu.Status.Equals(ProviderUserStatusType.Confirmed) && providerUserIds.Contains(pu.Id) select new { pu, u }; var users = query.Select(x => x.u); await users.ForEachAsync(u => { dbContext.Attach(u); u.AccountRevisionDate = DateTime.UtcNow; }); await dbContext.SaveChangesAsync(); } }
public virtual async Task <ClaimsPrincipal> CreateAsync(ClaimsPrincipal existsClaimsPrincipal = null) { using (var scope = ServiceScopeFactory.CreateScope()) { var claimsPrincipal = existsClaimsPrincipal ?? new ClaimsPrincipal(new ClaimsIdentity( AuthenticationType, AbpClaimTypes.UserName, AbpClaimTypes.Role)); var context = new AbpClaimsPrincipalContributorContext(claimsPrincipal, scope.ServiceProvider); foreach (var contributorType in Options.Contributors) { var contributor = (IAbpClaimsPrincipalContributor)scope.ServiceProvider.GetRequiredService(contributorType); await contributor.ContributeAsync(context); } return(claimsPrincipal); } }
protected async Task UserBumpAccountRevisionDateByCipherId(IEnumerable <Cipher> ciphers) { using (var scope = ServiceScopeFactory.CreateScope()) { foreach (var cipher in ciphers) { var dbContext = GetDatabaseContext(scope); var query = new UserBumpAccountRevisionDateByCipherIdQuery(cipher); var users = query.Run(dbContext); await users.ForEachAsync(e => { dbContext.Attach(e); e.RevisionDate = DateTime.UtcNow; }); await dbContext.SaveChangesAsync(); } } }
public async Task SaveAsync(Grant obj) { using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var existingGrant = await (from g in dbContext.Grants where g.Key == obj.Key select g).FirstOrDefaultAsync(); if (existingGrant != null) { dbContext.Entry(existingGrant).CurrentValues.SetValues(obj); } else { var entity = Mapper.Map<EfModel.Grant>(obj); await dbContext.AddAsync(entity); await dbContext.SaveChangesAsync(); } } }
public void Execute(TArgs args) { if (!Options.IsJobExecutionEnabled) { throw new AbpException( "Background job execution is disabled. " + "This method should not be called! " + "If you want to enable the background job execution, " + $"set {nameof(AbpBackgroundJobOptions)}.{nameof(AbpBackgroundJobOptions.IsJobExecutionEnabled)} to true! " + "If you've intentionally disabled job execution and this seems a bug, please report it." ); } using (var scope = ServiceScopeFactory.CreateScope()) { var jobType = Options.GetJob(typeof(TArgs)).JobType; var context = new JobExecutionContext(scope.ServiceProvider, jobType, args); AsyncHelper.RunSync(() => JobExecuter.ExecuteAsync(context)); } }
public async Task ReplaceAsync(OrganizationUser obj, IEnumerable <SelectionReadOnly> collections) { await base.ReplaceAsync(obj); using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var procedure = new OrganizationUserUpdateWithCollectionsQuery(obj, collections); var update = procedure.Update.Run(dbContext); dbContext.UpdateRange(await update.ToListAsync()); var insert = procedure.Insert.Run(dbContext); await dbContext.AddRangeAsync(await insert.ToListAsync()); dbContext.RemoveRange(await procedure.Delete.Run(dbContext).ToListAsync()); await dbContext.SaveChangesAsync(); } }
protected async Task UserBumpAccountRevisionDateByOrganizationUserId(Guid organizationUserId) { using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var query = from u in dbContext.Users join ou in dbContext.OrganizationUsers on u.Id equals ou.UserId where ou.Id.Equals(organizationUserId) && ou.Status.Equals(OrganizationUserStatusType.Confirmed) select new { u, ou }; var users = query.Select(x => x.u); await users.ForEachAsync(u => { dbContext.Attach(u); u.AccountRevisionDate = DateTime.UtcNow; }); await dbContext.SaveChangesAsync(); } }
public async Task <ICollection <CollectionDetails> > GetManyByUserIdAsync(Guid userId) { using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); return((await new UserCollectionDetailsQuery(userId).Run(dbContext).ToListAsync()) .GroupBy(c => c.Id) .Select(g => new CollectionDetails { Id = g.Key, OrganizationId = g.FirstOrDefault().OrganizationId, Name = g.FirstOrDefault().Name, ExternalId = g.FirstOrDefault().ExternalId, CreationDate = g.FirstOrDefault().CreationDate, RevisionDate = g.FirstOrDefault().RevisionDate, ReadOnly = g.Min(c => c.ReadOnly), HidePasswords = g.Min(c => c.HidePasswords) }).ToList()); } }
public async Task <Tuple <CollectionDetails, ICollection <SelectionReadOnly> > > GetByIdWithGroupsAsync(Guid id, Guid userId) { var collection = await GetByIdAsync(id, userId); using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var query = from cg in dbContext.CollectionGroups where cg.CollectionId.Equals(id) select new SelectionReadOnly { Id = cg.GroupId, ReadOnly = cg.ReadOnly, HidePasswords = cg.HidePasswords, }; var configurations = await query.ToArrayAsync(); return(new Tuple <CollectionDetails, ICollection <SelectionReadOnly> >(collection, configurations)); } }
public async Task <Tuple <Core.Entities.Group, ICollection <SelectionReadOnly> > > GetByIdWithCollectionsAsync(Guid id) { var grp = await base.GetByIdAsync(id); using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var query = await( from cg in dbContext.CollectionGroups where cg.GroupId == id select cg).ToListAsync(); var collections = query.Select(c => new SelectionReadOnly { Id = c.CollectionId, ReadOnly = c.ReadOnly, HidePasswords = c.HidePasswords, }).ToList(); return(new Tuple <Core.Entities.Group, ICollection <SelectionReadOnly> >( grp, collections)); } }
public void GcCleanupDbFactoryTest() { var scope = ServiceScopeFactory.CreateScope(); var contextFactory = scope.ServiceProvider.GetRequiredService <IDbContextFactory>(); var weak = CallInItsOwnScope(() => { var ctx = contextFactory.CreateDbContext <FakeDbContext1>(); ctx.Dispose(); var wRef = new WeakReference(ctx); Assert.True(wRef.IsAlive); GC.Collect(); Assert.True(wRef.IsAlive); return(wRef); }); GC.Collect(); Assert.False(weak.IsAlive); }
public async Task <IEnumerable <OrganizationUserPublicKey> > GetManyPublicKeysByOrganizationUserAsync(Guid organizationId, IEnumerable <Guid> Ids) { using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var query = from ou in dbContext.OrganizationUsers where Ids.Contains(ou.Id) && ou.Status == OrganizationUserStatusType.Accepted join u in dbContext.Users on ou.UserId equals u.Id where ou.OrganizationId == organizationId select new { ou, u }; var data = await query .Select(x => new OrganizationUserPublicKey() { Id = x.ou.Id, PublicKey = x.u.PublicKey, }).ToListAsync(); return(data); } }
public async Task <Tuple <OrganizationUserUserDetails, ICollection <SelectionReadOnly> > > GetDetailsByIdWithCollectionsAsync(Guid id) { var organizationUserUserDetails = await GetDetailsByIdAsync(id); using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var query = from ou in dbContext.OrganizationUsers join cu in dbContext.CollectionUsers on ou.Id equals cu.OrganizationUserId where !ou.AccessAll && ou.Id == id select cu; var collections = await query.Select(cu => new SelectionReadOnly { Id = cu.CollectionId, ReadOnly = cu.ReadOnly, HidePasswords = cu.HidePasswords, }).ToListAsync(); return(new Tuple <OrganizationUserUserDetails, ICollection <SelectionReadOnly> >(organizationUserUserDetails, collections)); } }
public async Task <ICollection <Guid> > CreateManyAsync(IEnumerable <Core.Entities.OrganizationUser> organizationUsers) { if (!organizationUsers.Any()) { return(new List <Guid>()); } foreach (var organizationUser in organizationUsers) { organizationUser.SetNewId(); } using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var entities = Mapper.Map <List <OrganizationUser> >(organizationUsers); await dbContext.AddRangeAsync(entities); } return(organizationUsers.Select(u => u.Id).ToList()); }
public async Task RunAsync(string[] args) { Logger.LogInformation("ROCKET CLI (https://aiwins.cn)"); await CheckCliVersionAsync(); var commandLineArgs = CommandLineArgumentParser.Parse(args); var commandType = CommandSelector.Select(commandLineArgs); using (var scope = ServiceScopeFactory.CreateScope()) { var command = (IConsoleCommand)scope.ServiceProvider.GetRequiredService(commandType); try { await command.ExecuteAsync(commandLineArgs); } catch (CliUsageException usageException) { Logger.LogWarning(usageException.Message); } catch (Exception ex) { Logger.LogException(ex); } } }
protected virtual void MessageReceived(object sender, BasicDeliverEventArgs ea) { using (var scope = ServiceScopeFactory.CreateScope()) { var context = new JobExecutionContext( scope.ServiceProvider, JobConfiguration.JobType, Serializer.Deserialize(ea.Body, typeof(TArgs)) ); try { AsyncHelper.RunSync(() => JobExecuter.ExecuteAsync(context)); ChannelAccessor.Channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); } catch (BackgroundJobExecutionException) { //TODO: Reject like that? ChannelAccessor.Channel.BasicReject(deliveryTag: ea.DeliveryTag, requeue: true); } catch (Exception) { //TODO: Reject like that? ChannelAccessor.Channel.BasicReject(deliveryTag: ea.DeliveryTag, requeue: false); } } }
private void Timer_Elapsed(object sender, System.EventArgs e) { using (var scope = ServiceScopeFactory.CreateScope()) { try { AsyncHelper.RunSync( () => DoWorkAsync(new PeriodicBackgroundWorkerContext(scope.ServiceProvider)) ); } catch (Exception ex) { AsyncHelper.RunSync( () => scope.ServiceProvider .GetRequiredService <IExceptionNotifier>() .NotifyAsync(new ExceptionNotificationContext(ex)) ); Logger.LogException(ex); } } }