public IEnumerable <priz> GetAll()
 {
     using (var dbContext = _dbContextFactory.Create())
     {
         return(dbContext.Set <priz>().ToList());
     }
 }
Exemple #2
0
        public void AddOrganizationRole(string name)
        {
            using (LabDbEntities entities = _dbContextFactory.Create())
            {
                OrganizationRole newRole = new OrganizationRole
                {
                    Name        = name,
                    Description = ""
                };

                entities.OrganizationRoles.Add(newRole);

                foreach (Organization org in entities.Organizations)
                {
                    OrganizationRoleMapping newMapping = new OrganizationRoleMapping
                    {
                        Role         = newRole,
                        Organization = org,
                        IsSelected   = false
                    };
                    entities.OrganizationRoleMappings.Add(newMapping);
                }

                entities.SaveChanges();
            }
        }
Exemple #3
0
        public async Task <List <Contact> > GetContacts(IEnumerable <Guid> contactIds, CancellationToken cancellationToken)
        {
            await using var db = _dbContextFactory.Create();

            return(await db.Contacts.Where(c => contactIds.Contains(c.Id))
                   .ToListAsync(cancellationToken));
        }
Exemple #4
0
        public void SaveEvent <TAggregate>(IDomainEvent @event) where TAggregate : IAggregateRoot
        {
            using (var context = _contextFactory.Create())
            {
                var aggregate = context.DomainAggregates.FirstOrDefault(x => x.Id == @event.AggregateRootId);

                if (aggregate == null)
                {
                    context.DomainAggregates.Add(new DomainAggregate
                    {
                        Id   = @event.AggregateRootId,
                        Type = typeof(TAggregate).AssemblyQualifiedName
                    });
                }

                var currentSequenceCount = context.DomainEvents.Count(x => x.DomainAggregateId == @event.AggregateRootId);

                context.DomainEvents.Add(new DomainEvent
                {
                    DomainAggregateId = @event.AggregateRootId,
                    SequenceNumber    = currentSequenceCount + 1,
                    Type      = @event.GetType().AssemblyQualifiedName,
                    Body      = JsonConvert.SerializeObject(@event),
                    TimeStamp = @event.TimeStamp
                                //UserId = @event.UserId
                });

                context.SaveChanges();
            }
        }
 public void Transaction(Action <TDbContext> transaction)
 {
     using (var context = dbContextFactory.Create())
     {
         transaction(context);
     }
 }
Exemple #6
0
        public async Task <bool> IsUserInConversationAsync(ConversationType conversationType, long conversationId, long userId)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                switch (conversationType)
                {
                case ConversationType.Dialog:
                {
                    return(await context.Dialogs
                           .AnyAsync(opt => (opt.FirstUID == userId) && opt.Id == conversationId).ConfigureAwait(false));
                }

                case ConversationType.Chat:
                {
                    return(await context.ChatUsers
                           .AnyAsync(opt => opt.UserId == userId && opt.ChatId == conversationId && !opt.Deleted && !opt.Banned).ConfigureAwait(false));
                }

                case ConversationType.Channel:
                {
                    return(await context.ChannelUsers
                           .AnyAsync(opt => opt.UserId == userId && opt.ChannelId == conversationId && !opt.Deleted && !opt.Banned).ConfigureAwait(false));
                }

                default:
                    return(false);
                }
            }
        }
Exemple #7
0
        public MenuViewModel GetByName(Guid siteId, string name, Guid languageId = new Guid())
        {
            return(_cacheManager.Get(string.Format(CacheKeys.MenuCacheKey, siteId, name, languageId), () =>
            {
                using (var context = _dbContextFactory.Create())
                {
                    var menu = context.Menus.FirstOrDefault(x => x.SiteId == siteId && x.Name == name && x.Status != MenuStatus.Deleted);

                    if (menu == null)
                    {
                        return new MenuViewModel();
                    }

                    LoadMenuItems(context, menu);

                    var language = languageId != Guid.Empty
                        ? context.Languages.FirstOrDefault(x => x.SiteId == siteId && x.Id == languageId && x.Status == LanguageStatus.Active)
                        : null;

                    bool addLanguageSlug = context.Sites.Where(x => x.Id == siteId).Select(site => site.AddLanguageSlug).FirstOrDefault();

                    var menuModel = new MenuViewModel
                    {
                        Name = menu.Name,
                        MenuItems = PopulateMenuItems(context, menu.MenuItems, Guid.Empty, language, addLanguageSlug)
                    };

                    return menuModel;
                }
            }));
        }
