public IFutureValue<int> CheckIsUsed(IRepository repository, CategoryTree categoryTree)
        {
            var query = repository.AsQueryable<WidgetCategory>().Where(ec => ec.Category.CategoryTree == categoryTree
            && !ec.Widget.IsDeleted
            && (ec.Widget.Status == ContentStatus.Draft || ec.Widget.Status == ContentStatus.Published)).ToRowCountFutureValue();

            return query;
        }
Beispiel #2
0
        public WidgetStatistics Average()
        {
            var result = new WidgetStatistics();

            try
            {
                using (var ctx = _dbContextScopeFactory.CreateReadOnly())
                {
                    #region Get Incomes
                    result.IncomeCompany = _incomeRepo.Find(x =>
                                                            x.IncomeType == Enums.IncomeType.CompanyTotal
                                                            ).GroupBy(x => new {
                        Year  = x.CreatedAt.Value.Year,
                        Month = x.CreatedAt.Value.Month
                    }).Select(x => new {
                        Year  = x.Key.Year,
                        Month = x.Key.Month,
                        Total = x.Sum(y => y.Total)
                    }).OrderByDescending(x => x.Year)
                                           .ThenByDescending(x => x.Month)
                                           .Select(x => x.Total).DefaultIfEmpty(0).Average();
                    #endregion

                    #region Get Students
                    result.NewStudents = (decimal)_userPerCourseRepo.AsQueryable().GroupBy(x => new {
                        Year  = x.CreatedAt.Value.Year,
                        Month = x.CreatedAt.Value.Month
                    }).Select(x => new
                    {
                        Year  = x.Key.Year,
                        Month = x.Key.Month,
                        Total = x.Count()
                    }).OrderByDescending(x => x.Year)
                                         .ThenByDescending(x => x.Month)
                                         .Select(x => x.Total).DefaultIfEmpty(0).Average();
                    #endregion

                    #region Get Courses
                    result.NewCourses = (decimal)_courseRepo.AsQueryable().GroupBy(x => new {
                        Year  = x.CreatedAt.Value.Year,
                        Month = x.CreatedAt.Value.Month
                    }).Select(x => new {
                        Year  = x.Key.Year,
                        Month = x.Key.Month,
                        Total = x.Count()
                    }).OrderByDescending(x => x.Year)
                                        .ThenByDescending(x => x.Month)
                                        .Select(x => x.Total).DefaultIfEmpty(0).Average();
                    #endregion
                }
            }
            catch (Exception e)
            {
                logger.Error(e.Message);
            }

            return(result);
        }
        public async Task Execute(ResendInviteCommandArgs args)
        {
            var actionExecutor = await _userManager.FindByIdAsync(args.ActionExecutorId);

            var map = await _repository.AsQueryable <Map>()
                      .NotRemoved()
                      .WithAdminPermissions(actionExecutor.Id)
                      .WithId(args.MapId)
                      .LoadAggregate()
                      .FirstOrDefaultAsync();

            if (map == null)
            {
                throw new ServiceException("Map not found");
            }

            var existingMembership = map.Memberships.FirstOrDefault(x => x.Id == args.InviteId);

            if (existingMembership == null)
            {
                throw new ServiceException("Invite not found");
            }

            var invitedUser = await _userManager.FindByIdAsync(existingMembership.InvitedId);

            var notificationSettings = await _repository.AsQueryable <UserNotificationSettings>()
                                       .Where(x => x.UserId == invitedUser.Id)
                                       .FirstAsync();

            if (!notificationSettings.NotifyAboutNewInvites)
            {
                return;
            }

            var emailArgs = new MapInviteEmailTemplateArgs
            {
                Address  = invitedUser.Email,
                MapId    = map.Id,
                InviteId = existingMembership.Id
            };

            var message = _emailMessageFactory.Get <MapInviteEmailTemplate, MapInviteEmailTemplateArgs>(emailArgs);

            _emailService.SendEmail(message);
        }
Beispiel #4
0
        /// <summary>
        /// Gets current page by given virtual path.
        /// </summary>
        /// <param name="virtualPath"></param>
        /// <returns>
        /// Current page object by given virtual path.
        /// </returns>
        public IPage GetPageByVirtualPath(string virtualPath)
        {
            var trimmed = virtualPath.UrlHash();

            if (temporaryPageCache.ContainsKey(trimmed))
            {
                return(temporaryPageCache[trimmed]);
            }

            // NOTE: if GetPageQuery() and CachePage() is used properly below code should not be executed.
            var page = repository
                       .AsQueryable <PageProperties>(p => p.PageUrlHash == trimmed)
                       .Fetch(p => p.Layout)
                       .Fetch(p => p.PagesView)
                       .FirstOrDefault();

            if (page != null)
            {
                page.IsInSitemap = page.PagesView.IsInSitemap;
                if (temporaryPageCache.ContainsKey(trimmed))
                {
                    temporaryPageCache.Remove(trimmed);
                }
                temporaryPageCache.Add(trimmed, page);
            }

            return(page);
        }
        /// <summary>
        /// Выполнение запроса.
        /// </summary>
        /// <param name="protectionDocId">Идентификатор охранного документа.</param>
        /// <returns>Охранный документ.</returns>
        public async Task<ProtectionDoc> ExecuteAsync(int protectionDocId)
        {
            IRepository<ProtectionDoc> repository = Uow.GetRepository<ProtectionDoc>();

            return await repository.AsQueryable()
                .Include(protectionDoc => protectionDoc.ProtectionDocCustomers)
                .ThenInclude(customer => customer.CustomerRole)
                .FirstOrDefaultAsync(protectionDoc => protectionDoc.Id == protectionDocId);
        }
