예제 #1
0
        private string BuildWhere <TResult>(string sqlTemplate, Expression <Func <TResult, bool> > expression, out object arguments)
        {
            var queryArgments = LamdaHelper.GetWhere <TResult>(expression);
            //  Dictionary<string, object> dic = new Dictionary<string, object>();
            dynamic args = new ExpandoObject();

            StringBuilder where = new StringBuilder();
            // where.Append("where ");
            // object arguments = new object();
            string template = "{TableAlias}.{ColumnName} {Operator} @{ArgumentName} {Link} ";

            foreach (QueryArgument argument in queryArgments)
            {
                ((IDictionary <string, object>)args)[argument.Name] = argument.Value;
                string temp = template.Replace("{TableAlias}", aliasDic[argument.EntityType]);
                temp = temp.Replace("{ColumnName}", _dialectBuilder.GetColumn(argument.Name));
                temp = temp.Replace("{Operator}", argument.Operator);
                temp = temp.Replace("{ArgumentName}", argument.ArgumentName);
                temp = temp.Replace("{Link}", argument.Link);
                where.Append(temp);
            }
            arguments = args;

            sqlTemplate = sqlTemplate.Replace("{WhereClause}", where.ToString());
            return(sqlTemplate);
        }
        private async Task <WebApiPagedResponseDto <FileInfo> > GetVideosViewModel(string physicalPath, int page = 1, int pageSize = 40, string orderColumn = nameof(FileInfo.LastWriteTime), string orderType = OrderByType.Descending)
        {
            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            var repository = _fileSystemGenericRepositoryFactory.CreateFileRepository(cts.Token, physicalPath, true, "*.*", ".mp4", ".avi", ".txt");
            var dataTask   = repository.GetAllAsync(LamdaHelper.GetOrderByFunc <FileInfo>(orderColumn, orderType), (page - 1) * pageSize, pageSize);
            var totalTask  = repository.GetCountAsync(null);

            await TaskHelper.WhenAllOrException(cts, dataTask, totalTask);

            var data  = dataTask.Result;
            var total = totalTask.Result;

            var response = new WebApiPagedResponseDto <FileInfo>
            {
                Page        = page,
                PageSize    = pageSize,
                Records     = total,
                Rows        = data.ToList(),
                OrderColumn = orderColumn,
                OrderType   = orderType
            };

            return(response);
        }
        public async Task <IViewComponentResult> InvokeAsync()
        {
            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            IEnumerable <FaqDto> data = null;
            int total = 0;

            var dataTask  = Service.GetAllAsync(cts.Token, LamdaHelper.GetOrderBy <FaqDto>(nameof(FaqDto.DateCreated), "asc"), null, null, false, false, null);
            var totalTask = Service.GetCountAsync(cts.Token);

            await TaskHelper.WhenAllOrException(cts, dataTask, totalTask);

            data  = dataTask.Result;
            total = totalTask.Result;


            var response = new WebApiPagedResponseDto <FaqDto>
            {
                Page     = 1,
                PageSize = total,
                Records  = total,
                Rows     = data.ToList()
            };

            ViewBag.Page     = 1;
            ViewBag.PageSize = total;

            return(View(response));
        }
예제 #4
0
        public void TestWhere()
        {
            string value = "234" + "%";
            Expression <Func <Category, bool> > exp = n => n.Id.Like(value) && n.Level == 2;
            var result = LamdaHelper.GetWhere <Category>(exp);

            Assert.AreEqual("11", "11");
        }