Exemple #8
0
        public async Task <PollDto> GetPollAsync(Guid pollId, long conversationId, ConversationType conversationType)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                var poll = await context.Polls
                           .Include(opt => opt.Options)
                           .ThenInclude(opt => opt.PollOptionVotes)
                           .FirstOrDefaultAsync(opt =>
                                                opt.PollId == pollId &&
                                                opt.ConvertsationId == conversationId &&
                                                opt.ConversationType == conversationType)
                           .ConfigureAwait(false);

                if (poll == null)
                {
                    var nodeId = await conversationsService.GetConversationNodeIdAsync(conversationType, conversationId).ConfigureAwait(false);

                    var connection = connectionsService.GetNodeConnection(nodeId);
                    if (connection != null)
                    {
                        var loadedPoll = await nodeRequestSender.GetPollInformationAsync(conversationId, conversationType, pollId, connection).ConfigureAwait(false);

                        loadedPoll = await SavePollAsync(loadedPoll).ConfigureAwait(false);

                        return(loadedPoll);
                    }
                }
                return(PollConverter.GetPollDto(poll));
            }
        }
Exemple #9
0
        public IEnumerable <IngredientListModel> GetAll()
        {
            using var dbContext = _dbContextFactory.Create();

            return(dbContext.Ingredients
                   .Select(e => IngredientMapper.MapIngredientEntityToListModel(e)).ToArray());
        }
Exemple #10
0
        public void Add(ILabel addObj)
        {
            using (WisTEntities context = _contextFactory.Create())
            {
                User user = new User(addObj);

                context.Users.Add(user);

                foreach (var image in addObj.Images)
                {
                    user.UserImages.Add(new UserImage(image));
                }

                try
                {
                    context.SaveChanges();
                }
                catch
                {
                    throw new AddExistingUserException();
                }

                addObj.Id = new Identifier(user.Id);
            }
        }
Exemple #11
0
        public async Task <ApiResult> Insert(InsertAutomation request, CancellationToken cancellationToken)
        {
            var item = request.Item ?? throw new ArgumentNullException(nameof(request.Item));

            item.Uid = Guid.NewGuid();

            var dbConditions = CollectDbConditions(item);
            var dbActions    = CollectDbActions(item);

            int affected;

            using (var db = _dbContextFactory.Create())
            {
                affected = await db.GetTable <DbAutomation>()
                           .Value(x => x.Uid, item.Uid)
                           .Value(x => x.EntityTypeCode, request.EntityTypeCode)
                           .Value(x => x.EntityTypeUid, request.EntityTypeUid)
                           .Value(x => x.TypeCode, "trigger")              // todo: ask user
                           .Value(x => x.Name, item.Name)
                           .Value(x => x.Description, item.Description)
                           .Value(x => x.IsActive, true)
                           .Value(x => x.IsSystem, item.System)
                           .Value(x => x.DisplayOrder, item.DisplayOrder)
                           .InsertAsync(cancellationToken);

                await db.GetTable <DbAutomationAction>().BulkCopyAsync(dbActions, cancellationToken);

                await db.GetTable <DbAutomationCondition>().BulkCopyAsync(dbConditions, cancellationToken);
            }

            return(new ApiResult {
                Uid = item.Uid, AffectedRows = affected
            });
        }