Beispiel #6
0
        /// <summary>
        /// Выполнение запроса.
        /// </summary>
        /// <param name="contractId">Идентификатор договора.</param>
        /// <returns>Договор.</returns>
        public async Task <Contract> ExecuteAsync(int contractId)
        {
            IRepository <Contract> repository = Uow.GetRepository <Contract>();

            return(await repository.AsQueryable()
                   .Include(contract => contract.ContractCustomers)
                   .ThenInclude(customer => customer.CustomerRole)
                   .FirstOrDefaultAsync(contract => contract.Id == contractId));
        }
Beispiel #7
0
 /// <summary>
 /// Loads the list of denied objects.
 /// </summary>
 /// <returns>The list of denied page</returns>
 private IEnumerable <TModel> LoadDeniedObjects <TModel>() where TModel : IEntity, IAccessSecuredObject
 {
     return(repository
            .AsQueryable <TModel>()
            .Where(f => f.AccessRules.Any(b => b.AccessLevel == AccessLevel.Deny))
            .FetchMany(f => f.AccessRules)
            .ToList()
            .Distinct());
 }
        public virtual async Task <bool> IsInRoleAsync(TUser user, string roleName, CancellationToken cancellationToken)
        {
            var userRole = await _userRoles.AsQueryable().InnerJoin <TRole>((ur, r) => ur.RoleId == r.RoleId)
                           .Where(x => x.UserId == user.UserId)
                           .Where <TRole>(x => x.RoleName == roleName)
                           .SingleOrDefaultAsync(cancellationToken);

            return(userRole != null);
        }
 private static string[] FindUsersInRole(IRepository repository, string roleName, string userNameToMatch)
 {
     return(repository
            .AsQueryable <Models.UserRole>(userRole => userRole.Role.Name == roleName &&
                                           userRole.User.UserName.Contains(userNameToMatch))
            .Select(userRole => userRole.User.UserName)
            .Distinct()
            .ToArray());
 }
Beispiel #10
0
        /// <summary>
        /// Выполнение запроса.
        /// </summary>
        /// <param name="requestId">Идентификатор заявки.</param>
        /// <returns>Заявка.</returns>
        public async Task <Request> ExecuteAsync(int requestId)
        {
            IRepository <Request> repository = Uow.GetRepository <Request>();

            return(await repository.AsQueryable()
                   .Include(request => request.RequestCustomers)
                   .ThenInclude(customer => customer.CustomerRole)
                   .FirstOrDefaultAsync(request => request.Id == requestId));
        }
Beispiel #11
0
        public async Task <List <JobColumn> > GetColumns()
        {
            var columns = await repository
                          .AsQueryable()
                          .Include(x => x.JobItems)
                          .ToListAsync();

            return(columns.ToList());
        }
        public void GetDb2Person()
        {
            var rows = _db2PeronRep.AsQueryable().ToList();

            foreach (var rowItem in rows)
            {
                Console.WriteLine(JsonConvert.SerializeObject(rowItem));
            }
        }
Beispiel #13
0
        /// <summary>
        /// Получает массив этапов бизнес процессов документа по их идентификаторам.
        /// </summary>
        /// <param name="routeStageIds">Идентификаторы этапов бизнес процессов.</param>
        /// <returns>Массив этапов бизнес процесса документа.</returns>
        private async Task <DicRouteStage[]> GetRouteStagesByIds(IEnumerable <int> routeStageIds)
        {
            IRepository <DicRouteStage> dicRouteStageRepository = Uow.GetRepository <DicRouteStage>();

            return(await dicRouteStageRepository
                   .AsQueryable()
                   .Where(routeStage => routeStageIds.Contains(routeStage.Id))
                   .ToArrayAsync());
        }
Beispiel #14
0
        /// <summary>
        /// Получает массив всех доступных маршрутов документа по его текущему бизнес процессу.
        /// </summary>
        /// <param name="currentDocumentWorkflow">Текущий бизнес процесс документа.</param>
        /// <returns>Массив доступных маршрутов документа.</returns>
        private async Task <RouteStageOrder[]> GetAllNextRouteStageOrders(DocumentWorkflow currentDocumentWorkflow)
        {
            IRepository <RouteStageOrder> routeStageOrderRepository = Uow.GetRepository <RouteStageOrder>();

            return(await routeStageOrderRepository
                   .AsQueryable()
                   .Where(routeStageOrder => routeStageOrder.CurrentStageId == currentDocumentWorkflow.CurrentStageId && !routeStageOrder.IsAutomatic)
                   .ToArrayAsync());
        }
