Ejemplo n.º 1
0
        public async Task <ActionResult <Pagination <BlogCardDto> > > GetAllBlogCardList([FromForm] SpecificParameters par)
        {
            var user = await GetCurrentUserAsync(HttpContext.User);

            if (user == null)
            {
                return(Unauthorized(new ApiResponse(401)));
            }


            /// _context.Blog.OrderByDescending(b => b.ReleaseDate).Take(N) to get the last N rows
            // query just Publiched Blogs
            IQueryable <Blog> blogs;

            if (par.CategoryId != null)
            {
                // det all blogs that have the specific category id
                blogs = from b in _context.Blog.OrderByDescending(b => b.ReleaseDate).Take(5000)
                        join c in _context.BlogCategoryList on b.Id equals c.BlogId
                        where c.BlogCategoryId == par.CategoryId && b.Publish == true
                        select b;
            }
            else
            {
                // return all blogs
                blogs = from b in _context.Blog.OrderByDescending(b => b.ReleaseDate).Take(5000)
                        where b.Publish == true
                        select b;
            }



            // get the Blogs with the same languages were user selected
            var langList = user.SelectedLanguages.Split(",").ToList();
            // create a new variable to add all Blogs with specific language that passed with langList variable
            IQueryable <Blog> langBlog = blogs.Where(l => l.LanguageId == langList[0]);

            foreach (var lang in langList)
            {
                // langList[0] has query with initialze
                if (lang != langList[0] && !string.IsNullOrEmpty(lang))
                {
                    // Concatenates old query with new one
                    langBlog = blogs.Concat(blogs.Where(l => l.LanguageId == lang));
                }
            }
            blogs = langBlog;


            // At the beginning of the sorting, the blogs are placed to remain at the top and then sorted by title or date of issue
            if (!string.IsNullOrEmpty(par.Sort))
            {
                switch (par.Sort)
                {
                case "titleAsc":
                    blogs = blogs.OrderByDescending(b => b.AtTop).ThenBy(b => b.Title);
                    break;

                case "titleDesc":
                    blogs = blogs.OrderByDescending(b => b.AtTop).ThenByDescending(b => b.Title);
                    break;

                case "dateAsc":
                    blogs = blogs.OrderByDescending(b => b.AtTop).ThenBy(b => b.ReleaseDate);
                    break;
                }
            }
            else
            {
                blogs = blogs.OrderByDescending(b => b.AtTop).ThenByDescending(b => b.ReleaseDate);
            }


            // Search
            if (!string.IsNullOrEmpty(par.Search))
            {
                // Search in Titles
                blogs = from bl in blogs
                        where bl.Title.ToLower().Contains(par.Search)
                        select bl;
            }

            int totalItem = blogs.Count();

            var pageFilter = new SpecificParameters(par.PageIndex, par.PageSize);
            // .Skip() and .Take() It must be at the end in order for pages to be created after filtering and searching
            List <Blog> _blogs = await blogs /*  how many do we want to Skip:
                                              *  minus one here because we want start from 0, PageSize=5 (PageIndex=1 - 1)=0
                                              *  5x0=0 this is start page*/
                                 .Skip((pageFilter.PageIndex - 1) *pageFilter.PageSize)
                                 .Take(pageFilter.PageSize)
                                 .ToListAsync();

            // if pass page not contain any data return Bad Request
            if (_blogs.Count() <= 0)
            {
                return(NoContent());
            }

            List <BlogCardDto> blogsData = _mapper.Map <List <Blog>, List <BlogCardDto> >(_blogs);

            // add some data in return BlogCardDto class**************
            // get the baseurl(Domain) of website
            var url = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";

            foreach (var blog in blogsData)
            {
                // count Likes/dislikes of this Blogs
                blog.LikesCount    = _context.BlogLike.Where(b => b.Like == true && b.BlogId == blog.Id).Count();
                blog.DislikesCount = _context.BlogLike.Where(b => b.Dislike == true && b.BlogId == blog.Id).Count();
                // count the commints
                blog.CommentsCount = _context.BlogComment.Where(b => b.BlogId == blog.Id).Count();

                // return default image for this blog
                var defaultImage = await _context.UploadBlogImagesList.Where(b => b.BlogId == blog.Id && b.Default == true).Select(img => img.Upload.Path).FirstOrDefaultAsync();

                blog.DefaultBlogImage = defaultImage == null ? null : url + defaultImage;
            }

            return(new Pagination <BlogCardDto>(par.PageIndex, par.PageSize, totalItem, blogsData));
        }
        public async Task<ActionResult<Pagination<UserDto>>> GetUsersList([FromForm] SpecificParameters par)
        {
            var user = await GetCurrentUserAsync(HttpContext.User);
            if (user == null) return Unauthorized(new ApiResponse(401));

            var pageFilter = new SpecificParameters(par.PageIndex, par.PageSize);
            IQueryable<AppUser> users;

            // app has just one SuperAdmin, we don't want retrun it with any query
            string superAdminId = await SuperAdminId();

            // check if current user is SuperAdmin
            var currentUserRole = (await _userManager.GetRolesAsync(user)).FirstOrDefault();
            if (currentUserRole == "SuperAdmin")
                users = _context.Users;// return all user include SuperAdmin user
            else
                users = _context.Users.Where(u => u.Id != superAdminId); // return all user without SuperAdmin user

            try
            {
                if (!string.IsNullOrEmpty(par.Search))
                    if (par.Search.Length > 2)
                    {
                        // Search in UserName
                        if ( !string.IsNullOrEmpty(par.Search) && !string.IsNullOrEmpty(par.SearchInColumnName))
                        {
                            if (par.SearchInColumnName.ToLower() == "email")
                            {
                                // Search in UserName
                                users = from u in users
                                        where u.Email.ToLower().Contains(par.Search)
                                        select u;
                            }
                            else if(par.SearchInColumnName.ToLower() == "username")
                            {
                                // Search in UserName
                                users = from u in users
                                        where u.UserName.ToLower().Contains(par.Search)
                                        select u;
                            
                            }
                            
                        }
                    }

                // to get users under specific Roles
                if (!string.IsNullOrEmpty(par.Role))
                {
                    // request directly to the EF Database to get users with this Role
                    users = from usr in users
                            join userRole in _context.UserRoles on usr.Id equals userRole.UserId
                            join role in _context.Roles on userRole.RoleId equals role.Id
                            where role.Name.ToLower() == par.Role.ToLower()
                            select usr;
                }


                int totalItem = users.Count();

                // .ToListAsync() Convert the IQueryable<Entty> to List<Entity> and executing in the database
                // .Skip() and Take() It must be at the end in order for pages to be created after filtering and searching
                List<AppUser> _users = await users.Include(u=>u.Address)
                                            /*  how many do we want to Skip:
                                                minus one here because we want start from 0, PageSize=5 (PageIndex=1 - 1)=0
                                                5x0=0 this is start page*/
                                            .Skip((pageFilter.PageIndex - 1) * pageFilter.PageSize)
                                            .Take(pageFilter.PageSize)
                                            .ToListAsync();
                // if pass page not contain any data return Bad Request
                if (_users.Count() <= 0)
                    return NoContent();

                List<UserDto> userData = _mapper.Map<List<AppUser>, List<UserDto>>(_users);

                // get the baseurl(Domain) of website
                var url = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";
                // get the default images for users
                foreach (var _user in userData)
                {
                    IQueryable<UserImagesDto> images = from ui in _context.UploadUserImagesList
                                                       join up in _context.Upload on ui.UploadId equals up.Id
                                                       join typ in _context.UploadType on ui.UploadTypeId equals typ.Id
                                                       where ui.UserId == _user.Id && ui.Default == true
                                                       select new UserImagesDto
                                                       {
                                                           Id = ui.Id,
                                                           Path = url + up.Path,
                                                           Type = typ.Name,
                                                           Default = ui.Default
                                                       };

                    _user.UserImagesList = images.ToList();
                }
                
                return new Pagination<UserDto>(par.PageIndex, par.PageSize, totalItem, userData);
            }
            catch (Exception ex)
            {
                return BadRequest(new ApiResponse(400, ex.Message));
            }
        }