Exemple #12
0
        public async Task DeleteUserInformationAsync(long userId)
        {
            try
            {
                using (MessengerDbContext context = contextFactory.Create())
                {
                    User user = await context.Users
                                .Include(opt => opt.Emails)
                                .Include(opt => opt.Phones)
                                .Include(opt => opt.Tokens)
                                .FirstOrDefaultAsync(opt => opt.Id == userId)
                                .ConfigureAwait(false);

                    user.Phones         = null;
                    user.Emails         = null;
                    user.About          = null;
                    user.Birthday       = null;
                    user.City           = null;
                    user.Country        = null;
                    user.Sha512Password = null;
                    user.Photo          = null;
                    user.NameSecond     = null;
                    user.NameFirst      = "unknown";
                    user.Tokens         = null;
                    context.Update(user);
                    await context.SaveChangesAsync().ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
            }
        }
        public async Task <string> AddNewOperationAsync(long nodeId, long userId)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                long currentTime          = DateTime.UtcNow.ToUnixTime();
                var  uncomplededOperation = await context.ChangeUserNodeOperations
                                            .FirstOrDefaultAsync(opt => !opt.Completed && opt.UserId == userId && opt.ExpirationTime > currentTime).ConfigureAwait(false);

                if (uncomplededOperation != null)
                {
                    context.Remove(uncomplededOperation);
                }
                ChangeUserNodeOperation operation = new ChangeUserNodeOperation
                {
                    NodeId         = nodeId,
                    UserId         = userId,
                    OperationId    = RandomExtensions.NextString(64),
                    Completed      = false,
                    RequestTime    = currentTime,
                    ExpirationTime = currentTime + (long)TimeSpan.FromDays(1).TotalSeconds
                };
                await context.AddAsync(operation).ConfigureAwait(false);

                await context.SaveChangesAsync().ConfigureAwait(false);

                return(operation.OperationId);
            }
        }
 public virtual TDocument Get(Guid documentId)
 {
     using (var ctx = dbContextFactory.Create())
     {
         return(ctx.Set <TDocument>().FirstOrDefault(x => x.GUID == documentId));
     }
 }
Exemple #15
0
        public void Add(Review review)
        {
            var dbContext = _dbContextFactory.Create();

            dbContext.Reviews.Add(review);
            dbContext.SaveChanges();
        }
        public async Task <ChannelVm> EditChannelAsync(ChannelVm channel, long editorUserId)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                ChannelUser channelUser = await context.ChannelUsers
                                          .Include(opt => opt.Channel)
                                          .FirstOrDefaultAsync(opt =>
                                                               opt.ChannelId == channel.ChannelId &&
                                                               opt.UserId == editorUserId &&
                                                               opt.ChannelUserRole >= ChannelUserRole.Administrator)
                                          .ConfigureAwait(false);

                if (channelUser != null)
                {
                    if (channelUser.ChannelUserRole == ChannelUserRole.Administrator && (channelUser.Banned || channelUser.Deleted))
                    {
                        throw new PermissionDeniedException();
                    }

                    channelUser.Channel = ChannelConverter.GetChannel(channelUser.Channel, channel);
                    context.Update(channelUser.Channel);
                    await context.SaveChangesAsync().ConfigureAwait(false);

                    var editedChannel = ChannelConverter.GetChannel(channelUser.Channel);
                    editedChannel.UserRole         = channelUser.ChannelUserRole;
                    editedChannel.SubscribersCount = await context.ChannelUsers.CountAsync(opt => opt.Deleted == false && opt.ChannelId == channel.ChannelId).ConfigureAwait(false);

                    return(editedChannel);
                }
                throw new PermissionDeniedException();
            }
        }
        public async Task <QRCodeContent> CreateQRCodeAsync(long userId, long nodeId)
        {
            var    sequence    = RandomExtensions.NextBytes(192);
            string sequenceStr = Convert.ToBase64String(sequence);

            QRCode qrCode = new QRCode
            {
                UserId       = userId,
                SequenceHash = GetSequenceHashSha512(sequenceStr)
            };

            using (MessengerDbContext context = contextFactory.Create())
            {
                bool isUserExists = await context.Users.AnyAsync(user => user.Id == userId).ConfigureAwait(false);

                if (!isUserExists)
                {
                    throw new ObjectDoesNotExistsException($"User with Id: {userId} does not found.");
                }

                await context.QRCodes.AddAsync(qrCode).ConfigureAwait(false);

                await context.SaveChangesAsync().ConfigureAwait(false);

                return(new QRCodeContent(qrCode.Id, qrCode.UserId, nodeId, sequenceStr));
            }
        }