Beispiel #15
0
        private void SetWidgetOptions(EditWidgetViewModel model, Widget content, bool treatNullsAsLists, bool isNew)
        {
            if (model.Options != null)
            {
                content.ContentOptions = new List <ContentOption>();

                // NOTE: Loading custom options before saving.
                // In other case, when loading custom options from option service, nHibernate updates version number (nHibernate bug)
                var customOptionsIdentifiers = model.Options.Where(o => o.Type == OptionType.Custom).Select(o => o.CustomOption.Identifier).Distinct().ToArray();
                var customOptions            = optionService.GetCustomOptionsById(customOptionsIdentifiers);

                foreach (var requestContentOption in model.Options)
                {
                    var contentOption = new ContentOption
                    {
                        Content      = content,
                        Key          = requestContentOption.OptionKey,
                        DefaultValue =
                            optionService.ClearFixValueForSave(
                                requestContentOption.OptionKey,
                                requestContentOption.Type,
                                requestContentOption.OptionDefaultValue),
                        Type         = requestContentOption.Type,
                        CustomOption =
                            requestContentOption.Type == OptionType.Custom
                                                    ? repository.AsProxy <CustomOption>(customOptions.First(o => o.Identifier == requestContentOption.CustomOption.Identifier).Id)
                                                    : null
                    };

                    optionService.ValidateOptionValue(contentOption);

                    content.ContentOptions.Add(contentOption);
                }
            }
            else if (!treatNullsAsLists)
            {
                // When calling from API with null list, options should be loaded before process
                // Null from API means, that list should be kept unchanged
                content.ContentOptions = repository
                                         .AsQueryable <ContentOption>(pco => pco.Content.Id == model.Id)
                                         .Fetch(pco => pco.CustomOption)
                                         .ToList();
            }
        }
Beispiel #16
0
        /// <summary>
        /// Gets the view model for rendering widget preview.
        /// </summary>
        /// <param name="contentId">The content id.</param>
        /// <param name="user">The user.</param>
        /// <returns>
        /// View model for rendering widget preview
        /// </returns>
        public RenderPageViewModel GetContentPreviewViewModel(Guid contentId, IPrincipal user, bool allowJavaScript)
        {
            // Creating fake region.
            var regionGuid = new Guid(regionId);
            var region     = new Region {
                Id = regionGuid, RegionIdentifier = regionIdentifier
            };
            var regionViewModel = new PageRegionViewModel {
                RegionId = regionGuid, RegionIdentifier = regionIdentifier
            };

            // Creating fake page content and loading it's children.
            var pageContent = new PageContent
            {
                Options = new List <PageContentOption>(),
                Region  = region
            };

            pageContent.Content = repository
                                  .AsQueryable <ContentEntity>(c => c.Id == contentId)
                                  .FetchMany(f => f.ContentOptions)
                                  .ToList()
                                  .FirstOrDefault();

            if (pageContent.Content != null)
            {
                DemandAccess(user, RootModuleConstants.UserRoles.EditContent, RootModuleConstants.UserRoles.PublishContent);
            }

            var options = optionService.GetMergedOptionValues(pageContent.Content.ContentOptions, pageContent.Options);

            var contentProjection = pageContentProjectionFactory.Create(pageContent, pageContent.Content, options);

            var pageViewModel = new RenderPageViewModel
            {
                Contents = new List <PageContentProjection> {
                    contentProjection
                },
                Stylesheets = new List <IStylesheetAccessor> {
                    contentProjection
                },
                Regions = new List <PageRegionViewModel> {
                    regionViewModel
                },
                AreRegionsEditable = true
            };

            if (allowJavaScript)
            {
                pageViewModel.JavaScripts = new List <IJavaScriptAccessor> {
                    contentProjection
                };
            }

            return(pageViewModel);
        }
Beispiel #17
0
        /// <summary>
        /// Gets current page by given virtual path.
        /// </summary>
        /// <param name="virtualPath"></param>
        /// <returns>
        /// Current page object by given virtual path.
        /// </returns>
        public IPage GetPageByVirtualPath(string virtualPath)
        {
            if (temporaryPageCache.ContainsKey(virtualPath.ToLowerInvariant()))
            {
                return(temporaryPageCache[virtualPath.ToLowerInvariant()]);
            }

            var page = repository
                       .AsQueryable <PageProperties>(p => p.PageUrl == virtualPath)
                       .Fetch(p => p.Layout)
                       .FirstOrDefault();

            if (page != null)
            {
                temporaryPageCache.Add(virtualPath.ToLowerInvariant(), page);
            }

            return(page);
        }