예제 #5
0
        private static void MapCollection(object mappingExpression, Type sourceType, Type destinationType)
        {
            var equalityComparisonMethod = typeof(EquivalentExpressions).GetMethod(nameof(EquivalentExpressions.EqualityComparison)).MakeGenericMethod(sourceType, destinationType);
            var equivalentExpression     = LamdaHelper.SourceDestinationEquivalentExpressionById(sourceType, destinationType);

            equalityComparisonMethod.Invoke(null, new List <object>()
            {
                mappingExpression, equivalentExpression
            }.ToArray());
        }
        public virtual async Task <ActionResult> Index(int page = 1, int pageSize = 10, string orderColumn = nameof(FileInfo.LastWriteTime), string orderType = "desc", string search = "")
        {
            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            try
            {
                var repository = FileSystemGenericRepositoryFactory.CreateFileRepositoryReadOnly(cts.Token, PhysicalPath, IncludeSubDirectories);
                var dataTask   = repository.SearchAsync(search, null, LamdaHelper.GetOrderByFunc <FileInfo>(orderColumn, orderType), (page - 1) * pageSize, pageSize);
                var totalTask  = repository.GetSearchCountAsync(search, null);

                await TaskHelper.WhenAllOrException(cts, dataTask, totalTask);

                var data  = dataTask.Result;
                var total = totalTask.Result;

                var rows = data.ToList().Select(Mapper.Map <FileInfo, FileMetadataDto>).ToList();

                foreach (FileMetadataDto dto in rows)
                {
                    dto.Id = dto.Id.Replace(PhysicalPath, "");
                }

                var response = new WebApiPagedResponseDto <FileMetadataDto>
                {
                    Page        = page,
                    PageSize    = pageSize,
                    Records     = total,
                    Rows        = rows,
                    OrderColumn = orderColumn,
                    OrderType   = orderType,
                    Search      = search
                };

                ViewBag.Search      = search;
                ViewBag.Page        = page;
                ViewBag.PageSize    = pageSize;
                ViewBag.OrderColumn = orderColumn;
                ViewBag.OrderType   = orderType;

                ViewBag.DisableCreate  = true;
                ViewBag.DisableSorting = true;
                ViewBag.DisableDelete  = false;

                ViewBag.PageTitle = Title;
                ViewBag.Admin     = Admin;
                return(View("List", response));
            }
            catch
            {
                return(HandleReadException());
            }
        }