Exemple #18
0
        public APIResult GetList([FromBody] GetListArgsModel args)
        {
            using (var db = dbFactory.Create(_communityService, args.CommunityFlag, args.AppFlag))
            {
                var query = db.Query <SettingBase>()
                            .Where(m => !m.IsDel);

                var list = query
                           .OrderByDescending(m => m.Id)
                           .Select(m => new RowItem()
                {
                    Detail      = m.Detail,
                    Flag        = m.Flag,
                    GroupFlag   = m.GroupFlag,
                    Id          = m.Id,
                    IsDel       = m.IsDel,
                    SettingType = m.SettingType,
                    Value       = m.Value
                })
                           .ToList();

                return(Success(new GetListModel()
                {
                    Items = list
                }));
            }
        }
        public ValidationReportDetails GetValidationReportDetails(int validationReportId)
        {
            LoggingService.LogDebugMessage($"Retrieving Validation Report Details for report with ID number: {validationReportId.ToString()}");
            using (var portalDbContext = DbContextFactory.Create())
            {
                var reportDetails = portalDbContext.ValidationReportDetails
                                    .Include(x => x.ValidationReportSummary)
                                    .Include(x => x.ValidationReportSummary.SchoolYear)
                                    .FirstOrDefault(x => x.ValidationReportSummaryId == validationReportId);

                if (reportDetails != null)
                {
                    reportDetails.CompletedWhen =
                        reportDetails.CompletedWhen?.ToLocalTime() ?? reportDetails.CompletedWhen;

                    reportDetails.ValidationReportSummary.RequestedWhen =
                        reportDetails.ValidationReportSummary.RequestedWhen.ToLocalTime();

                    LoggingService.LogDebugMessage(
                        $"Successfully retrieved Validation Report Details for report with ID number: {validationReportId.ToString()}");
                }

                return(reportDetails);
            }
        }
Exemple #20
0
 public User GetById(Guid id)
 {
     using (var context = _dbContextFactory.Create())
     {
         var dbEntity = context.Users.FirstOrDefault(x => x.Id == id && x.Status != UserStatus.Deleted);
         return(dbEntity != null?_mapper.Map <User>(dbEntity) : null);
     }
 }
Exemple #21
0
        public async Task Create(Document document, CancellationToken cancellationToken)
        {
            document.Uid ??= Guid.NewGuid();
            document.StatusCode ??= DocumentStatusCode.Draft;

            using (var db = _dbContextFactory.Create())
            {
                await db.GetTable <DbDocument>()
                .Value(x => x.Uid, document.Uid)
                .Value(x => x.CompanyUid, document.CompanyUid)
                .Value(x => x.DocumentTypeUid, document.DocumentTypeUid)
                .Value(x => x.StatusCode, document.StatusCode)
                .Value(x => x.Direction, document.Direction.ToString())
                .Value(x => x.DocumentNumber, document.DocumentNumber)
                .Value(x => x.DocumentDate, document.DocumentDate)
                .Value(x => x.Name, document.Name)
                .InsertAsync(cancellationToken);
            }

            /*if (document.StatusCode != DocumentStatusCode.Draft)
             * {
             *      await _mediator.Publish(new EntityStatusChanged<Document>
             *      {
             *              Entity = document,
             *              StatusCode = DocumentStatusCode.Draft
             *      }, cancellationToken);
             * }*/

            if (document.StatusCode == DocumentStatusCode.Published)
            {
                var documentNumber = await _numberGenerator
                                     .GenerateNumber(new GenerateNumberRequest
                {
                    EntityTypeCode = DocumentType.EntityTypeCode,
                    EntityTypeUid  = document.DocumentTypeUid,
                    EntityUid      = document.Uid
                }, cancellationToken);

                if (documentNumber != null)
                {
                    document.DocumentNumber = documentNumber;

                    using (var db = _dbContextFactory.Create())
                    {
                        await db.GetTable <DbDocument>()
                        .Where(x => x.Uid == document.Uid)
                        .Set(x => x.DocumentNumber, documentNumber)
                        .UpdateAsync(cancellationToken);
                    }
                }
            }

            await _mediator.Publish(new EntityStatusChanged <Document>
            {
                Entity     = document,
                StatusCode = document.StatusCode
            }, cancellationToken);
        }
        public async Task <List <MessageVm> > LoadForwardedMessagesAsync(ForwardedMessagesInfo forwarded, long?requestorId)
        {
            var            messagesCondition = PredicateBuilder.New <Message>();
            List <Message> messages          = new List <Message>();

            switch (forwarded.ConversationType)
            {
            case ConversationType.Chat:
            {
                messagesCondition = forwarded.MessagesGlobalId.Aggregate(messagesCondition,
                                                                         (current, value) => current.Or(opt => opt.GlobalId == value && opt.ChatId == forwarded.ConversationId).Expand());
                break;
            }

            case ConversationType.Dialog:
            {
                messagesCondition = forwarded.MessagesGlobalId.Aggregate(messagesCondition,
                                                                         (current, value) => current.Or(opt => opt.GlobalId == value && opt.DialogId == forwarded.ConversationId).Expand());
                break;
            }

            case ConversationType.Channel:
            {
                messagesCondition = forwarded.MessagesGlobalId.Aggregate(messagesCondition,
                                                                         (current, value) => current.Or(opt => opt.GlobalId == value && opt.ChannelId == forwarded.ConversationId).Expand());
            }
            break;

            case ConversationType.Unknown:
            {
                messagesCondition = forwarded.MessagesGlobalId.Aggregate(messagesCondition,
                                                                         (current, value) => current.Or(opt => opt.GlobalId == value && opt.ChannelId == null && opt.DialogId == null && opt.ChatId == null).Expand());
            }
            break;

            default:
                return(null);
            }
            using (MessengerDbContext context = contextFactory.Create())
            {
                messages = await context.Messages
                           .AsNoTracking()
                           .Include(opt => opt.Attachments)
                           .Where(messagesCondition)
                           .ToListAsync().ConfigureAwait(false);

                foreach (var message in messages)
                {
                    if (message.ChannelId != null)
                    {
                        message.SenderId = null;
                    }

                    message.Attachments = message.Attachments.Where(opt => opt.Type != (short)AttachmentType.ForwardedMessages).ToList();
                }
                return(MessageConverter.GetMessagesVm(MessageConverter.GetMessagesDto(messages), requestorId));
            }
        }
        public async Task <long> CountAsync(StreamId streamId, CancellationToken cancellationToken = default)
        {
            using (var context = _dbContextFactory.Create())
            {
                var count = await context.Events.LongCountAsync(@event => @event.StreamId == streamId, cancellationToken);

                return(count);
            }
        }