Beispiel #18
0
        public async Task StoreAsync(PersistedGrant grant)
        {
            var existing = await _persistedGrantRepository.AsQueryable().FirstOrDefaultAsync(x => x.Key == grant.Key).ConfigureAwait(false);

            if (existing == null)
            {
                _logger.LogDebug("{persistedGrantKey} not found in database", grant.Key);

                var persistedGrant = _mapper.Map <Entities.PersistedGrant>(grant);
                await _persistedGrantRepository.AddAsync(persistedGrant).ConfigureAwait(false);
            }
            else
            {
                _logger.LogDebug("{persistedGrantKey} found in database", grant.Key);

                var persistedGrant = _mapper.Map(grant, existing);
                await _persistedGrantRepository.UpdateAsync(persistedGrant).ConfigureAwait(false);
            }
        }
        public void CollectChildContents(string html, Models.Content content)
        {
            var widgetModels = ChildContentRenderHelper.ParseWidgetsFromHtml(html, true);

            if (widgetModels != null && widgetModels.Count > 0)
            {
                // Validate widget ids
                var widgetIds = widgetModels.Select(w => w.WidgetId).Distinct().ToArray();
                var widgets   = repository.AsQueryable <Models.Content>(c => widgetIds.Contains(c.Id)).Select(c => c.Id).ToList();
                widgetIds.Where(id => widgets.All(dbId => dbId != id)).ToList().ForEach(
                    id =>
                {
                    var message    = RootGlobalization.ChildContent_WidgetNotFound_ById;
                    var logMessage = string.Format("{0} Id: {1}", message, id);
                    throw new ValidationException(() => message, logMessage);
                });

                // Validate child content
                var group = widgetModels.GroupBy(w => w.AssignmentIdentifier).FirstOrDefault(g => g.Count() > 1);
                if (group != null)
                {
                    var message = string.Format(RootGlobalization.ChildContent_AssignmentAlreadyAdded, group.First().AssignmentIdentifier);
                    throw new ValidationException(() => message, message);
                }

                foreach (var model in widgetModels)
                {
                    // Add child content only if it's not added yet (for example, it may be added when restoring / cloning a content)
                    if (content.ChildContents.All(cc => cc.AssignmentIdentifier != model.AssignmentIdentifier))
                    {
                        // Create child content
                        var childContent = new ChildContent
                        {
                            Id     = Guid.NewGuid(),
                            Child  = repository.AsProxy <Models.Content>(model.WidgetId),
                            Parent = content,
                            AssignmentIdentifier = model.AssignmentIdentifier
                        };
                        content.ChildContents.Add(childContent);
                    }
                }
            }
        }
        public ActionResult Index()
        {
            ViewBag.Message = _testService.GotIt("test");

            var userTest = _userRepository.AsQueryable().FirstOrDefault(x => x.UserId == 1);

            ViewBag.Username = userTest.UserName;

            return(View());
        }
Beispiel #21
0
        /// <summary>
        ///     带条件查询所有
        /// </summary>
        public async Task <List <DepartmentEntity> > GetList(DepartmentListParam param)
        {
            #region 查询条件

            var query = _departmentEntityDB.AsQueryable();

            /*
             * // 部门名称
             * if (!string.IsNullOrEmpty(param.DepartmentName))
             *  query = query.Where(p => p.DepartmentName.Contains(param.DepartmentName));
             *
             */

            #endregion

            var data = await query.ToListAsync();

            return(data);
        }
Beispiel #22
0
        public static async Task <User> UserByEmailAsync(this IRepository repository, string email)
        {
            var result =
                await
                repository
                .AsQueryable <User>()
                .FirstOrDefaultAsync(x => x.Email.Equals(email, StringComparison.OrdinalIgnoreCase));

            return(result);
        }
Beispiel #23
0
        public static async Task <User> UserByUsernameAsync(this IRepository repository, string username)
        {
            var result =
                await
                repository
                .AsQueryable <User>()
                .FirstOrDefaultAsync(x => x.Username.Equals(username, StringComparison.OrdinalIgnoreCase));

            return(result);
        }
        // linq syntax: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
        public static async Task <User> GetUserById(this IRepository <User> repository, long id)
        {
            var result =
                await repository
                .AsQueryable()
                .OfType <User>()
                .SingleOrDefaultAsync(x => x.Id == id);

            return(result);
        }
Beispiel #25
0
        public async Task <List <Department> > Execute()
        {
            // validations
            await ValidateInput();

            return(await departmentRepository.AsQueryable()
                   .OrderBy(d => d.Name)
                   .AsNoTracking()
                   .ToListAsync());
        }
        public static async Task <User> GetUserByEmailAsync(this IRepository <User> repository, string email)
        {
            var result =
                await repository
                .AsQueryable()
                .OfType <User>()
                .SingleOrDefaultAsync(x => x.Email.ToLower() == email.ToLower());

            return(result);
        }
        public static async Task <bool> UserExistsByUsernameOrEmail(this IRepository <User> repository, string username, string email)
        {
            var result =
                await repository
                .AsQueryable()
                .OfType <User>()
                .AnyAsync(x => x.Username == username || x.Email.ToLower() == email.ToLower());

            return(result);
        }
Beispiel #28
0
        // linq syntax: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
        public static async Task <List <Course> > GetCoursesAsync(this IRepository <Course> repository)
        {
            var result =
                await repository
                .AsQueryable()
                .OfType <Course>()
                .ToListAsync();

            return(result);
        }