예제 #7
0
        public void TestWhere_constraint()
        {
            Category cat = new Category()
            {
                Id       = "01",
                Name     = "shp",
                FullName = "222",
                Level    = 1
            };
            Expression <Func <Category, bool> > exp = n => n.Id.Like(cat.Id + "%") && n.Level == cat.Level;
            var result = LamdaHelper.GetWhere <Category>(exp);

            Assert.AreEqual("11", "11");
        }
        protected async override Task <IEnumerable <SelectListItem> > GetSelectListItemsAsync(SelectListContext context)
        {
            var dataValueField = nameof(FileInfo.FullName);

            if (!Path.EndsWith(@"\"))
            {
                Path = Path + @"\";
            }

            var hostingEnvironment = context.HttpContext.RequestServices.GetRequiredService <IHostingEnvironment>();
            var mappedWwwPath      = hostingEnvironment.MapWwwPath(Path);
            var mappedContentPath  = hostingEnvironment.MapContentPath(Path);

            var searchPath = Path;
            var root       = "";
            var webFolder  = false;

            if (mappedWwwPath != mappedContentPath)
            {
                searchPath = mappedContentPath;
                root       = hostingEnvironment.ContentRootPath + @"\";
                if (Directory.Exists(mappedWwwPath))
                {
                    webFolder  = true;
                    searchPath = mappedWwwPath;
                    root       = hostingEnvironment.WebRootPath + @"\";
                }
            }

            var repository = _fileSystemGenericRepositoryFactory.CreateFileRepositoryReadOnly(default(CancellationToken), searchPath, IncludeSubDirectories, SearchPattern);
            var data       = await repository.GetAllAsync(LamdaHelper.GetOrderByFunc <FileInfo>(OrderByProperty, OrderByType), null, null);

            var results = new List <SelectListItem>();

            foreach (var item in data)
            {
                IHtmlHelper html = context.CreateHtmlHelper((dynamic)item);

                results.Add(new ModelSelectListItem()
                {
                    Model = item,
                    Html  = html,
                    Text  = RemoveSearchPathFromText ? context.Eval(html, item, DataTextFieldExpression).Replace(searchPath, "") : context.Eval(html, item, DataTextFieldExpression),
                    Value = RootRelativeValue ? webFolder ? context.Eval(html, item, dataValueField).Replace(root, "").Replace(@"\", @"/") : context.Eval(html, item, dataValueField).Replace(root, "") : context.Eval(html, item, dataValueField),
                });
            }

            return(results);
        }
예제 #9
0
        private string BuildWhere <TEntity>(System.Linq.Expressions.Expression <Func <TEntity, bool> > expression, out object arguments)
        {
            var           queryArgments = LamdaHelper.GetWhere <TEntity>(expression);
            dynamic       args          = new ExpandoObject();
            StringBuilder sql           = new StringBuilder();

            foreach (QueryArgument argument in queryArgments)
            {
                ((IDictionary <string, object>)args)[argument.ArgumentName] = argument.Value;
                sql.AppendFormat("{0} {1} @{2} {3} ", this._dialectBuilder.GetColumn(argument.Name), argument.Operator, argument.ArgumentName, argument.Link);
            }
            arguments = args;

            return(sql.ToString().Trim());
        }
예제 #10
0
        public string BuildSelectByLamda <TEntity, TResult>(Expression <Func <TEntity, bool> > expression, out object arguments, Expression <Func <TEntity, TResult> > select, string function)
        {
            List <string> columnExpression = new List <string>();

            LamdaHelper.ParseColumn(select.Body, columnExpression, "");
            string columnNames = string.Format("{0}({1})", function, string.Join(" ", columnExpression).Trim());
            string table       = this._dialectBuilder.GetTable(typeof(TEntity));

            string where = "";
            if (expression != null)
            {
                where = string.Format("where {0}", BuildWhere <TEntity>(expression, out arguments));
            }
            else
            {
                arguments = new object();
            }
            string sql = string.Format("select {0} from {1} {2}", columnNames, table, where);

            return(sql);
        }
예제 #11
0
        public async Task <ActionResult> Index(int page = 1, int pageSize = 20, string orderColumn = nameof(DirectoryInfo.LastWriteTime), string orderType = "desc", string search = "")
        {
            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            try
            {
                var repository = _fileSystemGenericRepositoryFactory.CreateFolderRepository(cts.Token, Server.GetWwwFolderPhysicalPathById(Folders.Gallery));
                var dataTask   = repository.SearchAsync(search, null, LamdaHelper.GetOrderByFunc <DirectoryInfo>(orderColumn, orderType), (page - 1) * pageSize, pageSize);
                var totalTask  = repository.GetSearchCountAsync(search, null);

                await TaskHelper.WhenAllOrException(cts, dataTask, totalTask);

                var data  = dataTask.Result;
                var total = totalTask.Result;

                var response = new WebApiPagedResponseDto <DirectoryInfo>
                {
                    Page        = page,
                    PageSize    = pageSize,
                    Records     = total,
                    Rows        = data.ToList(),
                    OrderColumn = orderColumn,
                    OrderType   = orderType,
                    Search      = search
                };

                ViewBag.Search      = search;
                ViewBag.Page        = page;
                ViewBag.PageSize    = pageSize;
                ViewBag.OrderColumn = orderColumn;
                ViewBag.OrderType   = orderType;

                return(View(response));
            }
            catch
            {
                return(HandleReadException());
            }
        }
        public async Task <IViewComponentResult> InvokeAsync()
        {
            string orderColumn = nameof(TestimonialDto.DateCreated);
            string orderType   = OrderByType.Descending;

            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            IEnumerable <TestimonialDto> testimonials = null;

            var testimonialsTask = _testimonialService.GetAllAsync(cts.Token, LamdaHelper.GetOrderBy <TestimonialDto>(orderColumn, orderType), null, null);

            await TaskHelper.WhenAllOrException(cts, testimonialsTask);

            testimonials = testimonialsTask.Result;


            var viewModel = new TestimonialsViewModel
            {
                Testimonials = testimonials.ToList()
            };

            return(View(viewModel));
        }
예제 #13
0
        public async Task <ActionResult> Index(int page = 1, int pageSize = 100, string orderColumn = nameof(FileInfo.LastWriteTime), string orderType = "desc")
        {
            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            try
            {
                var repository = _fileSystemGenericRepositoryFactory.CreateFileRepository(cts.Token, Server.GetWwwFolderPhysicalPathById(Folders.BucketList), true, "*.*", ".jpg", ".jpeg", ".txt", ".mp4", ".avi");
                var dataTask   = repository.GetAllAsync(LamdaHelper.GetOrderByFunc <FileInfo>(orderColumn, orderType), (page - 1) * pageSize, pageSize);
                var totalTask  = repository.GetCountAsync(null);

                await TaskHelper.WhenAllOrException(cts, dataTask, totalTask);

                var data  = dataTask.Result;
                var total = totalTask.Result;

                var response = new WebApiPagedResponseDto <FileInfo>
                {
                    Page        = page,
                    PageSize    = pageSize,
                    Records     = total,
                    Rows        = data.ToList(),
                    OrderColumn = orderColumn,
                    OrderType   = orderType
                };

                ViewBag.Page        = page;
                ViewBag.PageSize    = pageSize;
                ViewBag.OrderColumn = orderColumn;
                ViewBag.OrderType   = orderType;

                return(View(response));
            }
            catch
            {
                return(HandleReadException());
            }
        }
        public async Task <IViewComponentResult> InvokeAsync()
        {
            string orderColumn = nameof(ProjectDto.DateCreated);
            string orderType   = "desc";

            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            IEnumerable <ProjectDto> projects = null;


            var projectsTask = _projectService.GetAllAsync(cts.Token, LamdaHelper.GetOrderBy <ProjectDto>(orderColumn, orderType), null, null);

            await TaskHelper.WhenAllOrException(cts, projectsTask);

            projects = projectsTask.Result;


            var viewModel = new ProjectsViewModel
            {
                Projects = projects.ToList()
            };

            return(View(viewModel));
        }
예제 #15
0
        public async Task <IViewComponentResult> InvokeAsync()
        {
            string orderColumn = nameof(CarouselItemDto.DateCreated);
            string orderType   = OrderByType.Descending;

            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            IEnumerable <BlogPostDto>     posts = null;
            IList <CarouselItemDto>       carouselItemsFinal = new List <CarouselItemDto>();
            IEnumerable <CarouselItemDto> carouselItems      = null;

            IList <DirectoryInfo>   albums             = new List <DirectoryInfo>();
            IList <CarouselItemDto> albumCarouselItems = new List <CarouselItemDto>();


            var postsTask         = _blogService.BlogPostApplicationService.GetPostsForCarouselAsync(0, 3, cts.Token);
            var carouselItemsTask = _carouselItemService.GetAsync(cts.Token, c => c.Published, LamdaHelper.GetOrderBy <CarouselItemDto>(orderColumn, orderType), null, null);

            await TaskHelper.WhenAllOrException(cts, postsTask, carouselItemsTask);

            posts         = postsTask.Result;
            carouselItems = carouselItemsTask.Result;

            var repository = _fileSystemRepository.CreateFolderRepositoryReadOnly(cts.Token, Server.GetWwwFolderPhysicalPathById(Folders.Gallery));

            foreach (CarouselItemDto item in carouselItems)
            {
                if (!string.IsNullOrEmpty(item.Album))
                {
                    var album = repository.GetByPath(item.Album);
                    if (album != null)
                    {
                        albums.Add(album);
                        albumCarouselItems.Add(item);
                    }
                }
                else
                {
                    carouselItemsFinal.Add(item);
                }
            }

            var carouselViewModel = new CarouselViewModel
            {
                Posts = posts.ToList(),

                Albums             = albums.ToList(),
                AlbumCarouselItems = albumCarouselItems.ToList(),

                CarouselItems = carouselItemsFinal.ToList(),
                ItemCount     = posts.Count() + albums.Count() + carouselItemsFinal.Count()
            };

            return(View(carouselViewModel));
        }
        protected async override Task <IList <SitemapNode> > GetSitemapNodes(CancellationToken cancellationToken)
        {
            IList <SitemapNode> nodes = await base.GetSitemapNodes(cancellationToken);

            //Locations
            nodes.Add(
                new SitemapNode()
            {
                Url      = Url.AbsoluteUrl <LocationsController>(c => c.Index(1, 20, nameof(LocationDto.Name), "asc", ""), false),
                Priority = 0.9
            });

            //countries
            nodes.Add(
                new SitemapNode()
            {
                Url      = Url.AbsoluteUrl <CountriesController>(c => c.Index(1, 20, nameof(LocationDto.Name), "asc", ""), false),
                Priority = 0.9
            });

            foreach (TagDto t in (await _blogService.TagApplicationService.GetAllAsync(cancellationToken, null, null, null)))
            {
                nodes.Add(
                    new SitemapNode()
                {
                    Url       = Url.AbsoluteUrl(nameof(BlogController.Tag), "Blog", new { tagSlug = t.UrlSlug }),
                    Frequency = SitemapFrequency.Weekly,
                    Priority  = 0.8
                });
            }

            foreach (CategoryDto c in (await _blogService.CategoryApplicationService.GetAsync(cancellationToken, c => c.Published, null, null)))
            {
                nodes.Add(
                    new SitemapNode()
                {
                    Url       = Url.AbsoluteUrl(nameof(BlogController.Category), "Blog", new { categorySlug = c.UrlSlug }),
                    Frequency = SitemapFrequency.Weekly,
                    Priority  = 0.8
                });
            }

            foreach (BlogPostDto p in (await _blogService.BlogPostApplicationService.GetPostsAsync(0, 200, cancellationToken)))
            {
                nodes.Add(
                    new SitemapNode()
                {
                    Url       = Url.AbsoluteUrl <BlogController>(c => c.Post(p.DateCreated.Year, p.DateCreated.Month, p.UrlSlug)),
                    Frequency = SitemapFrequency.Weekly,
                    Priority  = 0.7
                });
            }

            var repository = _fileSystemGenericRepositoryFactory.CreateFolderRepository(cancellationToken, Server.GetWwwFolderPhysicalPathById(Folders.Gallery));

            foreach (DirectoryInfo f in (await repository.GetAllAsync(LamdaHelper.GetOrderByFunc <DirectoryInfo>(nameof(DirectoryInfo.LastWriteTime), OrderByType.Descending), null, null)))
            {
                nodes.Add(
                    new SitemapNode()
                {
                    Url       = Url.AbsoluteUrl("Gallery", "Gallery", new { name = f.Name.ToSlug() }),
                    Frequency = SitemapFrequency.Weekly,
                    Priority  = 0.7
                });
            }

            foreach (LocationDto l in (await _locationService.GetAllAsync(cancellationToken, null, null, null)))
            {
                if (!string.IsNullOrEmpty(l.UrlSlug))
                {
                    nodes.Add(
                        new SitemapNode()
                    {
                        Url       = Url.AbsoluteUrl <LocationsController>(lc => lc.Location(l.UrlSlug)),
                        Frequency = SitemapFrequency.Weekly,
                        Priority  = 0.6
                    });
                }
            }

            return(nodes);
        }
        public static IList <SelectListItem> GetSelectListFromDatabase <TDbContext>(this IHtmlHelper <dynamic> htmlHelper, string propertyName, bool selectedOnly = false) where TDbContext : DbContext
        {
            var modelExplorer = ExpressionMetadataProvider.FromStringExpression(propertyName, htmlHelper.ViewData, htmlHelper.MetadataProvider);

            Microsoft.AspNetCore.Mvc.ModelBinding.ModelMetadata metadata = modelExplorer.Metadata;

            var dropdownModelType = ((Type)metadata.AdditionalValues["DropdownModelType"]);
            var keyProperty       = ((string)metadata.AdditionalValues["KeyProperty"]);
            var valueProperty     = ((string)metadata.AdditionalValues["DisplayExpression"]);
            var bindingProperty   = ((string)metadata.AdditionalValues["BindingProperty"]);

            var orderByProperty = ((string)metadata.AdditionalValues["OrderByProperty"]);
            var orderByType     = ((string)metadata.AdditionalValues["OrderByType"]);

            var physicalFilePath = ((string)metadata.AdditionalValues["PhysicalFilePath"]);
            var fileFolderId     = ((string)metadata.AdditionalValues["FileFolderId"]);

            if (!string.IsNullOrEmpty(fileFolderId))
            {
                physicalFilePath = Server.GetWwwFolderPhysicalPathById(fileFolderId);
            }
            var physicalFolderPath = ((string)metadata.AdditionalValues["PhysicalFolderPath"]);
            var folderFolderId     = ((string)metadata.AdditionalValues["FolderFolderId"]);

            if (!string.IsNullOrEmpty(folderFolderId))
            {
                physicalFolderPath = Server.GetWwwFolderPhysicalPathById(folderFolderId);
            }

            var nullable = ((bool)metadata.AdditionalValues["Nullable"]);

            var options = ((IEnumerable <string>)metadata.AdditionalValues["Options"]);

            Type propertyType           = GetNonNullableModelType(metadata);
            List <SelectListItem> items = new List <SelectListItem>();
            List <string>         ids   = new List <string>();

            if (propertyType != typeof(string) && (propertyType.GetInterfaces().Contains(typeof(IEnumerable))))
            {
                if (modelExplorer.Model != null)
                {
                    foreach (var val in (IEnumerable)modelExplorer.Model)
                    {
                        if (val != null)
                        {
                            if (!string.IsNullOrWhiteSpace(bindingProperty))
                            {
                                ids.Add(val.GetPropValue(bindingProperty).ToString());
                            }
                            else
                            {
                                ids.Add(val.ToString());
                            }
                        }
                    }
                }
            }
            else
            {
                if (modelExplorer.Model != null)
                {
                    if (!string.IsNullOrWhiteSpace(bindingProperty))
                    {
                        ids.Add(modelExplorer.Model.GetPropValue(bindingProperty).ToString());
                    }
                    else
                    {
                        ids.Add(modelExplorer.Model.ToString());
                    }
                }
            }

            if (!string.IsNullOrEmpty(physicalFolderPath))
            {
                var repository = htmlHelper.FileSystemGenericRepositoryFactory().CreateFolderRepositoryReadOnly(default(CancellationToken), physicalFolderPath, true);
                var data       = repository.GetAll(LamdaHelper.GetOrderByFunc <DirectoryInfo>(orderByProperty, orderByType), null, null);
                keyProperty = nameof(DirectoryInfo.FullName);

                data.ToList().ForEach(item =>

                                      items.Add(new SelectListItem()
                {
                    Text     = GetDisplayString(htmlHelper, item, valueProperty).Replace(physicalFolderPath, ""),
                    Value    = item.GetPropValue(nameof(DirectoryInfo.FullName)) != null ? item.GetPropValue(nameof(DirectoryInfo.FullName)).ToString().Replace(physicalFolderPath, "") : "",
                    Selected = item.GetPropValue(keyProperty) != null && ids.Contains(item.GetPropValue(keyProperty).ToString().Replace(physicalFolderPath, ""))
                }));
            }
            else if (!string.IsNullOrEmpty(physicalFilePath))
            {
                var repository = htmlHelper.FileSystemGenericRepositoryFactory().CreateFileRepositoryReadOnly(default(CancellationToken), physicalFilePath, true);
                var data       = repository.GetAll(LamdaHelper.GetOrderByFunc <FileInfo>(orderByProperty, orderByType), null, null);
                keyProperty = nameof(FileInfo.FullName);

                data.ToList().ForEach(item =>

                                      items.Add(new SelectListItem()
                {
                    Text     = GetDisplayString(htmlHelper, item, valueProperty),
                    Value    = item.GetPropValue(keyProperty) != null ? item.GetPropValue(keyProperty).ToString().Replace(physicalFilePath, "") : "",
                    Selected = item.GetPropValue(keyProperty) != null && ids.Contains(item.GetPropValue(keyProperty).ToString().Replace(physicalFilePath, ""))
                }));
            }
            else if (metadata.DataTypeName == "ModelRepeater")
            {
                foreach (var item in htmlHelper.ViewData.Model)
                {
                    var itemObject = (Object)item;

                    items.Add(new SelectListItem()
                    {
                        Text     = GetDisplayString(htmlHelper, item, valueProperty),
                        Value    = itemObject.GetPropValue(keyProperty) != null ? itemObject.GetPropValue(keyProperty).ToString() : "",
                        Selected = itemObject.GetPropValue(keyProperty) != null && ids.Contains(itemObject.GetPropValue(keyProperty).ToString())
                    });
                }
            }
            else
            {
                //db
                if (options == null)
                {
                    using (var db = htmlHelper.DatabaseByEntityType(dropdownModelType))
                    {
                        var pi = dropdownModelType.GetProperty(orderByProperty);

                        Type iQueryableType = typeof(IQueryable <>).MakeGenericType(new[] { dropdownModelType });

                        IQueryable query = db.Queryable(dropdownModelType);

                        if (selectedOnly)
                        {
                            var whereClause = LamdaHelper.SearchForEntityByIds(dropdownModelType, ids.Cast <Object>());
                            query = (IQueryable)typeof(LamdaHelper).GetMethod(nameof(LamdaHelper.Where)).MakeGenericMethod(dropdownModelType).Invoke(null, new object[] { query, whereClause });
                        }
                        else
                        {
                            if (metadata.AdditionalValues.ContainsKey("WhereClauseEqualsDictionary"))
                            {
                                var whereClauseEqualsDictionary = (Dictionary <string, List <object> >)metadata.AdditionalValues["WhereClauseEqualsDictionary"];
                                foreach (var where in whereClauseEqualsDictionary)
                                {
                                    var whereClause = LamdaHelper.SearchForEntityByProperty(dropdownModelType, where.Key, where.Value);
                                    query = (IQueryable)typeof(LamdaHelper).GetMethod(nameof(LamdaHelper.Where)).MakeGenericMethod(dropdownModelType).Invoke(null, new object[] { query, whereClause });
                                }
                            }

                            if (!string.IsNullOrWhiteSpace(orderByProperty))
                            {
                                if (orderByType == "asc")
                                {
                                    query = (IQueryable)typeof(Utilities).GetMethod(nameof(Utilities.QueryableOrderBy)).MakeGenericMethod(dropdownModelType).Invoke(null, new object[] { query, orderByProperty, true });
                                }
                                else
                                {
                                    query = (IQueryable)typeof(Utilities).GetMethod(nameof(Utilities.QueryableOrderBy)).MakeGenericMethod(dropdownModelType).Invoke(null, new object[] { query, orderByProperty, false });
                                }
                            }
                        }

                        IEnumerable results = query.ToList(dropdownModelType);

                        foreach (var item in results)
                        {
                            items.Add(new SelectListItem()
                            {
                                Text = GetDisplayString(htmlHelper, item, valueProperty),
                                //Value = item.GetPropValue(keyProperty) != null ? item.GetPropValue(keyProperty).ToString() : "",
                                //Selected = item.GetPropValue(keyProperty) != null && ids.Contains(item.GetPropValue(keyProperty).ToString())
                                Value    = GetDisplayString(htmlHelper, item, keyProperty),
                                Selected = ids.Contains(GetDisplayString(htmlHelper, item, keyProperty))
                            });
                        }
                    }
                }
                else
                {
                    options.ToList().ForEach(item =>
                                             items.Add(new SelectListItem()
                    {
                        Text     = item,
                        Value    = item,
                        Selected = ids.Contains(item)
                    }));
                }
            }

            if (metadata.IsNullableValueType || nullable)
            {
                items.Insert(0, new SelectListItem {
                    Text = "", Value = ""
                });
            }

            return(items);
        }
예제 #18
0
        public async Task <ActionResult> Index(int page = 1, int pageSize = 20, string orderColumn = nameof(LocationDto.Name), string orderType = "asc", string search = "")
        {
            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            try
            {
                var dataTask  = _locationService.SearchAsync(cts.Token, LocationType.Country.ToString() + "&" + search, l => !string.IsNullOrEmpty(l.Album) && !string.IsNullOrEmpty(l.UrlSlug), LamdaHelper.GetOrderBy <LocationDto>(orderColumn, orderType), page - 1, pageSize);
                var totalTask = _locationService.GetSearchCountAsync(cts.Token, LocationType.Country.ToString() + "&" + search, l => !string.IsNullOrEmpty(l.Album) && !string.IsNullOrEmpty(l.UrlSlug));

                await TaskHelper.WhenAllOrException(cts, dataTask, totalTask);

                var data  = dataTask.Result;
                var total = totalTask.Result;

                var response = new WebApiPagedResponseDto <LocationDto>
                {
                    Page        = page,
                    PageSize    = pageSize,
                    Records     = total,
                    Rows        = data.ToList(),
                    OrderColumn = orderColumn,
                    OrderType   = orderType,
                    Search      = search
                };

                ViewBag.Search      = search;
                ViewBag.Page        = page;
                ViewBag.PageSize    = pageSize;
                ViewBag.OrderColumn = orderColumn;
                ViewBag.OrderType   = orderType;

                return(View(response));
            }
            catch
            {
                return(HandleReadException());
            }
        }
예제 #19
0
        protected override async Task <IEnumerable <SelectListItem> > GetSelectListItemsAsync(SelectListContext context)
        {
            //Get DbContext from DI container
            DbContext db = (DbContext)context.HttpContext.RequestServices.GetService(DbContextType);

            if (db == null)
            {
                throw new Exception("Database not found");
            }

            //Get DbSet as IQueryable
            IQueryable query = (IQueryable)_dbContextSetMethod.MakeGenericMethod(ModelType).Invoke(db, null);

            if (!string.IsNullOrEmpty(RawSql))
            {
                query = (IQueryable)RelationalQueryableExtensions.FromSql((dynamic)query, RawSql, RawSqlParameters);
            }

            if (!EnableChangeTracking)
            {
                query = (IQueryable)EntityFrameworkQueryableExtensions.AsNoTracking((dynamic)query);
            }

            if (context.SelectedOnly)
            {
                //Select by Id
                var whereClause = DbContextHelper.SearchForEntityByValues(ModelType, DataValueField, context.CurrentValues);
                query = (IQueryable)_dbContextWhereClauseMethod.MakeGenericMethod(ModelType).Invoke(null, new object[] { query, whereClause });
            }
            else
            {
                if (context.ModelExplorer.Metadata is DefaultModelMetadata defaultModelMetadata)
                {
                    //Loop over where clauses

                    IEnumerable <SelectListDbWhereEqualsAttribute> whereClauseAttributes = null;
                    if (defaultModelMetadata.MetadataKind == ModelMetadataKind.Property)
                    {
                        whereClauseAttributes = defaultModelMetadata.Attributes.PropertyAttributes.OfType <SelectListDbWhereEqualsAttribute>().Where(a => a.SelectListId == this.SelectListId);
                    }
                    else if (defaultModelMetadata.MetadataKind == ModelMetadataKind.Type)
                    {
                        whereClauseAttributes = defaultModelMetadata.Attributes.TypeAttributes.OfType <SelectListDbWhereEqualsAttribute>().Where(a => a.SelectListId == this.SelectListId);
                    }

                    if (whereClauseAttributes != null)
                    {
                        foreach (var where in whereClauseAttributes)
                        {
                            var whereClause = LamdaHelper.SearchForEntityByProperty(ModelType, where.PropertyName, where.Values);
                            query = (IQueryable)_dbContextWhereClauseMethod.MakeGenericMethod(ModelType).Invoke(null, new object[] { query, whereClause });
                        }
                    }
                }
            }

            //Order By
            if (!string.IsNullOrWhiteSpace(OrderByProperty))
            {
                if (OrderByType == "asc")
                {
                    query = (IQueryable)_dbContextOrderByMethod.MakeGenericMethod(ModelType).Invoke(null, new object[] { query, OrderByProperty, true });
                }
                else
                {
                    query = (IQueryable)_dbContextOrderByMethod.MakeGenericMethod(ModelType).Invoke(null, new object[] { query, OrderByProperty, false });
                }
            }

            //Skip
            query = (IQueryable)Queryable.Skip((dynamic)query, Skip);

            //Take
            query = (IQueryable)Queryable.Take((dynamic)query, Take);

            //Get Results
            IEnumerable results = (IEnumerable)(await EntityFrameworkQueryableExtensions.ToListAsync((dynamic)query, CancellationToken.None));

            return(new ModelMultiSelectList(context.Html, results, DataValueField, DataTextFieldExpression));
        }