Exemple #24
0
 public IEnumerable <Log> GetIdentityIssues()
 {
     using (var dbContext = DbContextFactory.Create())
     {
         return(dbContext.Logs
                .ToList()
                .Where(x => new Uri(x.Url).PathAndQuery.StartsWith($"/{ApiName}/api/identity/")));
     }
 }
Exemple #25
0
        /// <summary>
        /// Gets the context from the ambient <see cref="IEfUnitOfWork"/> if one exists,
        /// else it tries to create a new one via service location with the specified registered name.
        /// </summary>
        /// <param name="registeredNameForServiceLocation">The context's registered name for service location.</param>
        /// <returns>Instance of <see cref="DbContext"/>.</returns>
        /// <remarks></remarks>
        public DbContext GetOrCreateDbContext(String registeredNameForServiceLocation)
        {
            if (!AmbientEfUnitOfWorkExists())
            {
                return(_DbContextFactory.Create(registeredNameForServiceLocation));
            }

            return(GetOrCreateDbContextForUnitOfWork(registeredNameForServiceLocation));
        }
        public async Task <int> Create(Gateway gateway)
        {
            using (var _context = _factory.Create()) {
                var r1     = _context.Gateways.Add(gateway);
                var result = await _context.SaveChangesAsync();

                return(r1.id);
            }
        }
Exemple #27
0
        public async Task AddAsync(Contact contact)
        {
            await using (var context = _dbContextFactory.Create())
            {
                await context.AddAsync(contact);

                await SaveDbContextChangesAsync(context);
            }
        }
        public IReadOnlyUnitOfWork StartReadOnlyUnit(Guid userId)
        {
            if (userId == Guid.Empty)
            {
                throw new ArgumentOutOfRangeException(nameof(userId), $"{nameof(userId)} cannot be empty.");
            }

            return(new ReadOnlyUnitOfWorkWithPermissions(_factory.Create(), userId));
        }
Exemple #29
0
 /// <summary>
 /// Fetches/selects all job definitions. Since we know there will not be many jobs we will not apply
 /// filtering or pagination.
 /// </summary>
 /// <param name="ordering">OrderBy clause</param>
 /// <returns>List of job definitions</returns>
 public IList <JobDefinition> FetchJobDefinitions(string ordering)
 {
     using (IDbContext dbContext = _dbContextFactory.Create())
     {
         return(dbContext.Set <JobDefinition>()
                .OrderBy(ordering)
                .ToList());
     }
 }
Exemple #30
0
 public ModuleType GetById(Guid id)
 {
     using (var context = _dbContextFactory.Create())
     {
         var dbEntity = context.ModuleTypes
                        .FirstOrDefault(x => x.Id == id && x.Status != ModuleTypeStatus.Deleted);
         return(dbEntity != null?_mapper.Map <ModuleType>(dbEntity) : null);
     }
 }