Beispiel #29
0
        public static async Task <bool> CourseExistsByNameOrCodeAsync(this IRepository <Course> repository, string name, string code)
        {
            var result =
                await repository
                .AsQueryable()
                .OfType <Course>()
                .AnyAsync(x => x.Name == name || x.Code == code);

            return(result);
        }
        public async Task <ActionResult> SearchArticle(Articles articles)
        {
            var response = repository.AsQueryable()
                           .Where(x => x.Title == articles.Title ||
                                  x.WriterName == articles.WriterName ||
                                  x.WriterSurname == articles.WriterSurname ||
                                  x.Content.Equals(articles.Content)).ToList();

            return(Ok(response));
        }
Beispiel #31
0
        public static async Task <Role> RoleByNameAsync(this IRepository repository, string name)
        {
            var result =
                await
                repository
                .AsQueryable <Role>()
                .FirstOrDefaultAsync(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));

            return(result);
        }
Beispiel #32
0
 protected override bool ExecuteWithData(string cmd, IRepository repo, Player player)
 {
     var preName = cmd.Split(new[] {' '}, 2);
     var name = preName[1].Split('=')[0].Trim();
     var destinationName = cmd.Split('=')[1].Trim();
     var destination = repo.AsQueryable<GameObject>()
         .OfType<Room>().FirstOrDefault(m => m.Name == destinationName);
     var exit = new Exit() { Name = name.Trim(), Destination = destination, Location = player.Location };
     repo.Add(exit);
     console.WriteLine("Exit created");
     return true;
 }
Beispiel #33
0
 public Room GetMapRoom(IRepository repo)
 {
     var mapRoom = repo.AsQueryable<GameObject>().OfType<Room>().FirstOrDefault(m => m.Name == "MapRoom");
     if (mapRoom == null)
     {
         mapRoom = new Room();
         mapRoom.Name = "The Map Room";
         repo.Add(mapRoom);
         repo.UnitOfWork.SaveChanges();
     }
     return mapRoom;
 }
 private static IQueryable<OptionModel> GetWidgetOptionsQuery(IRepository repository, Guid widgetId)
 {
     return repository
         .AsQueryable<ContentOption>(o => o.Content.Id == widgetId)
         .Select(o => new OptionModel
             {
                 Key = o.Key,
                 DefaultValue = o.DefaultValue,
                 Type = (OptionType)(int)o.Type,
                 CustomTypeIdentifier = o.CustomOption != null ? o.CustomOption.Identifier : null
             });
 }
Beispiel #35
0
 public Player GetPlayer(IRepository repo)
 {
     var player = repo.AsQueryable<GameObject>().OfType<Player>().FirstOrDefault();
     if (player == null)
     {
         player = new Player();
         player.Location = GetMapRoom(repo);
         player.Aliases.Add(new Tag { Value = "Me" });
         player.Aliases.Add(new Tag { Value = "Player" });
         repo.Add(player);
         repo.UnitOfWork.SaveChanges();
     }
     return player;
 }
Beispiel #36
0
 public static IEnumerable<PageData> GetPagesToFuture(bool enableMultilanguage, IRepository repository)
 {
     return enableMultilanguage ? repository
         .AsQueryable<Root.Models.Page>()
         .Select(p => new PageData
         {
             Id = p.Id,
             Title = p.Title,
             Url = p.PageUrl,
             LanguageId = p.Language != null ? p.Language.Id : Guid.Empty,
             LanguageGroupIdentifier = p.LanguageGroupIdentifier,
             IsPublished = p.Status == PageStatus.Published
         })
         .ToFuture() : null;
 }
Beispiel #37
0
        protected override bool ExecuteWithData(string cmd, IRepository repo, Player player)
        {
            var parameters = cmd.Split(new[] { ' ' }, 2)[1];
            bool addStatus = parameters.Contains("+=");

            string splitVal;
            if (addStatus) splitVal = "+=";
            else splitVal = "-=";

            var goName = parameters.Split(new[] { splitVal }, StringSplitOptions.None)[0];
            var statusName = parameters.Split(new[] { splitVal }, StringSplitOptions.None)[1];

            var go = queries.FindNearPlayer(repo, player, goName);
            if (go == null)
            {
                formatters.OfType<NotFoundFormatter>().First().Format(go);
                return false;
            }
            else
            {
                var alias = repo.AsQueryable<Tag>().FirstOrDefault(m => m.Value == statusName);

                if (addStatus)
                {
                    if (alias == null)
                    {
                        alias = new Tag { Value = statusName };
                        repo.Add(alias);
                        console.WriteLine("Status created.");
                    }
                    go.Statuses.Add(alias);
                    console.WriteLine("Status added.");
                }
                else
                {
                    if (alias == null)
                    {
                        console.WriteLine("That status does not exist");
                    }
                    else
                    {
                        go.Statuses.Remove(alias);
                        console.WriteLine("Status removed.");
                    }
                }
                return true;
            }
        }
Beispiel #38
0
        public void Execute(string input)
        {
            string Output = GetAllButFirstWord(input);

              using (repository = repoFactory())
              {
                  var pObj = repository.AsQueryable().First(qq => qq.GameObjectId == player.Id);
                  var WhichExit = pObj.Location.Inventory.FirstOrDefault(qq => (qq.Name.Equals
                      (Output, StringComparison.CurrentCultureIgnoreCase)) && qq.Type=="Exit");
                  if (WhichExit != null)
                  {
                      pObj.Location = WhichExit.DestinationLocation;
                  }
                  format.Output(pObj.Location);
              }
        }
Beispiel #39
0
 public bool IsValid(string input)
 {
     string InputHolder = input;
     if  (((IsFirstWord(InputHolder, "move")) || (IsFirstWord(InputHolder, "go"))))
     {
         InputHolder = GetAllButFirstWord(input);
     }
     using (repository = repoFactory())
     {
         var pObj = repository.AsQueryable().First(qq => qq.GameObjectId == player.Id);
         var exit = pObj.Location.Inventory.Where(qq => qq.Type == "Exit").
             FirstOrDefault(qq => qq.ExitAliases.Any(ww => ww.Alais.Equals(InputHolder, StringComparison.CurrentCultureIgnoreCase))
                 || qq.Name.Equals(InputHolder, StringComparison.CurrentCultureIgnoreCase));
         return exit != null;
     }
 }
Beispiel #40
0
 private static IQueryable<OptionModel> GetWidgetOptionsQuery(IRepository repository, Guid widgetId)
 {
     return repository
         .AsQueryable<ContentOption>(o => o.Content.Id == widgetId)
         .Select(o => new OptionModel
             {
                 Key = o.Key,
                 DefaultValue = o.DefaultValue,
                 Type = (OptionType)(int)o.Type,
                 CustomTypeIdentifier = o.CustomOption != null ? o.CustomOption.Identifier : null,
                 Translations = o.Translations.Select(x => new OptionTranslationModel
                 {
                     LanguageId = x.Language.Id.ToString(),
                     Value = x.Value
                 }).ToList()
             });
 }
Beispiel #41
0
 protected override bool ExecuteWithData(string cmd, IRepository repo, Player player)
 {
     var preName = cmd.Split(new[] { ' ' }, 2);
     var name = preName[1].Split('.')[0];
     var preOpType = preName[1].Split(new[] { '.' }, 2);
     var opType = preOpType[1].Split('=')[0];
     var fieldInput = cmd.Split('=')[1].Trim();
     var go = goQueries.GetGameObjectByNameAndPlayerLocation(repo, name, player);
     if (opType == "+" && go != null)
     {
         var fieldTag = repo.AsQueryable<Tag>().FirstOrDefault(m => m.Value == fieldInput);
         if (fieldTag == null)
         {
             fieldTag = new Tag();
             fieldTag.Value = fieldInput;
         }
         go.Aliases.Add(fieldTag);
         console.WriteLine("Alias set!");
         return true;
     }
     else
     {
         if (go == null)
         {
             console.Write("I don't recognize: ");
             console.WriteLine(name);
             return false;
         }
         else
         {
             if (opType == "-")
             {
                 var fieldTag = go.Aliases.FirstOrDefault(m => m.Value == fieldInput);
                 go.Aliases.Remove(fieldTag);
                 console.WriteLine("Alias removed!");
                 return true;
             }
             else
             {
                 console.Write("I don't recognize: ");
                 console.WriteLine(opType);
                 return false;
             }
         }
     }
 }
        private static IQueryable<RegionModel> GetLayoutRegionsQuery(IRepository repository, Guid layoutId)
        {
            return repository
                .AsQueryable<LayoutRegion>(lr => lr.Layout.Id == layoutId && !lr.Layout.IsDeleted && lr.Region != null && !lr.Region.IsDeleted)
                .Select(lr => new RegionModel
                    {
                        Id = lr.Region.Id,
                        Version = lr.Region.Version,
                        CreatedBy = lr.CreatedByUser,
                        CreatedOn = lr.CreatedOn,
                        LastModifiedBy = lr.ModifiedByUser,
                        LastModifiedOn = lr.ModifiedOn,

                        RegionIdentifier = lr.Region.RegionIdentifier,
                        Description = lr.Description
                    });
        }
Beispiel #43
0
 protected override bool ExecuteWithData(string cmd, IRepository repo, Player player)
 {
     var locationName = cmd.Split(new[] { ' ' }, 2)[1];
     var location = repo.AsQueryable<GameObject>()
         .OfType<Room>().FirstOrDefault(m => m.Name == locationName);
     if (player.Location == location)
     {
         console.WriteLine("Really!? You are already there!");
         return false;
     }
     else
     {
         player.Location = location;
         console.Write("You have teleported to: ");
         console.WriteLine(player.Location.Name);
         return true;
     }
 }
        private static IQueryable<OptionValueModel> GetPageContentOptionsQuery(IRepository repository, Guid pageContentId, IOptionService optionService)
        {
            var pageContent = repository
                .AsQueryable<PageContent>()
                .Where(f => f.Id == pageContentId && !f.IsDeleted && !f.Content.IsDeleted)
                .Fetch(f => f.Content).ThenFetchMany(f => f.ContentOptions)
                .FetchMany(f => f.Options)
                .ToList()
                .FirstOne();

            return optionService
                .GetMergedOptionValuesForEdit(pageContent.Content.ContentOptions, pageContent.Options)
                .Select(o => new OptionValueModel
                    {
                        Key = o.OptionKey,
                        Value = o.OptionValue,
                        DefaultValue = o.OptionDefaultValue,
                        Type = ((Root.OptionType)(int)o.Type),
                        UseDefaultValue = o.UseDefaultValue,
                        CustomTypeIdentifier = o.CustomOption != null ? o.CustomOption.Identifier : null
                    }).AsQueryable();
        }
        /// <summary>
        /// Gets the titles for values.
        /// </summary>
        /// <param name="values">The values.</param>
        /// <param name="repository">The repository.</param>
        /// <returns>
        /// The dictionary with value - title pairs
        /// </returns>
        public Dictionary<string, string> GetTitlesForValues(string[] values, IRepository repository)
        {
            if (values == null || values.Length == 0)
            {
                return null;
            }

            var guids = new List<Guid>(values.Length);

            foreach (var value in values)
            {
                var guid = ConvertValueToCorrectType(value);
                if (guid != null)
                {
                    guids.Add((Guid)guid);
                }
            }

            Dictionary<string, string> result;
            if (guids.Count > 0)
            {
                result = repository
                    .AsQueryable<MediaFolder>()
                    .Where(a => guids.Contains(a.Id))
                    .Select(a => new { a.Id, a.Title })
                    .ToDictionary(a => a.Id.ToString(), a => a.Title);
            }
            else
            {
                result = new Dictionary<string, string>();
            }

            if (values.Any(string.IsNullOrEmpty))
            {
                result.Add(string.Empty, MediaGlobalization.RootFolder_Title);
            }

            return result;
        }
        private static IQueryable<OptionValueModel> GetPageContentOptionsQuery(IRepository repository, Guid pageContentId, IOptionService optionService)
        {
            var pageContent = repository
                .AsQueryable<PageContent>()
                .Where(f => f.Id == pageContentId && !f.IsDeleted && !f.Content.IsDeleted)
                .Fetch(f => f.Page).ThenFetch(f => f.Language)
                .Fetch(f => f.Content).ThenFetchMany(f => f.ContentOptions)
                .FetchMany(f => f.Options)
                .ToList()
                .FirstOne();

            var langId = pageContent.Page.Language != null ? pageContent.Page.Language.Id.ToString() : "";
            var mergedOptionValues = optionService.GetMergedOptionValuesForEdit(pageContent.Content.ContentOptions, pageContent.Options);

            foreach (var optionValue in mergedOptionValues)
            {
                if (optionValue.Translations != null)
                {
                    var translation = optionValue.Translations.FirstOrDefault(x => x.LanguageId == langId);
                    if (translation != null)
                    {
                        optionValue.OptionValue = optionValue.UseDefaultValue ? translation.OptionValue : optionValue.OptionValue;
                        optionValue.OptionDefaultValue = translation.OptionValue;
                    }
                }
            }

            return mergedOptionValues
                    .Select(o => new OptionValueModel
                        {
                            Key = o.OptionKey,
                            Value = o.OptionValue,
                            DefaultValue = o.OptionDefaultValue,
                            Type = ((Root.OptionType)(int)o.Type),
                            UseDefaultValue = o.UseDefaultValue,
                            CustomTypeIdentifier = o.CustomOption != null ? o.CustomOption.Identifier : null

                        }).AsQueryable();
        }
 public IEnumerable<IEntityCategory> QueryEntityCategories(IRepository repository, ICategory category)
 {
     return repository.AsQueryable<WidgetCategory>().Where(wc => wc.Category.Id == category.Id).ToFuture();
 }
 public IEnumerable<IEntityCategory> QueryEntityCategories(IRepository repository, ICategory category)
 {
     return repository.AsQueryable<PageCategory>().Where(p => p.Page is BlogPost && p.Category.Id == category.Id).ToFuture();
 }
Beispiel #49
0
 private static string[] GetUsersInRole(IRepository repository, string roleName)
 {
     return repository
         .AsQueryable<Models.UserRole>(userRole => userRole.Role.Name == roleName)
         .Select(userRole => userRole.User.UserName)
         .Distinct()
         .ToArray();
 }
Beispiel #50
0
        private static void RemoveUsersFromRoles(IRepository repository, IUnitOfWork unitOfWork, string[] userNames, string[] roleNames)
        {
            unitOfWork.BeginTransaction();

            var distinctRoleNames = roleNames.Distinct().ToList();
            var futureQueries = new List<IEnumerable<Models.Role>>();

            foreach (var userName in userNames.Distinct())
            {
                var futureQuery = repository
                    .AsQueryable<Models.UserRole>(userRole => userRole.User.UserName == userName
                        && distinctRoleNames.Contains(userRole.Role.Name))
                    .Select(userRole => new Models.Role
                        {
                            Id = userRole.Id,
                            Version = userRole.Version
                        })
                    .ToFuture();
                
                futureQueries.Add(futureQuery);
            }

            futureQueries.ForEach(futureQuery => 
                futureQuery.ToList().ForEach(role => 
                    repository.Delete<Models.UserRole>(role.Id, role.Version)));

            unitOfWork.Commit();
        }
Beispiel #51
0
        private static void AddUsersToRoles(IRepository repository, IUnitOfWork unitOfWork, string[] userNames, string[] roleNames)
        {
            unitOfWork.BeginTransaction();

            // Get roles future query
            var distinctRoleNames = roleNames.Distinct().ToArray();
            var roleIdsQuery = repository
                .AsQueryable<Models.Role>(role => distinctRoleNames.Contains(role.Name))
                .Select(role => new
                                    {
                                        Id = role.Id,
                                        Name = role.Name
                                    })
                .ToFuture();

            // Get users future query
            var distinctUserNames = userNames.Distinct().ToArray();
            var userIdsQuery = repository
                .AsQueryable<Models.User>(user => distinctUserNames.Contains(user.UserName))
                .Select(user => new
                                    {
                                        Id = user.Id,
                                        Name = user.UserName
                                    })
                .ToFuture();

            // Get already assigned roles
            var alreadyAssigned = repository
                .AsQueryable<Models.UserRole>(userRole => distinctUserNames.Contains(userRole.User.UserName))
                .Select(userRole => new
                                        {
                                            UserId = userRole.User.Id,
                                            RoleId = userRole.Role.Id
                                        })
                .ToFuture()
                .ToList();

            // Validate roles
            var roles = roleIdsQuery.ToList();
            roleNames
                .Where(roleName => roles.All(role => roleName != role.Name))
                .ForEach(roleName =>
                    { throw new ProviderException(string.Format("Role {0} does not exist.", roleName)); });

            // Validate users
            var users = userIdsQuery.ToList();
            userNames
                .Where(userName => users.All(user => userName != user.Name))
                .ForEach(userName =>
                    { throw new ProviderException(string.Format("User {0} does not exist.", userName)); });

            // Add users to roles
            roles
                .ForEach(role => users
                    .ForEach(user =>
                        {
                            if (!alreadyAssigned.Any(a => a.UserId == user.Id && a.RoleId == role.Id))
                            {
                                var userRole = new Models.UserRole
                                                   {
                                                       User = repository.AsProxy<Models.User>(user.Id),
                                                       Role = repository.AsProxy<Models.Role>(role.Id), 
                                                   };
                                repository.Save(userRole);
                            }
                        }));

            unitOfWork.Commit();
        }
Beispiel #52
0
 private static bool RoleExists(IRepository repository, string roleName)
 {
     return repository
         .AsQueryable<Models.Role>(role => role.Name == roleName)
         .Select(u => u.Name)
         .FirstOrDefault() != null;
 }
Beispiel #53
0
 private static bool IsUserInRole(IRepository repository, string username, string roleName)
 {
     return repository
         .AsQueryable<Models.User>(u => u.UserName == username
             && u.UserRoles.Any(ur => ur.Role.Name == roleName))
         .Select(u => u.UserName)
         .FirstOrDefault() != null;
 }
Beispiel #54
0
 private static string[] GetRolesForUser(IRepository repository, string username)
 {
     return repository
         .AsQueryable<Models.UserRole>(userRole => userRole.User.UserName == username)
         .Select(userRole => userRole.Role.Name)
         .Distinct()
         .ToArray();
 }
Beispiel #55
0
 private static string[] FindUsersInRole(IRepository repository, string roleName, string userNameToMatch)
 {
     return repository
         .AsQueryable<Models.UserRole>(userRole => userRole.Role.Name == roleName
             && userRole.User.UserName.Contains(userNameToMatch))
         .Select(userRole => userRole.User.UserName)
         .Distinct()
         .ToArray();
 }
 public IFutureValue<int> CheckIsUsed(IRepository repository, CategoryTree categoryTree)
 {
     return repository.AsQueryable<MediaCategory>().Where(m => m.Media is MediaFile && m.Category.CategoryTree == categoryTree && m.Media.Original == null).ToRowCountFutureValue();
 }
 public IEnumerable<IEntityCategory> QueryEntityCategories(IRepository repository, ICategory category)
 {
     return repository.AsQueryable<MediaCategory>().Where(m =>  m.Media is MediaFile && m.Category.Id == category.Id).ToFuture();
 }
 public IFutureValue<int> CheckIsUsed(IRepository repository, CategoryTree categoryTree)
 {
     var query = repository.AsQueryable<PageCategory>().Where(p => p.Page is BlogPost && p.Category.CategoryTree == categoryTree);
     return query.ToRowCountFutureValue();
 }
Beispiel #59
0
 private static string[] GetAllRoles(IRepository repository)
 {
     return repository.AsQueryable<Models.Role>().Select(r => r.Name).ToArray();
 }
 public IFutureValue<int> CheckIsUsed(IRepository repository, CategoryTree categoryTree)
 {
     var query = repository.AsQueryable<MediaCategory>().Where(mc => mc.Media is MediaImage && mc.Category.CategoryTree == categoryTree && mc.Media.Original == null);
     return query.ToRowCountFutureValue();
 }