<file_sep>using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    public enum SearchField
    {
        Id, SiteId, CategoryIds, CategoryNames, Type, SearchId, Title, TitleEnglish, Alias, Sumary, Tags, IsShow, IsClip, IsTrailer, IsFilm, Keyword, KeywordEN
    }

    [DataContract]
    public class SearchInfo : BaseEntity<long>
    {
        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }
        
        [DataMember]
        [DisplayName("SiteId")]
        public int SiteId { get; set; }
        
        [DataMember]
        [DisplayName("CategoryIds")]
        public string CategoryIds { get; set; }

        [NotMapped]
        [DisplayName("CategoryNames")]
        public string CategoryNames { get; set; }
        
        [DataMember]
        [DisplayName("Type")]
        public int Type { get; set; }
        
        [DataMember]
        [DisplayName("SearchId")]
        public string SearchId { get; set; }
        
        [DataMember]
        [DisplayName("Title")]
        public string Title { get; set; }
        
        [DataMember]
        [DisplayName("TitleEnglish")]
        public string TitleEnglish { get; set; }

        [DataMember]
        [DisplayName("Images")]
        public string Images { get; set; }
        
        [DataMember]
        [DisplayName("Alias")]
        public string Alias { get; set; }
        
        [DataMember]
        [DisplayName("Sumary")]
        public string Sumary { get; set; }
        
        [DataMember]
        [DisplayName("Tags")]
        public string Tags { get; set; }
        
        [DataMember]
        [DisplayName("CreateDate")]
        public DateTime CreateDate { get; set; }
        
        [DataMember]
        [DisplayName("IsBlock")]
        public bool IsBlock { get; set; }

        [DataMember]
        [DisplayName("Processed")]
        public int Processed { get; set; }

        [NotMapped]
        [DisplayName("IsShow")]
        public bool IsShow { get; set; }

        [NotMapped]
        [DisplayName("IsClip")]
        public bool IsClip { get; set; }

        [NotMapped]
        [DisplayName("IsTrailer")]
        public bool IsTrailer { get; set; }

        [NotMapped]
        [DisplayName("IsFilm")]
        public bool IsFilm { get; set; }

        [NotMapped]
        [DisplayName("ViewCount")]
        public string ViewCount { get; set; }
    }
    
    public class SearchMap : EntityTypeConfiguration<SearchInfo>, IEntityTypeConfiguration
    {
        public SearchMap()
        {
            ToTable("Modules_Search");
            HasKey(m => m.Id);
            Property(m => m.LanguageCode).HasMaxLength(50);
            Property(m => m.SiteId);
            Property(m => m.CategoryIds).HasMaxLength(250).IsRequired();
            Property(m => m.Type);
            Property(m => m.SearchId).HasMaxLength(50);
            Property(m => m.Title).HasMaxLength(250);
            Property(m => m.TitleEnglish).IsRequired().HasMaxLength(250);
            Property(m => m.Images).HasMaxLength(500);
            Property(m => m.Alias).HasMaxLength(250);
            Property(m => m.Sumary).HasMaxLength(500);
            Property(m => m.Tags).HasMaxLength(400);
            Property(m => m.CreateDate);
            Property(m => m.IsBlock);
        }
    }
}
<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class CategoryModel
    {
        public CategoryModel()
        {
            IsActived = true;
        }

        [ControlHidden]
        public int Id { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.ParentId+ "').empty();")]
        public string LanguageCode { get; set; }

        [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public int SiteId { get; set; }

        [ControlCascadingDropDown(LabelText = "Chuyên mục gốc", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public int ParentId { get; set; }

        [ControlNumeric(LabelText = "Vị trí", Required = true, MaxLength = 3, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public int OrderBy { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Làm trang chủ", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public bool IsHome { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Được hiển thị", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public bool IsActived { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Có chuyên mục con", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public bool HasChilden { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Không sử dụng", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public bool IsDeleted { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "<NAME>", PlaceHolder = "Tối đa 250 ký tự", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)]
        public string ShortName { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Tên đầy đủ", PlaceHolder = "Tối đa 400 ký tự", Required = true, MaxLength = 400, ContainerCssClass = Constants.ContainerCssClassCol8, ContainerRowIndex = 2)]
        public string Name { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "<NAME>", PlaceHolder = "Tối đa 250 ký tự", MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 4)]
        public string Url { get; set; }

        [ControlText(LabelText = "Mô tả SEO", PlaceHolder = "Tối đa 2000 ký tự", Type = ControlText.MultiText, Required = true, Rows = 2, MaxLength = 2000, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 5)]
        public string Description { get; set; }

        [ControlText(LabelText = "Tags SEO", PlaceHolder = "Tối đa 2000 ký tự", Type = ControlText.MultiText, Required = true, Rows = 2, MaxLength = 2000, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 6)]
        public string Tags { get; set; }

        public static implicit operator CategoryModel(CategoryInfo other)
        {
            if (other == null)
            {
                return null;
            }

            return new CategoryModel
            {
                Id = other.Id,
                SiteId = other.SiteId,
                ParentId = other.ParentId,
                ShortName = other.ShortName,
                Name = other.Name,
                LanguageCode = other.LanguageCode,
                IsActived = other.IsActived,
                OrderBy = other.OrderBy,
                Description = other.Description,
                Tags = other.Tags,
                Url = other.Url,
                IsHome = other.IsHome,
                HasChilden = other.HasChilden,
                IsDeleted = other.IsDeleted
            };
        }
    }
}<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class CollectionModel
    {
        [ControlHidden]
        public int Id { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public string LanguageCode { get; set; }

        [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public int SiteId { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Tên bộ phim", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)]
        public string Name { get; set; }

        [ControlNumeric(LabelText = "Vị trí", Required = true, MaxLength = 3, ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 3)]
        public int OrderBy { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Bộ phim mới cập nhật", ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 3)]
        public bool IsHot { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true,LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 4)]
        public int Status { get; set; }

        [ControlText(Type = ControlText.MultiText, Rows = 2, MaxLength = 2000, LabelText = "Giới thiệu", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 5)]
        public string Description { get; set; }
        
        public static implicit operator CollectionModel(CollectionInfo entity)
        {
            return new CollectionModel
            {
                Id = entity.Id,
                LanguageCode = entity.LanguageCode,
                SiteId = entity.SiteId,
                Name = entity.Name,
                IsHot = entity.IsHot,
                Description = entity.Description,
                Status = entity.Status,
                OrderBy = entity.OrderBy
            };
        }
    }
}
<file_sep>﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class ArticlesInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("SiteId")]
        public int SiteId { get; set; }

        [DataMember]
        [DisplayName("ParentId")]
        public int ParentId { get; set; }

        [DataMember]
        [DisplayName("CategoryId")]
        public int CategoryId { get; set; }

        [NotMapped]
        [DisplayName("CategoryAlias")]
        public string CategoryAlias { get; set; }

        [NotMapped]
        [DisplayName("CategoryName")]
        public string CategoryName { get; set; }

        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }

        [DataMember]
        [DisplayName("Icon")]
        public string Icon { get; set; }

        [DataMember]
        [DisplayName("Title")]
        public string Title { get; set; }

        [DataMember]
        [DisplayName("Alias")]
        public string Alias { get; set; }

        [DataMember]
        [DisplayName("Summary")]
        public string Summary { get; set; }

        [DataMember]
        [DisplayName("Contents")]
        public string Contents { get; set; }

        [DataMember]
        [DisplayName("CreateDate")]
        public DateTime CreateDate { get; set; }

        [DataMember]
        [DisplayName("CreateByUser")]
        public int CreateByUser { get; set; }

        [DataMember]
        [DisplayName("IsPublished")]
        public bool IsPublished { get; set; }

        [DataMember]
        [DisplayName("PublishedDate")]
        public DateTime? PublishedDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextPublishedDate
        {
            get
            {
                if (PublishedDate != null)
                {
                    return PublishedDate.Value.ToString(Extensions.Constants.DateTimeFomat2);
                }
                return CreateDate.ToString(Extensions.Constants.DateTimeFomat2);
            }
        }

        [DataMember]
        [DisplayName("IsHome")]
        public bool IsHome { get; set; }

        [DataMember]
        [DisplayName("IsVideo")]
        public bool IsVideo { get; set; }

        [DataMember]
        [DisplayName("VideosUrl")]
        public string VideosUrl { get; set; }

        [DataMember]
        [DisplayName("ViewCount")]
        public int ViewCount { get; set; }

        [DataMember]
        [DisplayName("Description")]
        public string Description { get; set; }

        [DataMember]
        [DisplayName("Tags")]
        public string Tags { get; set; }

        [DataMember]
        [DisplayName("IsDeleted")]
        public bool IsDeleted { get; set; }
    }

    public class ArticlesMap : EntityTypeConfiguration<ArticlesInfo>, IEntityTypeConfiguration
    {
        public ArticlesMap()
        {
            ToTable("Modules_Articles");
            HasKey(x => x.Id);
            Property(x => x.SiteId).IsRequired();
            Property(x => x.CategoryId).IsRequired();
            Property(x => x.Icon).HasMaxLength(300);
            Property(x => x.LanguageCode).HasMaxLength(50);
            Property(x => x.Title).IsRequired().HasMaxLength(200);
            Property(x => x.Alias).IsRequired().HasMaxLength(200);
            Property(x => x.Summary).IsRequired().HasMaxLength(400);
            Property(x => x.Contents).IsRequired();
            Property(x => x.CreateDate).IsRequired();
            Property(x => x.CreateByUser).IsRequired();
            Property(x => x.IsPublished).IsRequired();
            Property(x => x.IsHome).IsRequired();
            Property(x => x.IsVideo).IsRequired();
            Property(x => x.ViewCount).IsRequired();
            Property(x => x.Description).HasMaxLength(400);
            Property(x => x.Tags).HasMaxLength(500);
            Property(x => x.IsDeleted).IsRequired();
        }
    }
}<file_sep>﻿using System;
using System.Globalization;
using System.Web.Mvc;
using CMSSolutions.Extensions;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminActorController : BaseAdminController
    {
        public AdminActorController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
            TableName = "tblActors";
        }
        
        [Url("admin/actors")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý diễn viên"), Url = "#" });

            var result = new ControlGridFormResult<ActorInfo>
            {
                Title = T("Quản lý diễn viên"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetActors,
                DefaultPageSize = WorkContext.DefaultPageSize,
                EnablePaginate = true,
                UpdateActionName = "Update",
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml,
                ClientId = TableName,
                ActionsColumnWidth = 100
            };

            result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true);
            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true);

            result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(60);
            result.AddColumn(x => x.FullName, T("Họ và Tên"));
            result.AddColumn(x => EnumExtensions.GetDisplayName((Status)x.Status), T("Trạng thái"));

            result.AddAction().HasText(T("Thêm mới"))
                .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
                .HasButtonStyle(ButtonStyle.Primary)
                .HasBoxButton(false)
                .HasRow(false)
                .HasCssClass(Constants.RowLeft)
                .HasRow(true)
                .ShowModalDialog();

            result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3);
            
            result.AddRowAction()
                .HasText(T("Sửa"))
                .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                .HasButtonStyle(ButtonStyle.Default)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .ShowModalDialog();

            result.AddRowAction(true)
                .HasText(T("Xóa"))
                .HasName("Delete")
                .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString()))
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");

            return result;
        }

        private ControlGridAjaxData<ActorInfo> GetActors(ControlGridFormRequest options)
        {
            var searchText = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText]))
            {
                searchText = Request.Form[Extensions.Constants.SearchText];
            }

            var statusId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId]))
            {
                statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]);
            }

            int totals;
            var items = WorkContext.Resolve<IActorService>().SearchPaged(searchText, statusId, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<ActorInfo>(items, totals);

            return result;
        }
        
        [Themed(false)]
        [Url("admin/actors/edit/{id}")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý diễn viên"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin diễn viên"), Url = "#" });

            var model = new ActorModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<IActorService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<ActorModel>(model)
            {
                Title = T("Thông tin diễn viên"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                CancelButtonText = T("Đóng"),
                ShowBoxHeader = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.RegisterExternalDataSource(x => x.Status, y => BindStatus());

            return result;
        }
        
        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/actors/update")]
        public ActionResult Update(ActorModel model)
        {
            if (!ModelState.IsValid)
            {
				return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var service = WorkContext.Resolve<IActorService>();
            ActorInfo item = model.Id == 0 ? new ActorInfo() : service.GetById(model.Id);

            if (service.CheckExist(model.Id, model.FullName))
            {
                return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE")
                    .Alert(T("Họ và Tên đã tồn tại."));
            }

            item.FullName = model.FullName;
            item.Description = model.Description;
            item.Status = model.Status;
            service.Save(item);

            return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"))
                .CloseModalDialog();
        }
        
        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<IActorService>();
            var item = service.GetById(id);
            item.Status = (int)Status.Deleted;
            service.Update(item);

            return new AjaxResult()
                .NotifyMessage("DELETE_ENTITY_COMPLETE")
                .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!"));
        }
    }
}
<file_sep>﻿using System.Collections.Generic;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class TagViewModel
    {
        public IList<TagInfo> ListTags { get; set; }
    }
}<file_sep>﻿using System.Web.Mvc;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminSiteController : BaseAdminController
    {
        public AdminSiteController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor)
        {
            TableName = "tblSites";
        }

        [Url("admin/sites")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý trang web"), Url = "#" });

            var result = new ControlGridFormResult<SiteInfo>
            {
                Title = T("Quản lý trang web"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetSites,
                UpdateActionName = "Update",
                ActionsColumnWidth = 100,
                ClientId = TableName,
                DefaultPageSize = WorkContext.DefaultPageSize,
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml
            };

            result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true);

            result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(60);
            result.AddColumn(x => x.Name, T("Tên trang web"));
            result.AddColumn(x => x.Domain, T("Tên miền"));
            result.AddColumn(x => x.Url, T("Đường dẫn"));
            result.AddColumn(x => x.IsActived)
                .HasHeaderText(T("Sử dụng"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage();


            result.AddAction().HasText(T("Thêm mới"))
               .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
               .HasButtonStyle(ButtonStyle.Primary)
               .HasBoxButton(false)
               .HasCssClass(Constants.RowLeft)
               .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(false, string.Empty))).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
                .HasText(T("Sửa"))
                .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                .HasButtonStyle(ButtonStyle.Default)
                .HasButtonSize(ButtonSize.ExtraSmall);

            //result.AddRowAction(true)
            //    .HasText(T("Xóa"))
            //    .HasName("Delete")
            //    .HasValue(x => x.Id)
            //    .HasButtonStyle(ButtonStyle.Danger)
            //    .HasButtonSize(ButtonSize.ExtraSmall)
            //    .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            //result.AddReloadEvent("DELETE_ENTITY_COMPLETE");
            return result;
        }

        private ControlGridAjaxData<SiteInfo> GetSites(ControlGridFormRequest options)
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var items = WorkContext.Resolve<ISiteService>().GetRecords(x => x.LanguageCode == languageCode);
            var result = new ControlGridAjaxData<SiteInfo>(items);
            return result;
        }
        
        [Url("admin/sites/edit/{id}")]
        public ActionResult Edit(int id)
        {
            var model = new SiteModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<ISiteService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<SiteModel>(model)
            {
                Title = T("Thông tin trang web"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                ShowCancelButton = false,
                ShowBoxHeader = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.AddAction().HasText(T("Trở về"))
               .HasUrl(Url.Action("Index"))
               .HasCssClass("btn btn-danger");

            result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages());

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/sites/update")]
        public ActionResult Update(SiteModel model)
        {
            SiteInfo item;
            var service = WorkContext.Resolve<ISiteService>();
            if (model.Id == 0)
            {
                item = new SiteInfo();
            }
            else
            {
                item = service.GetById(model.Id);
            }

            item.Name = model.Name;
            item.LanguageCode = model.LanguageCode;
            item.Url = model.Url;
            item.Domain = model.Domain;
            item.IsActived = model.IsActived;
            item.Description = model.Description;
            service.Save(item);

            return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE").Alert(T("Cập nhật thành công!"));
        }

        //[FormButton("Delete")]
        //[HttpPost, ActionName("Update")]
        //public ActionResult Delete(int id)
        //{
        //    var service = WorkContext.Resolve<ISiteService>();
        //    var model = service.GetById(id);
        //    service.Delete(model);

        //    return new AjaxResult().NotifyMessage("DELETE_ENTITY_COMPLETE");
        //}
    }
}
<file_sep>﻿using System.ComponentModel;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    /// <summary>
    /// Nước sản xuất
    /// </summary>
    [DataContract]
    public class CountryInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("Code")]
        public string Code { get; set; }
        
        [DataMember]
        [DisplayName("Name")]
        public string Name { get; set; }
    }

    public class CountryMap : EntityTypeConfiguration<CountryInfo>, IEntityTypeConfiguration
    {
        public CountryMap()
        {
            ToTable("Modules_Countries");
            HasKey(m => m.Id);
            Property(m => m.Code).IsRequired().HasMaxLength(50);
            Property(m => m.Name).IsRequired().HasMaxLength(250);
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web.Mvc;
using CMSSolutions.Extensions;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Services;
using GemBox.Spreadsheet;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminReportSmsController : BaseAdminController
    {
        public AdminReportSmsController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
            TableName = "tblReportSms";
        }

        [Url("admin/report/sms")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Báo cáo SMS"), Url = "#" });

            var result = new ControlGridFormResult<TransactionSmsInfo>
            {
                Title = T("Báo cáo SMS"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetReportSMS,
                DefaultPageSize = WorkContext.DefaultPageSize,
                EnablePaginate = true,
                UpdateActionName = "Update",
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml,
                ClientId = TableName,
                ActionsColumnWidth = 150
            };

            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.TypeId, "$('#" + Extensions.Constants.TypeId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.Locked, "$('#" + Extensions.Constants.Locked + "').val();", true);
            result.AddCustomVar(Extensions.Constants.FromDate, "$('#" + Extensions.Constants.FromDate + "').val();", true);
            result.AddCustomVar(Extensions.Constants.ToDate, "$('#" + Extensions.Constants.ToDate + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true);

            result.AddColumn(x => x.TransactionCode, T("Mã GD")).HasWidth(60).AlignCenter();
            result.AddColumn(x => x.CustomerCode, T("Mã KH"));
            result.AddColumn(x => x.FullName, T("Tên KH"));
            result.AddColumn(x => x.Amount, T("Số tiền"));
            result.AddColumn(x => EnumExtensions.GetDisplayName((RequestStatus)x.Status), T("Trạng thái"));
            result.AddColumn(x => x.TextStartDate, T("Từ ngày"));
            result.AddColumn(x => x.TextEndDate, T("Đến ngày"));
            result.AddColumn(x => x.IsLock)
                .HasHeaderText(T("Đang khóa"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage();

            result.AddAction().HasText(T("Chốt đối soát"))
                .HasUrl(Url.Action("Index", "AdminClosedSms"))
                .HasButtonStyle(ButtonStyle.Danger)
                .HasCssClass(Constants.RowLeft);

            result.AddAction().HasText(T("Xuất dữ liệu MO"))
                .HasUrl(Url.Action("ExportExcelMo"))
                .HasButtonStyle(ButtonStyle.Info)
                .HasCssClass(Constants.RowLeft);

            result.AddAction().HasText(T("Xuất dữ liệu MT"))
               .HasUrl(Url.Action("ExportExcelMt"))
               .HasButtonStyle(ButtonStyle.Info)
               .HasCssClass(Constants.RowLeft)
               .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol6);
            result.AddAction(new ControlFormHtmlAction(BuildTypes)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildLocked)).HasParentClass(Constants.ContainerCssClassCol3).HasRow(true);
            result.AddAction(new ControlFormHtmlAction(() => BuildFromDate())).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildToDate())).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3);

            return result;
        }

        public override string BuildStatus()
        {
            var list = EnumExtensions.GetListItems<RequestStatus>();
            var sb = new StringBuilder();
            sb.AppendFormat(T("Trạng thái lỗi") + " <select id=\"" + Extensions.Constants.StatusId + "\" name=\"" + Extensions.Constants.StatusId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var status in list)
            {
                if ((int)RequestStatus.Messages200 == int.Parse(status.Value))
                {
                    sb.AppendFormat("<option value=\"{1}\" selected>{0}</option>", status.Text, status.Value);
                    continue;
                }
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        private string BuildTypes()
        {
            var list = EnumExtensions.GetListItems<SMSType>();
            var sb = new StringBuilder();
            sb.AppendFormat(T("Loại tin nhắn") + " <select id=\"" + Extensions.Constants.TypeId + "\" name=\"" + Extensions.Constants.TypeId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var status in list)
            {
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        private string BuildLocked()
        {
            var list = new List<SelectListItem>
            {
                new SelectListItem{Value = "0", Text = "Chưa chốt sổ đối soát"},
                new SelectListItem{Value = "1", Text = "Đã chốt sổ đối soát"}
            };
            var sb = new StringBuilder();
            sb.AppendFormat(T("Đối soát") + " <select id=\"" + Extensions.Constants.Locked + "\" name=\"" + Extensions.Constants.Locked + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var status in list)
            {
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        private ControlGridAjaxData<TransactionSmsInfo> GetReportSMS(ControlGridFormRequest options)
        {
            var searchText = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText]))
            {
                searchText = Request.Form[Extensions.Constants.SearchText];
            }

            var type = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.TypeId]))
            {
                type = Convert.ToInt32(Request.Form[Extensions.Constants.TypeId]);
            }

            var status = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId]))
            {
                status = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]);
            }

            var locked = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.Locked]))
            {
                locked = Convert.ToInt32(Request.Form[Extensions.Constants.Locked]);
            }

            var fromDate = DateTime.Now.Date;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FromDate]))
            {
                fromDate = DateTime.ParseExact(Request.Form[Extensions.Constants.FromDate], "dd/MM/yyyy", CultureInfo.InvariantCulture);
            }

            var toDate = DateTime.Now.Date;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ToDate]))
            {
                toDate = DateTime.ParseExact(Request.Form[Extensions.Constants.ToDate], "dd/MM/yyyy", CultureInfo.InvariantCulture);
            }

            int totals;
            var items = WorkContext.Resolve<ITransactionSmsService>().GetPaged(searchText, type, status, locked, fromDate, toDate, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<TransactionSmsInfo>(items, totals);

            return result;
        }

        [Url("admin/report/sms/export-excel-mo")]
        public ActionResult ExportExcelMo()
        {
            var ef = new ExcelFile();
            string fileName = Server.MapPath("/Media/Default/ExcelTemplate/DuLieuSMS.xls");
            ef.LoadXls(fileName, XlsOptions.PreserveAll);
            ExcelWorksheet ws = ef.Worksheets[0];
            var data = WorkContext.Resolve<ITransactionSmsService>().ExportExcelSms(Utilities.DateNull(), Utilities.DateNull(), (int)SMSType.MO);
            if (data != null && data.Count > 0)
            {
                int index = 1;
                foreach (var item in data)
                {
                    ws.Cells[index, 0].Value = index;
                    ws.Cells[index, 1].Value = item.CustomerCode;
                    ws.Cells[index, 2].Value = item.FullName;
                    ws.Cells[index, 3].Value = item.Amount;
                    ws.Cells[index, 4].Value = item.ShortCode;
                    ws.Cells[index, 5].Value = item.UserId;
                    ws.Cells[index, 6].Value = item.CreateDate.ToString(Extensions.Constants.DateTimeFomatFull);
                    ws.Cells[index, 7].Value = EnumExtensions.GetDisplayName((RequestStatus)item.Status);
                    index++;
                    ws.Rows[index].InsertCopy(1, ws.Rows[1]);
                }

                ws.Rows[index].Delete();
            }

            byte[] fileContents;
            using (var stream = new MemoryStream())
            {
                ef.SaveXls(stream);

                fileContents = stream.ToArray();
            }

            return File(fileContents, "application/vnd.ms-excel");
        }

        [Url("admin/report/sms/export-excel-mt")]
        public ActionResult ExportExcelMt()
        {
            var ef = new ExcelFile();
            string fileName = Server.MapPath("/Media/Default/ExcelTemplate/DuLieuSMS.xls");
            ef.LoadXls(fileName, XlsOptions.PreserveAll);
            ExcelWorksheet ws = ef.Worksheets[0];
            var data = WorkContext.Resolve<ITransactionSmsService>().ExportExcelSms(Utilities.DateNull(), Utilities.DateNull(), (int)SMSType.MT);
            if (data != null && data.Count > 0)
            {
                int index = 1;
                foreach (var item in data)
                {
                    ws.Cells[index, 0].Value = index;
                    ws.Cells[index, 1].Value = item.CustomerCode;
                    ws.Cells[index, 2].Value = item.FullName;
                    ws.Cells[index, 3].Value = item.Amount;
                    ws.Cells[index, 4].Value = item.ShortCode;
                    ws.Cells[index, 5].Value = item.UserId;
                    ws.Cells[index, 6].Value = item.CreateDate.ToString(Extensions.Constants.DateTimeFomatFull);
                    ws.Cells[index, 7].Value = EnumExtensions.GetDisplayName((RequestStatus)item.Status);
                    index++;
                    ws.Rows[index].InsertCopy(1, ws.Rows[1]);
                }

                ws.Rows[index].Delete();
            }

            byte[] fileContents;
            using (var stream = new MemoryStream())
            {
                ef.SaveXls(stream);

                fileContents = stream.ToArray();
            }

            return File(fileContents, "application/vnd.ms-excel");
        }
    }
}
<file_sep>﻿using System.ComponentModel;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    /// <summary>
    /// Diễn viên
    /// </summary>
    [DataContract]
    public class ActorInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("FullName")]
        public string FullName { get; set; }
        
        [DataMember]
        [DisplayName("Description")]
        public string Description { get; set; }
        
        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }
    }
    
    public class ActorMap : EntityTypeConfiguration<ActorInfo>, IEntityTypeConfiguration
    {
        public ActorMap()
        {
            ToTable("Modules_Actors");
            HasKey(m => m.Id);
            Property(m => m.FullName).IsRequired().HasMaxLength(250);
            Property(m => m.Description).HasMaxLength(2000);
            Property(m => m.Status).IsRequired();
        }
    }
}
<file_sep>using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface ICardTypeService : IGenericService<CardTypeInfo, int>, IDependency
    {
        IList<CardTypeInfo> GetPaged(int status, int pageIndex, int pageSize, out int totals);

        CardTypeInfo GetByCode(string code, int hasSerial);
    }

    public class CardTypeService : GenericService<CardTypeInfo, int>, ICardTypeService
    {
        public CardTypeService(IRepository<CardTypeInfo, int> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public IList<CardTypeInfo> GetPaged(int status, int pageIndex, int pageSize, out int totals)
        {
            var results = Repository.Table.Where(x => x.Status == status).ToList();
            {
                totals = results.Count();
                return (from x in results select x).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
        }

        public CardTypeInfo GetByCode(string code, int hasSerial)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Code", code),
                AddInputParameter("@HasSerial", hasSerial)
            };

            return ExecuteReaderRecord<CardTypeInfo>("sp_CardTypes_GetByCode", list.ToArray());
        }
    }
}
<file_sep>﻿using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IDownloadCustomerService : IGenericService<DownloadCustomerInfo, long>, IDependency
    {
        List<DownloadCustomerInfo> GetByCustomer(int customerId);

        DownloadCustomerInfo GetItem(int customerId, int downloadId);

        DataTable GetHistory(int customerId);
    }

    public class DownloadCustomerService : GenericService<DownloadCustomerInfo, long>, IDownloadCustomerService
    {
        public DownloadCustomerService(IRepository<DownloadCustomerInfo, long> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public List<DownloadCustomerInfo> GetByCustomer(int customerId)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@CustomerId", customerId)
            };

            return ExecuteReader<DownloadCustomerInfo>("sp_DownloadCustomers_GetByCustomer", list.ToArray());
        }

        public DownloadCustomerInfo GetItem(int customerId, int downloadId)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@CustomerId", customerId),
                AddInputParameter("@DownloadId", downloadId)
            };

            return ExecuteReaderRecord<DownloadCustomerInfo>("sp_DownloadCustomers_GetItem", list.ToArray());
        }

        public DataTable GetHistory(int customerId)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@CustomerId", customerId)
            };

            return ExecuteReader("sp_DownloadCustomers_GetHistory", list.ToArray()).Tables[0];
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Mvc;
using CMSSolutions.Configuration;
using CMSSolutions.Extensions;
using CMSSolutions.Net.Mail;
using CMSSolutions.Security.Cryptography;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;

namespace CMSSolutions.Websites.Controllers
{
    public class BaseHomeController : BaseController
    {
        #region Paged

        public int PageIndex { get; set; }

        public int PageSize { get; set; }
        #endregion

        #region User Login

        public string GlobalCapcha
        {
            get
            {
                if (Session[Extensions.Constants.GlobalCapcha] != null)
                {
                    return Session[Extensions.Constants.GlobalCapcha].ToString();
                }

                return string.Empty;
            }
        }

        public bool IsVip
        {
            get
            {
                if (CurrentDate != DateTime.Now.Date)
                {
                    var customer = WorkContext.Resolve<ICustomerService>().GetById(UserId);
                    SetCustomerState(customer);
                }

                if (EndDate >= DateTime.Now)
                {
                    return true;
                }

                return false;
            }
        }

        public bool IsLogin
        {
            get
            {
                return UserId > 0 && !string.IsNullOrEmpty(CustomerCode);
            }
        }

        public string CustomerCode
        {
            get
            {
                return GetCookies(Extensions.Constants.GlobalCustomerCode);
            }
        }

        public string UserName
        {
            get
            {
                return GetCookies(Extensions.Constants.GlobalUserName);
            }
        }

        public string FullName
        {
            get
            {
                return GetCookies(Extensions.Constants.GlobalFullName);
            }
        }

        public int UserId
        {
            get
            {
                var id = GetCookies(Extensions.Constants.GlobalUserId);
                if (!string.IsNullOrEmpty(id))
                {
                    return int.Parse(id);
                }

                return 0;
            }
        }

        public decimal VipXu
        {
            get
            {
                var xu = GetCookies(Extensions.Constants.GlobalVipXu);
                if (!string.IsNullOrEmpty(xu))
                {
                    return int.Parse(xu);
                }

                return 0;
            }
        }

        public int TotalDay
        {
            get
            {
                var day = GetCookies(Extensions.Constants.GlobalTotalDay);
                if (!string.IsNullOrEmpty(day))
                {
                    return int.Parse(day);
                }

                return 0;
            }
        }

        public DateTime StartDate
        {
            get
            {
                var date = GetCookies(Extensions.Constants.GlobalStartDate);
                if (!string.IsNullOrEmpty(date))
                {
                    return DateTime.Parse(date);
                }

                return Utilities.DateNull();
            }
        }

        public DateTime EndDate
        {
            get
            {
                var date = GetCookies(Extensions.Constants.GlobalEndDate);
                if (!string.IsNullOrEmpty(date))
                {
                    return DateTime.Parse(date);
                }

                return Utilities.DateNull();
            }
        }

        public int SiteId 
        { 
            get
            {
                if (Session[Extensions.Constants.GlobalSiteId] != null)
                {
                    return (int)Session[Extensions.Constants.GlobalSiteId];
                }

                return (int)Site.Home;
            } 
            set { Session[Extensions.Constants.GlobalSiteId] = value; }
        }

        public string TransactionCode
        {
            get
            {
                if (Session[Extensions.Constants.TransactionCode] != null)
                {
                    return Session[Extensions.Constants.TransactionCode].ToString();
                }

                return string.Empty;
            }
            set
            {
                Session[Extensions.Constants.TransactionCode] = value;
            }
        }

        public DateTime CurrentDate
        {
            get
            {
                if (Session[Extensions.Constants.CurrentDate] != null)
                {
                    return DateTime.Parse(Session[Extensions.Constants.CurrentDate].ToString());
                }

                return Utilities.DateNull();
            }
            set
            {
                Session[Extensions.Constants.CurrentDate] = value;
            }
        }

        public string UrlLogin
        {
            get
            {
                if (Session[Extensions.Constants.UrlLoginHistory] != null)
                {
                    return Session[Extensions.Constants.UrlLoginHistory].ToString();
                }

                return Url.Action("Index","Home");
            }
            set
            {
                Session[Extensions.Constants.UrlLoginHistory] = value;
            }
        }

        #endregion

        public BaseHomeController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
           
        }

        public virtual ActionResult RedirectToLocal(string returnUrl)
        {
            if (!string.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }

            return Redirect(UrlLogin);
        }

        #region Cookies
        public void AddCookies(string key, string value, bool isRemember)
        {
            var expiration = DateTime.Now;
            if (isRemember)
            {
                expiration = DateTime.Now.AddMonths(1);
            }
            else
            {
                expiration = DateTime.Now.AddDays(1);
            }
            var cookie = new HttpCookie(key, EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, value))
            {
                Expires = expiration,
                HttpOnly = true
            };

            Response.Cookies.Add(cookie);
        }

        public string GetCookies(string key)
        {
            HttpCookie authCookie = Request.Cookies[key];
            if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value))
            {
                return EncryptionExtensions.Decrypt(KeyConfiguration.PublishKey, authCookie.Value);
            }

            return string.Empty;
        }

        public void RemoveCookies(string key)
        {
            if (Request.Cookies[key] != null)
            {
                var myCookie = new HttpCookie(key)
                {
                    Expires = DateTime.Now.AddDays(-1d)
                };
                Response.Cookies.Add(myCookie);
            }
        }
        #endregion

        #region Customers
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        [Url("mang-xa-hoi")]
        public ActionResult ExternalLogin(string provider, string returnUrl)
        {
            return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
        }

        [AllowAnonymous]
        [Url("dang-nhap")]
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            GoogleClient.RewriteRequest();
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            if (!result.IsSuccessful)
            {
                return RedirectToLocal(returnUrl);
            }

            var service = WorkContext.Resolve<ICustomerService>();
            var cutomerCode = service.GetLatestCustomerCode();
            //var loginType = EnumExtensions.Parse<LoginTypes>(OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName);
            //string userName = cutomerCode;
            //if (loginType == LoginTypes.Google)
            //{
            //    userName = result.ExtraData["username"];
            //}
            var fullName = result.ExtraData["name"];
            var gender = Gender.None;
            try
            {
                if (result.ExtraData["gender"] == null)
                {
                    gender = EnumExtensions.Parse<Gender>(result.ExtraData["gender"]);
                }
            }
            catch (Exception)
            {

            }

            var loginId = result.ExtraData["id"];
            var email = result.UserName;
            if (!Utilities.ValidateUserName(email))
            {
                email = loginId + "@nodomain.vn";
                returnUrl = Url.Action("Index", "Home");
                return RedirectToLocal(returnUrl);
            }

            var customer = new CustomerInfo
            {
                UserName = email,
                Password = EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, Extensions.Constants.DefaultPassword),
                Email = email,
                FullName = fullName,
                Sex = (int)gender,
                MemberDate = DateTime.Now.Date,
                Birthday = Utilities.DateNull(),
                VipXu = 0,
                Status = (int)Status.Approved,
                IsBlock = false
            };

            customer.ImageIcon = gender == Gender.Male ? Extensions.Constants.ImageMale : Extensions.Constants.ImageFemale;
            var item = service.CheckRegister(customer.UserName);
            if (item == null)
            {
                customer.CustomerCode = cutomerCode;
                service.Insert(customer);
                var status = SendEmailRegister("Thông tin đăng nhập thành viên VIPHD.VN", customer.CustomerCode, customer.UserName, Extensions.Constants.DefaultPassword, customer.Email);
                if (!status)
                {
                    var user1 = service.Login(customer.UserName, customer.Password);
                    if (user1 != null)
                    {
                        SetCustomerState(user1);
                    }

                    return View("Messages", new MessageErrorModel
                    {
                        TitleForm = "Thông tin đăng nhập thành viên VIPHD.VN",
                        GoBackText = "Quay lại",
                        Messages = "Chúc mừng bạn, bạn đã đăng ký thành viên viphd.vn thành công. Chúng tôi không thể xác thực được email " + customer.Email + " của bạn hãy truy cập: http://viphd.vn/nguoi-dung/sua-thong-tin Tài khoản: " + customer.UserName + " Mật khẩu: " + Extensions.Constants.DefaultPassword
                    });
                }
            }
            else
            {
                customer.UserName = item.UserName;
                customer.Password = <PASSWORD>;
            }

            var user = service.Login(customer.UserName, customer.Password);
            if (user != null)
            {
                SetCustomerState(user);
                return RedirectToLocal(returnUrl);
            }

            return View("Messages", new MessageErrorModel
            {
                TitleForm = "Thông báo",
                GoBackText = "Quay lại",
                Messages = "Đăng nhập thất bại"
            });
        }

        [HttpPost, ValidateInput(false)]
        [Url("dang-ky-tai-khoan-vip")]
        public virtual ActionResult RegisterUser()
        {
            var email = Request.Form["txtEmail"];
            var password = Request.Form["txtPassword"];
            var comfim = Request.Form["txtComfim"];
            var fullName = Request.Form["txtFullName"];
            var captcha = Request.Form["txtCaptcha"];
            var result = new DataViewerModel();
            if (password != comfim)
            {
                result.Status = false;
                result.Data = "Mật khẩu xác nhận mật khẩu không đúng.";

                return Json(result);
            }

            if (string.IsNullOrEmpty(captcha) || captcha.ToUpper() != GlobalCapcha.ToUpper())
            {
                result.Status = false;
                result.Data = "Bạn nhập mã xác thực không đúng vui lòng nhập lại.";
                return Json(result);
            }

            var customer = new CustomerInfo
            {
                UserName = Utilities.RemoveInjection(email),
                Password = <PASSWORD>.Encrypt(KeyConfiguration.PublishKey, Utilities.RemoveInjection(password)),
                Email = Utilities.RemoveInjection(email),
                FullName = Utilities.RemoveInjection(fullName),
                Sex = 1,
                MemberDate = DateTime.Now.Date,
                Birthday = Utilities.DateNull(),
                VipXu = 0,
                Status = (int)Status.Approved,
                IsBlock = false,
                ImageIcon = Extensions.Constants.ImageMale
            };

            if (!Utilities.ValidateUserName(customer.UserName))
            {
                result.Status = false;
                result.Data = "Tài khoản là email hoặc tên không dấu và không có ký tự đặc biệt.";

                return Json(result);
            }

            var service = WorkContext.Resolve<ICustomerService>();
            var item = service.CheckRegister(customer.UserName);
            if (item != null)
            {
                result.Status = false;
                result.Data = "Tài khoản đã tồn tại trên hệ thống vui lòng nhập tài khoản khác.";

                return Json(result);
            }

            var cutomerCode = service.GetLatestCustomerCode();
            customer.CustomerCode = cutomerCode;
            service.Insert(customer);
            var user = service.Login(customer.UserName, customer.Password);
            result.Status = true;
            result.Data = "Không tìm thấy tài khoản của bạn vui lòng liên hệ quản trị.";
            if (user != null)
            {
                SetCustomerState(user);
                var status = SendEmailRegister("Thông tin đăng nhập thành viên VIPHD.VN", customer.CustomerCode, customer.UserName, Utilities.RemoveInjection(password), customer.Email);
                if (status)
                {
                    result.Status = true;
                    result.Data = "Chúc mừng bạn, bạn đã đăng ký thành viên viphd.vn thành công.<br/> Chúng tôi đã gửi thông tin tài khoản vào email<br/> " + customer.Email + ".";
                }
                else
                {
                    result.Status = true;
                    result.Data = "Chúc mừng bạn, bạn đã đăng ký thành viên viphd.vn thành công.<br/> Chúng tôi không thể xác thực được email<br/> " + customer.Email + " của bạn hãy truy cập<br/> http://viphd.vn/nguoi-dung/sua-thong-tin <br/>mật khẩu: " + Utilities.RemoveInjection(password);
                }
            }

            return Json(result);
        }

        [HttpPost, ValidateInput(false)]
        [Url("quen-mat-khau-thanh-vien")]
        public virtual ActionResult ForgetPasswordMember()
        {
            var email = Request.Form["txtEmail"];
            var captcha = Request.Form["txtCaptcha"];
            var result = new DataViewerModel();

            if (string.IsNullOrEmpty(captcha) || captcha.ToUpper() != GlobalCapcha.ToUpper())
            {
                result.Status = false;
                result.Data = "Bạn nhập mã xác thực không đúng vui lòng nhập lại.";
                return Json(result);
            }

            if (!Utilities.IsEmailValid(email))
            {
                result.Status = false;
                result.Data = "Email không đúng định dạng hoặc có ký tự đặc biệt.<br/> Định dạng chuẩn VD: <EMAIL>";

                return Json(result);
            }

            var newpass = EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, Utilities.GenerateUniqueNumber());
            var service = WorkContext.Resolve<ICustomerService>();
            var item = service.GetMemberForgetPassword(newpass, email.ToLower());
            if (item == null)
            {
                result.Status = false;
                result.Data = "Không tồn tại tài khoản có email này trên hệ thống.<br/> Vui lòng kiểm tra lại email.";

                return Json(result);
            }

            result.Status = true;
            result.Data = "Hệ thống đã gửi lại email cho bạn thông tin tài khoản.<br/> Bạn vui lòng đăng nhập vào email để nhận lại mật khẩu<br/> sau đó quay lại để sử dụng tài khoản của bạn.";
            try
            {
                SendEmailForgetPassword("Quên mật khẩu đăng nhập VIPHD.VN", item.CustomerCode, item.UserName, EncryptionExtensions.Decrypt(KeyConfiguration.PublishKey, item.Password), item.Email);
            }
            catch (Exception)
            {
                result.Status = false;
                result.Data = "Xin lỗi bạn hệ thống không thể gửi email cho bạn.<br/> Vui lòng liên hệ quản trị để được hỗ trợ.";
            }

            return Json(result);
        }

        public void SetCustomerState(CustomerInfo customer, bool isRemember = true)
        {
            if (customer!= null)
            {
                AddCookies(Extensions.Constants.GlobalCustomerCode, customer.CustomerCode, isRemember);
                AddCookies(Extensions.Constants.GlobalUserName, customer.UserName, isRemember);
                AddCookies(Extensions.Constants.GlobalFullName, customer.FullName, isRemember);
                AddCookies(Extensions.Constants.GlobalUserId, customer.Id.ToString(), isRemember);
                AddCookies(Extensions.Constants.GlobalVipXu, customer.VipXu.ToString(), isRemember);
                AddCookies(Extensions.Constants.GlobalTotalDay, customer.TotalDay.ToString(), isRemember);
                AddCookies(Extensions.Constants.GlobalStartDate, customer.StartDate != null ? customer.StartDate.Value.ToString(Extensions.Constants.DateTimeFomatFull) : "01/01/1900", isRemember);
                AddCookies(Extensions.Constants.GlobalEndDate, customer.EndDate != null ? customer.EndDate.Value.ToString(Extensions.Constants.DateTimeFomatFull) : "01/01/1900", isRemember);
                CurrentDate = DateTime.Now.Date;
            }
        }

        [HttpPost, ValidateInput(false)]
        [Url("khach-hang-dang-nhap")]
        public virtual ActionResult CustomerLogin()
        {
            var email = Request.Form["txtEmail"];
            var password = Request.Form["txtPassword"];
            var remember = Request.Form["ckbRemember"];
            var result = new DataViewerModel();
            if (!Utilities.ValidateUserName(email))
            {
                result = new DataViewerModel
                {
                    Status = false,
                    Data = T("Tài khoản là email hoặc tên không dấu và không có ký tự đặc biệt.")
                };

                return Json(result);
            }

            var service = WorkContext.Resolve<ICustomerService>();
            var user = service.Login(Utilities.RemoveInjection(email),
                EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, Utilities.RemoveInjection(password)));
            if (user != null)
            {
                var isRemember = false;
                if (!string.IsNullOrEmpty(remember))
                {
                    isRemember = bool.Parse(remember.Trim().TrimEnd(','));
                }
                SetCustomerState(user, isRemember);
                result = new DataViewerModel
                {
                    Status = true,
                    Url = UrlLogin
                };

                return Json(result);
            }

            result = new DataViewerModel
            {
                Status = false,
                Data = "Người dùng không tồn tại. Vui lòng kiểm tra lại."
            };

            return Json(result);
        }

        [HttpPost, ValidateInput(false)]
        [Url("check-login")]
        public virtual ActionResult CheckLogin()
        {
            var result = new DataViewerModel();
            if (!IsLogin)
            {
                result = new DataViewerModel
                {
                    Status = false,
                    Data = ""
                };

                return Json(result);
            }

            result = new DataViewerModel
            {
                Status = true,
                Data = ""
            };

            return Json(result);
        }

        [HttpPost, ValidateInput(false)]
        [Url("get-vip-informations")]
        public virtual ActionResult GetVip()
        {
            var result = new DataViewerModel();
            if (!IsLogin || !IsVip)
            {
                result = new DataViewerModel
                {
                    Status = false
                };

                return Json(result);
            }

            result = new DataViewerModel
            {
                Status = IsVip
            };

            if (EndDate == Utilities.DateNull())
            {
                result.Data = string.Empty;
            }
            else
            {
                result.Data = EndDate.ToString(Extensions.Constants.DateTimeFomatFull2);
            }

            return Json(result);
        }

        [HttpGet]
        [Url("nguoi-dung/dang-xuat")]
        public virtual ActionResult UserLogout()
        {
            RemoveCookies(Extensions.Constants.GlobalCustomerCode);
            RemoveCookies(Extensions.Constants.GlobalUserName);
            RemoveCookies(Extensions.Constants.GlobalFullName);
            RemoveCookies(Extensions.Constants.GlobalUserId);
            RemoveCookies(Extensions.Constants.GlobalVipXu);
            RemoveCookies(Extensions.Constants.GlobalTotalDay);
            RemoveCookies(Extensions.Constants.GlobalStartDate);
            RemoveCookies(Extensions.Constants.GlobalEndDate);
            Session.RemoveAll();

            return RedirectToLocal(Url.Action("Index", "Home"));
        }
        #endregion

        #region News
        [HttpPost, ValidateInput(false)]
        [Url("list-news-by-category")]
        public virtual ActionResult GetNewsByCategory(string category)
        {
            var id = category == "all" ? 0 : int.Parse(category);
            var service = WorkContext.Resolve<IArticlesService>();
            service.LanguageCode = WorkContext.CurrentCulture;
            service.CategoryId = id;
            service.SiteId = SiteId;
            var data = service.BuildNewsByCategory();
            var html = new StringBuilder();
            if (data != null && data.Count > 0)
            {
                foreach (var item in data)
                {
                    var url = Url.Action("ViewDetails", "HomeNews", new { @alias = item.Alias, @id = item.Id });
                    html.Append("<li>");
                    html.Append("<p>");
                    html.Append("<a title='" + item.Title + "' href='" + url + "'>" + item.Title + "</a>");
                    if (item.ViewCount > 10)
                    {
                        html.Append(" <span class='icon-nnews'></span>");
                    }
                    html.Append("</p>");
                    html.Append("<span class='time-tem'>" + item.TextPublishedDate + "</span>");
                    html.Append("</li>");
                }
                html.Append("<li class='li-see_a-link'><a title='Xem thêm' href='" + Url.Action("Index", "HomeNews") + "'>Xem thêm >></a></li>");
            }
            var result = new DataViewerModel();
            result = new DataViewerModel
            {
                Status = true,
                Data = html.ToString()
            };

            return Json(result);
        }
        #endregion

        #region Capcha
        [HttpPost, ValidateInput(false)]
        [Url("capcha/auto-generate")]
        public virtual ActionResult CapchaGenerate(string token)
        {
            Session[Extensions.Constants.GlobalCapcha] = CaptchaImage.GenerateRandomCode();
            var capchaImage = new CaptchaImage(GlobalCapcha).GetCapchaImage();
            var result = new DataViewerModel
            {
                Status = true,
                Data = capchaImage
            };

            return Json(result);
        }
        #endregion

        #region Send Emails
        public bool SendEmailForgetPassword(string subject, string customerCode, string username, string password, string toEmailReceive)
        {
            try
            {
                string html = System.IO.File.ReadAllText(Server.MapPath("~/Media/Default/EmailTemplates/MemberForgetPassword.html"));
                html = html.Replace("[CODE]", customerCode);
                html = html.Replace("[EMAIL]", toEmailReceive.ToLower().Trim());
                html = html.Replace("[USERNAME]", username.ToLower().Trim());
                html = html.Replace("[PASSWORD]", password.Trim());
                SendEmail(subject, html, toEmailReceive, string.Empty);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool SendEmailRegister(string subject, string customerCode, string username, string password, string toEmailReceive)
        {
            try
            {
                string html = System.IO.File.ReadAllText(Server.MapPath("~/Media/Default/EmailTemplates/MemberRegister.html"));
                html = html.Replace("[CODE]", customerCode);
                html = html.Replace("[EMAIL]", toEmailReceive.ToLower().Trim());
                html = html.Replace("[USERNAME]", username.ToLower().Trim());
                html = html.Replace("[PASSWORD]", password.Trim());
                SendEmail(subject, html, toEmailReceive, "<EMAIL>");
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public void SendEmail(string subject, string body, string toEmailReceive, string ccEmail)
        {
            var service = WorkContext.Resolve<IEmailSender>();
            var mailMessage = new MailMessage
            {
                Subject = subject,
                SubjectEncoding = Encoding.UTF8,
                Body = body,
                BodyEncoding = Encoding.UTF8,
                IsBodyHtml = true
            };
            
            mailMessage.Sender = new MailAddress(toEmailReceive);
            mailMessage.To.Add(toEmailReceive);
            if (!string.IsNullOrEmpty(ccEmail))
            {
                mailMessage.CC.Add(ccEmail);
                mailMessage.Bcc.Add("<EMAIL>");
            }

            service.Send(mailMessage);
        }
        #endregion

        #region Films
        [HttpPost, ValidateInput(false)]
        [Url("list-films-by-type")]
        public virtual ActionResult GetFilmByType(int type, int statistical = 0)
        {
            var serviceFilms = WorkContext.Resolve<IFilmService>();
            serviceFilms.SiteId = SiteId;
            serviceFilms.LanguageCode = WorkContext.CurrentCulture;
            var result = new DataViewerModel{Status = false, Data = ""};
            switch ((HomeDisplayFilmType)type)
            {
                #region FilmHot
                case HomeDisplayFilmType.FilmHot:
                    {
                        var listFilmHot = serviceFilms.BuildFilmHot();
                        var html = new StringBuilder();
                        if (listFilmHot != null && listFilmHot.Count > 0)
                        {
                            var count = listFilmHot.Count % 8;
                            var total = listFilmHot.Count - count;
                            for (int i = 7; i < total; i += 8)
                            {

                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");

                                #region Item 1

                                var index = i - 7;
                                html.Append(BuildItem(listFilmHot[index], index, true));

                                #endregion

                                #region Item 2

                                index = i - 6;
                                html.Append(BuildItem(listFilmHot[index], index, true));

                                #endregion

                                #region Item 3

                                index = i - 5;
                                html.Append(BuildItem(listFilmHot[index], index, true));

                                #endregion

                                #region Item 4

                                index = i - 4;
                                html.Append(BuildItem(listFilmHot[index], index, true));

                                #endregion

                                #region Item 5

                                index = i - 3;
                                html.Append(BuildItem(listFilmHot[index], index, true));

                                #endregion

                                #region Item 6

                                index = i - 2;
                                html.Append(BuildItem(listFilmHot[index], index, true));

                                #endregion

                                #region Item 7

                                index = i - 1;
                                html.Append(BuildItem(listFilmHot[index], index, true));

                                #endregion

                                #region Item 8

                                index = i;
                                html.Append(BuildItem(listFilmHot[index], index, true));

                                #endregion

                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }

                            if (count > 0)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");
                                for (int i = 0; i < count; i++)
                                {
                                    var index = i;
                                    if (total > 0)
                                    {
                                        index = total + i;
                                    }
                                    html.Append(BuildItem(listFilmHot[index], index, true));
                                }
                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            } 
                        }

                        result = new DataViewerModel
                        {
                            Status = true,
                            Data = html.ToString()
                        };
                    }
                    break;
                #endregion

                #region FilmRetail
                case HomeDisplayFilmType.FilmRetail:
                    {
                        var listFilmRetail = serviceFilms.BuildFilmRetail();
                        var html = new StringBuilder();
                        if (listFilmRetail != null && listFilmRetail.Count > 0)
                        {
                            var count = listFilmRetail.Count % 8;
                            var total = listFilmRetail.Count - count;
                            for (int i = 7; i < total; i += 8)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");

                                #region Item 1
                                var index = i - 7;
                                html.Append(BuildItem(listFilmRetail[index], index, false));
                                #endregion

                                #region Item 2
                                index = i - 6;
                                html.Append(BuildItem(listFilmRetail[index], index, false));
                                #endregion

                                #region Item 3
                                index = i - 5;
                                html.Append(BuildItem(listFilmRetail[index], index, false));
                                #endregion

                                #region Item 4
                                index = i - 4;
                                html.Append(BuildItem(listFilmRetail[index], index, false));
                                #endregion

                                #region Item 5
                                index = i - 3;
                                html.Append(BuildItem(listFilmRetail[index], index, false));
                                #endregion

                                #region Item 6
                                index = i - 2;
                                html.Append(BuildItem(listFilmRetail[index], index, false));
                                #endregion

                                #region Item 7
                                index = i - 1;
                                html.Append(BuildItem(listFilmRetail[index], index, false));
                                #endregion

                                #region Item 8
                                index = i;
                                html.Append(BuildItem(listFilmRetail[index], index, false));
                                #endregion

                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }

                            if (count > 0)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");
                                for (int i = 0; i < count; i++)
                                {
                                    var index = i;
                                    if (total > 0)
                                    {
                                        index = total + i;
                                    }
                                    html.Append(BuildItem(listFilmRetail[index], index, false));
                                }
                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                        }

                        result = new DataViewerModel
                        {
                            Status = true,
                            Data = html.ToString()
                        };
                    }
                    break;
                #endregion

                #region FilmLengthEpisodes
                case HomeDisplayFilmType.FilmLengthEpisodes:
                    {
                        var listFilmLengthEpisodes = serviceFilms.BuildFilmManyEpisodes();
                        var html = new StringBuilder();
                        if (listFilmLengthEpisodes != null && listFilmLengthEpisodes.Count > 0)
                        {
                            var count = listFilmLengthEpisodes.Count % 8;
                            var total = listFilmLengthEpisodes.Count - count;
                            for (int i = 7; i < total; i += 8)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");

                                #region Item 1
                                var index = i - 7;
                                html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                #endregion

                                #region Item 2
                                index = i - 6;
                                html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                #endregion

                                #region Item 3
                                index = i - 5;
                                html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                #endregion

                                #region Item 4
                                index = i - 4;
                                html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                #endregion

                                #region Item 5
                                index = i - 3;
                                html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                #endregion

                                #region Item 6
                                index = i - 2;
                                html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                #endregion

                                #region Item 7
                                index = i - 1;
                                html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                #endregion

                                #region Item 8
                                index = i;
                                html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                #endregion

                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }

                            if (count > 0)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");
                                for (int i = 0; i < count; i++)
                                {
                                    var index = i;
                                    if (total > 0)
                                    {
                                        index = total + i;
                                    }
                                    html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                }
                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                        }

                        result = new DataViewerModel
                        {
                            Status = true,
                            Data = html.ToString()
                        };
                    }
                    break;
                #endregion

                #region FilmJJChannelIntroduce
                case HomeDisplayFilmType.FilmJJChannelIntroduce:
                    {
                        serviceFilms.CategoryId = 0;
                        var listFilmJJChannelIntroduce = serviceFilms.BuildFilmJJChannelIntroduce();
                        var html = new StringBuilder();
                        if (listFilmJJChannelIntroduce != null && listFilmJJChannelIntroduce.Count > 0)
                        {
                            var count = listFilmJJChannelIntroduce.Count % 8;
                            var total = listFilmJJChannelIntroduce.Count - count;
                            for (int i = 7; i < total; i += 8)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");

                                #region Item 1
                                var index = i - 7;
                                html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                #endregion

                                #region Item 2
                                index = i - 6;
                                html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                #endregion

                                #region Item 3
                                index = i - 5;
                                html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                #endregion

                                #region Item 4
                                index = i - 4;
                                html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                #endregion

                                #region Item 5
                                index = i - 3;
                                html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                #endregion

                                #region Item 6
                                index = i - 2;
                                html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                #endregion

                                #region Item 7
                                index = i - 1;
                                html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                #endregion

                                #region Item 8
                                index = i;
                                html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                #endregion

                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }

                            if (count > 0)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");
                                for (int i = 0; i < count; i++)
                                {
                                    var index = i;
                                    if (total > 0)
                                    {
                                        index = total + i;
                                    }
                                    html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                }
                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                        }

                        result = new DataViewerModel
                        {
                            Status = true,
                            Data = html.ToString()
                        };
                    }
                    break;
                #endregion

                #region FilmTheater
                case HomeDisplayFilmType.FilmTheater:
                    {
                        var listFilmTheater = serviceFilms.BuildFilmTheater();
                        var html = new StringBuilder();
                        if (listFilmTheater != null && listFilmTheater.Count > 0)
                        {
                            var count = listFilmTheater.Count % 8;
                            var total = listFilmTheater.Count - count;
                            for (int i = 7; i < total; i += 8)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");

                                #region Item 1
                                var index = i - 7;
                                html.Append(BuildItem(listFilmTheater[index], index, false));
                                #endregion

                                #region Item 2
                                index = i - 6;
                                html.Append(BuildItem(listFilmTheater[index], index, false));
                                #endregion

                                #region Item 3
                                index = i - 5;
                                html.Append(BuildItem(listFilmTheater[index], index, false));
                                #endregion

                                #region Item 4
                                index = i - 4;
                                html.Append(BuildItem(listFilmTheater[index], index, false));
                                #endregion

                                #region Item 5
                                index = i - 3;
                                html.Append(BuildItem(listFilmTheater[index], index, false));
                                #endregion

                                #region Item 6
                                index = i - 2;
                                html.Append(BuildItem(listFilmTheater[index], index, false));
                                #endregion

                                #region Item 7
                                index = i - 1;
                                html.Append(BuildItem(listFilmTheater[index], index, false));
                                #endregion

                                #region Item 8
                                index = i;
                                html.Append(BuildItem(listFilmTheater[index], index, false));
                                #endregion

                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }

                            if (count > 0)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");
                                for (int i = 0; i < count; i++)
                                {
                                    var index = i;
                                    if (total > 0)
                                    {
                                        index = total + i;
                                    }
                                    html.Append(BuildItem(listFilmTheater[index], index, false));
                                }
                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                        }

                        result = new DataViewerModel
                        {
                            Status = true,
                            Data = html.ToString()
                        };
                    }
                    break;
                #endregion

                #region TVShow
                case HomeDisplayFilmType.TVShow:
                    {
                        serviceFilms.CategoryId = 0;
                        var listTVShows = serviceFilms.BuildTVShow();
                        var html = new StringBuilder();
                        if (listTVShows != null && listTVShows.Count > 0)
                        {
                            var count = listTVShows.Count%2;
                            var total = listTVShows.Count - count;
                            for (int i = 1; i < total; i += 2)
                            {
                                var item = listTVShows[i - 1];
                                var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id });
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango member-item\">");
                                html.Append("<li>");
                                html.Append("<div class=\"slide_child_div_dt2col item\">");
                                html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url, item.FilmName);
                                html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\">", item.ImageIcon, item.FilmNameEnglish, item.FilmName);
                                html.Append("<p class=\"title_film_child\">");
                                html.AppendFormat("<span class=\"orange_color\">{0}</span>", item.FilmNameEnglish);
                                html.AppendFormat("<span>{0}</span>", item.FilmName);
                                html.Append("</p>");
                                html.AppendFormat("<span class=\"mask-num-film\">Tập <p>{0}</p></span>", item.EpisodeCount);
                                html.Append("</a>");

                                html.AppendFormat("<div class=\"tooltip_description\" style=\"display:none\" title=\"Item {0} Description\">", i);
                                html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", (string.IsNullOrEmpty(item.FilmNameEnglish) ? item.FilmName : item.FilmNameEnglish), url, item.FilmName);
                                html.Append("<div class=\"film-info\">");
                                html.AppendFormat("<span>Số tập: </span><label>{0}</label></br>", item.EpisodeCount);
                                html.AppendFormat("<span>Thể loại phim: </span><label>{0}</label></br>", item.FilmTypeNames);
                                html.AppendFormat("<span>Quốc gia: </span><label>{0}</label></br>", item.CountryName);
                                html.AppendFormat("<span>Thời lượng: </span><label>{0}</label></br>", item.Time);
                                html.AppendFormat("<span>Dung lượng: </span><label>{0}</label>", item.Capacity);
                                html.Append("</div>");
                                html.Append("<div class=\"film-body\">");
                                html.AppendFormat("<p>{0}</p>", item.Summary);
                                html.Append("</div>");
                                html.Append("</div>");

                                html.Append("</div>");
                                html.Append("</li> ");

                                var item2 = listTVShows[i];
                                var url2 = Url.Action("FilmView", "HomeView", new { @alias = item2.FilmAlias, @id = item2.Id });
                                html.Append("<li>");
                                html.Append("<div class=\"slide_child_div_dt2col item\">");
                                html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url2, item2.FilmName);
                                html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\">", item2.ImageIcon, item2.FilmNameEnglish, item2.FilmName);
                                html.Append("<p class=\"title_film_child\">");
                                html.AppendFormat("<span class=\"orange_color\">{0}</span>", item2.FilmNameEnglish);
                                html.AppendFormat("<span>{0}</span>", item2.FilmName);
                                html.Append("</p>");
                                html.AppendFormat("<span class=\"mask-num-film\">Tập <p>{0}</p></span>", item2.EpisodeCount);
                                html.Append("</a>");
                                
                                html.AppendFormat("<div class=\"tooltip_description\" style=\"display:none\" title=\"Item {0} Description\">", i);
                                html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", (string.IsNullOrEmpty(item2.FilmNameEnglish) ? item2.FilmName : item2.FilmNameEnglish), url2, item2.FilmName);
                                html.Append("<div class=\"film-info\">");
                                html.AppendFormat("<span>Số tập: </span><label>{0}</label></br>", item2.EpisodeCount);
                                html.AppendFormat("<span>Thể loại phim: </span><label>{0}</label></br>", item2.FilmTypeNames);
                                html.AppendFormat("<span>Quốc gia: </span><label>{0}</label></br>", item2.CountryName);
                                html.AppendFormat("<span>Thời lượng: </span><label>{0}</label></br>", item2.Time);
                                html.AppendFormat("<span>Dung lượng: </span><label>{0}</label>", item2.Capacity);
                                html.Append("</div>");
                                html.Append("<div class=\"film-body\">");
                                html.AppendFormat("<p>{0}</p>", item2.Summary);
                                html.Append("</div>");
                                html.Append("</div>");

                                html.Append("</div>");
                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                            if (count > 0)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango member-item\">");
                                html.Append("<li>");
                                for (int i = 0; i < count; i++)
                                {
                                    var item = listTVShows[i];
                                    var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id });
                                    if (total > 0)
                                    {
                                        item = listTVShows[total + i];
                                    }

                                    html.Append("<div class=\"slide_child_div_dt2col item\">");
                                    html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url, item.FilmName);
                                    html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\">", item.ImageIcon, item.FilmNameEnglish, item.FilmName);
                                    html.Append("<p class=\"title_film_child\">");
                                    html.AppendFormat("<span class=\"orange_color\">{0}</span>", item.FilmNameEnglish);
                                    html.AppendFormat("<span>{0}</span>", item.FilmName);
                                    html.Append("</p>");
                                    html.AppendFormat("<span class=\"mask-num-film\">Tập <p>{0}</p></span>", item.EpisodeCount);
                                    html.Append("</a>");

                                    html.AppendFormat("<div class=\"tooltip_description\" style=\"display:none\" title=\"Item {0} Description\">", listTVShows.Count - 1);
                                    html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", (string.IsNullOrEmpty(item.FilmNameEnglish) ? item.FilmName : item.FilmNameEnglish), url, item.FilmName);
                                    html.Append("<div class=\"film-info\">");
                                    html.AppendFormat("<span>Số tập: </span><label>{0}</label></br>", item.EpisodeCount);
                                    html.AppendFormat("<span>Thể loại phim: </span><label>{0}</label></br>", item.FilmTypeNames);
                                    html.AppendFormat("<span>Quốc gia: </span><label>{0}</label></br>", item.CountryName);
                                    html.AppendFormat("<span>Thời lượng: </span><label>{0}</label></br>", item.Time);
                                    html.AppendFormat("<span>Dung lượng: </span><label>{0}</label>", item.Capacity);
                                    html.Append("</div>");
                                    html.Append("<div class=\"film-body\">");
                                    html.AppendFormat("<p>{0}</p>", item.Summary);
                                    html.Append("</div>");
                                    html.Append("</div>");
                                    html.Append("</div>");
                                }
                                
                                html.Append("</li> ");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                        }

                        result = new DataViewerModel
                        {
                            Status = true,
                            Data = html.ToString()
                        };
                    }
                    break;
                #endregion

                #region Clips
                case HomeDisplayFilmType.Clip:
                    {
                        serviceFilms.CategoryId = 5;
                        var listClips = serviceFilms.BuildClips();
                        var html = new StringBuilder();
                        if (listClips != null && listClips.Count > 0)
                        {
                            var count = listClips.Count%8;
                            var total = listClips.Count - count;
                            for (int i = 7; i < total; i += 8)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango member-item\">");
                                html.Append("<li>");

                                var index = i - 7;
                                html.Append(BuildItemClip(listClips[index], index));

                                index = i - 6;
                                html.Append(BuildItemClip(listClips[index], index));

                                index = i - 5;
                                html.Append(BuildItemClip(listClips[index], index));

                                index = i - 4;
                                html.Append(BuildItemClip(listClips[index], index));

                                index = i - 3;
                                html.Append(BuildItemClip(listClips[index], index));

                                index = i - 2;
                                html.Append(BuildItemClip(listClips[index], index));

                                index = i - 1;
                                html.Append(BuildItemClip(listClips[index], index));

                                index = i;
                                html.Append(BuildItemClip(listClips[index], index));

                                html.Append("</li> ");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                            if (count > 0)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango member-item\">");
                                html.Append("<li>");
                                for (int i = 0; i < count; i++)
                                {
                                    var index = i;
                                    if (total > 0)
                                    {
                                        index = total + i;
                                    }
                                    html.Append(BuildItemClip(listClips[index], index));
                                }
                                
                                html.Append("</li> ");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                        }

                        result = new DataViewerModel
                        {
                            Status = true,
                            Data = html.ToString()
                        };
                    }
                    break;
                #endregion

                #region Statistical FilmRetail
                case HomeDisplayFilmType.StatisticalFilmRetail:
                    {
                        var listStatisticalFilmRetail = serviceFilms.BuildStatistical1(30, statistical);
                        var html = new StringBuilder();
                        if (listStatisticalFilmRetail != null && listStatisticalFilmRetail.Count > 0)
                        {
                            foreach (var item in listStatisticalFilmRetail)
                            {
                                html.Append(BuildItemStatistical(item));
                            }
                        }

                        result = new DataViewerModel
                        {
                            Status = true,
                            Data = html.ToString()
                        };
                    }
                    break;
                #endregion

                #region Statistical FilmLengthEpisodes
                case HomeDisplayFilmType.StatisticalLengthEpisodes:
                    {
                        var listStatisticalFilmRetail = serviceFilms.BuildStatistical2(30, statistical);
                        var html = new StringBuilder();
                        if (listStatisticalFilmRetail != null && listStatisticalFilmRetail.Count > 0)
                        {
                            foreach (var item in listStatisticalFilmRetail)
                            {
                                html.Append(BuildItemStatistical(item));
                            }
                        }

                        result = new DataViewerModel
                        {
                            Status = true,
                            Data = html.ToString()
                        };
                    }
                    break;
                #endregion

                #region Statistical Shows
                case HomeDisplayFilmType.StatisticalShows:
                    {
                        var listStatisticalShows = serviceFilms.BuildStatistical3(30, statistical);
                        var html = new StringBuilder();
                        if (listStatisticalShows != null && listStatisticalShows.Count > 0)
                        {
                            foreach (var item in listStatisticalShows)
                            {
                                html.Append(BuildItemStatistical(item));
                            }
                        }

                        result = new DataViewerModel
                        {
                            Status = true,
                            Data = html.ToString()
                        };
                    }
                    break;
                #endregion

                #region Statistical Clips
                case HomeDisplayFilmType.StatisticalClips:
                    {
                        var listStatisticalClips = serviceFilms.BuildStatistical4(30, statistical);
                        var html = new StringBuilder();
                        if (listStatisticalClips != null && listStatisticalClips.Count > 0)
                        {
                            foreach (var item in listStatisticalClips)
                            {
                                html.Append(BuildClip(item));
                            }
                        }

                        result = new DataViewerModel
                        {
                            Status = true,
                            Data = html.ToString()
                        };
                    }
                    break;
                #endregion

                #region Statistical Trailer
                case HomeDisplayFilmType.StatisticalTrailer:
                    {
                        var listStatisticalTrailer = serviceFilms.BuildStatistical5(30, statistical);
                        var html = new StringBuilder();
                        if (listStatisticalTrailer != null && listStatisticalTrailer.Count > 0)
                        {
                            foreach (var item in listStatisticalTrailer)
                            {
                                html.Append(BuildTrailer(item));
                            }
                        }

                        result = new DataViewerModel
                        {
                            Status = true,
                            Data = html.ToString()
                        };
                    }
                    break;
                #endregion

                #region Statistical Trailer
                case HomeDisplayFilmType.StatisticalNextFilm:
                    {
                        var listStatisticalTrailer = serviceFilms.BuildStatistical5(30, statistical);
                        var html = new StringBuilder();
                        if (listStatisticalTrailer != null && listStatisticalTrailer.Count > 0)
                        {
                            foreach (var item in listStatisticalTrailer)
                            {
                                html.Append(BuildTrailer(item));
                            }
                        }

                        result = new DataViewerModel
                        {
                            Status = true,
                            Data = html.ToString()
                        };
                    }
                    break;
                #endregion
            }
           
            return Json(result);
        }

        public string GetFilmHtml(int type, int statistical = 0)
        {
            var serviceFilms = WorkContext.Resolve<IFilmService>();
            serviceFilms.SiteId = SiteId;
            serviceFilms.LanguageCode = WorkContext.CurrentCulture;
            switch ((HomeDisplayFilmType)type)
            {
                #region FilmHot
                case HomeDisplayFilmType.FilmHot:
                    {
                        var listFilmHot = serviceFilms.BuildFilmHot();
                        var html = new StringBuilder();
                        if (listFilmHot != null && listFilmHot.Count > 0)
                        {
                            var count = listFilmHot.Count % 8;
                            var total = listFilmHot.Count - count;
                            for (int i = 7; i < total; i += 8)
                            {

                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");

                                #region Item 1

                                var index = i - 7;
                                html.Append(BuildItem(listFilmHot[index], index, true));

                                #endregion

                                #region Item 2

                                index = i - 6;
                                html.Append(BuildItem(listFilmHot[index], index, true));

                                #endregion

                                #region Item 3

                                index = i - 5;
                                html.Append(BuildItem(listFilmHot[index], index, true));

                                #endregion

                                #region Item 4

                                index = i - 4;
                                html.Append(BuildItem(listFilmHot[index], index, true));

                                #endregion

                                #region Item 5

                                index = i - 3;
                                html.Append(BuildItem(listFilmHot[index], index, true));

                                #endregion

                                #region Item 6

                                index = i - 2;
                                html.Append(BuildItem(listFilmHot[index], index, true));

                                #endregion

                                #region Item 7

                                index = i - 1;
                                html.Append(BuildItem(listFilmHot[index], index, true));

                                #endregion

                                #region Item 8

                                index = i;
                                html.Append(BuildItem(listFilmHot[index], index, true));

                                #endregion

                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }

                            if (count > 0)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");
                                for (int i = 0; i < count; i++)
                                {
                                    var index = i;
                                    if (total > 0)
                                    {
                                        index = total + i;
                                    }
                                    html.Append(BuildItem(listFilmHot[index], index, true));
                                }
                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                        }

                        return html.ToString();
                    }
                #endregion

                #region FilmRetail
                case HomeDisplayFilmType.FilmRetail:
                    {
                        var listFilmRetail = serviceFilms.BuildFilmRetail();
                        var html = new StringBuilder();
                        if (listFilmRetail != null && listFilmRetail.Count > 0)
                        {
                            var count = listFilmRetail.Count % 8;
                            var total = listFilmRetail.Count - count;
                            for (int i = 7; i < total; i += 8)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");

                                #region Item 1
                                var index = i - 7;
                                html.Append(BuildItem(listFilmRetail[index], index, false));
                                #endregion

                                #region Item 2
                                index = i - 6;
                                html.Append(BuildItem(listFilmRetail[index], index, false));
                                #endregion

                                #region Item 3
                                index = i - 5;
                                html.Append(BuildItem(listFilmRetail[index], index, false));
                                #endregion

                                #region Item 4
                                index = i - 4;
                                html.Append(BuildItem(listFilmRetail[index], index, false));
                                #endregion

                                #region Item 5
                                index = i - 3;
                                html.Append(BuildItem(listFilmRetail[index], index, false));
                                #endregion

                                #region Item 6
                                index = i - 2;
                                html.Append(BuildItem(listFilmRetail[index], index, false));
                                #endregion

                                #region Item 7
                                index = i - 1;
                                html.Append(BuildItem(listFilmRetail[index], index, false));
                                #endregion

                                #region Item 8
                                index = i;
                                html.Append(BuildItem(listFilmRetail[index], index, false));
                                #endregion

                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }

                            if (count > 0)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");
                                for (int i = 0; i < count; i++)
                                {
                                    var index = i;
                                    if (total > 0)
                                    {
                                        index = total + i;
                                    }
                                    html.Append(BuildItem(listFilmRetail[index], index, false));
                                }
                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                        }

                        return html.ToString();
                    }
                #endregion

                #region FilmLengthEpisodes
                case HomeDisplayFilmType.FilmLengthEpisodes:
                    {
                        var listFilmLengthEpisodes = serviceFilms.BuildFilmManyEpisodes();
                        var html = new StringBuilder();
                        if (listFilmLengthEpisodes != null && listFilmLengthEpisodes.Count > 0)
                        {
                            var count = listFilmLengthEpisodes.Count % 8;
                            var total = listFilmLengthEpisodes.Count - count;
                            for (int i = 7; i < total; i += 8)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");

                                #region Item 1
                                var index = i - 7;
                                html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                #endregion

                                #region Item 2
                                index = i - 6;
                                html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                #endregion

                                #region Item 3
                                index = i - 5;
                                html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                #endregion

                                #region Item 4
                                index = i - 4;
                                html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                #endregion

                                #region Item 5
                                index = i - 3;
                                html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                #endregion

                                #region Item 6
                                index = i - 2;
                                html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                #endregion

                                #region Item 7
                                index = i - 1;
                                html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                #endregion

                                #region Item 8
                                index = i;
                                html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                #endregion

                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }

                            if (count > 0)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");
                                for (int i = 0; i < count; i++)
                                {
                                    var index = i;
                                    if (total > 0)
                                    {
                                        index = total + i;
                                    }
                                    html.Append(BuildItem(listFilmLengthEpisodes[index], index, true));
                                }
                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                        }

                        return html.ToString();
                    }
                #endregion

                #region FilmJJChannelIntroduce
                case HomeDisplayFilmType.FilmJJChannelIntroduce:
                    {
                        serviceFilms.CategoryId = 0;
                        var listFilmJJChannelIntroduce = serviceFilms.BuildFilmJJChannelIntroduce();
                        var html = new StringBuilder();
                        if (listFilmJJChannelIntroduce != null && listFilmJJChannelIntroduce.Count > 0)
                        {
                            var count = listFilmJJChannelIntroduce.Count % 8;
                            var total = listFilmJJChannelIntroduce.Count - count;
                            for (int i = 7; i < total; i += 8)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");

                                #region Item 1
                                var index = i - 7;
                                html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                #endregion

                                #region Item 2
                                index = i - 6;
                                html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                #endregion

                                #region Item 3
                                index = i - 5;
                                html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                #endregion

                                #region Item 4
                                index = i - 4;
                                html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                #endregion

                                #region Item 5
                                index = i - 3;
                                html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                #endregion

                                #region Item 6
                                index = i - 2;
                                html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                #endregion

                                #region Item 7
                                index = i - 1;
                                html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                #endregion

                                #region Item 8
                                index = i;
                                html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                #endregion

                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }

                            if (count > 0)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");
                                for (int i = 0; i < count; i++)
                                {
                                    var index = i;
                                    if (total > 0)
                                    {
                                        index = total + i;
                                    }
                                    html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true));
                                }
                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                        }

                        return html.ToString();
                    }
                #endregion

                #region FilmTheater
                case HomeDisplayFilmType.FilmTheater:
                    {
                        var listFilmTheater = serviceFilms.BuildFilmTheater();
                        var html = new StringBuilder();
                        if (listFilmTheater != null && listFilmTheater.Count > 0)
                        {
                            var count = listFilmTheater.Count % 8;
                            var total = listFilmTheater.Count - count;
                            for (int i = 7; i < total; i += 8)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");

                                #region Item 1
                                var index = i - 7;
                                html.Append(BuildItem(listFilmTheater[index], index, false));
                                #endregion

                                #region Item 2
                                index = i - 6;
                                html.Append(BuildItem(listFilmTheater[index], index, false));
                                #endregion

                                #region Item 3
                                index = i - 5;
                                html.Append(BuildItem(listFilmTheater[index], index, false));
                                #endregion

                                #region Item 4
                                index = i - 4;
                                html.Append(BuildItem(listFilmTheater[index], index, false));
                                #endregion

                                #region Item 5
                                index = i - 3;
                                html.Append(BuildItem(listFilmTheater[index], index, false));
                                #endregion

                                #region Item 6
                                index = i - 2;
                                html.Append(BuildItem(listFilmTheater[index], index, false));
                                #endregion

                                #region Item 7
                                index = i - 1;
                                html.Append(BuildItem(listFilmTheater[index], index, false));
                                #endregion

                                #region Item 8
                                index = i;
                                html.Append(BuildItem(listFilmTheater[index], index, false));
                                #endregion

                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }

                            if (count > 0)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                                html.Append("<li>");
                                for (int i = 0; i < count; i++)
                                {
                                    var index = i;
                                    if (total > 0)
                                    {
                                        index = total + i;
                                    }
                                    html.Append(BuildItem(listFilmTheater[index], index, false));
                                }
                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                        }

                        return html.ToString();
                    }
                #endregion

                #region TVShow
                case HomeDisplayFilmType.TVShow:
                    {
                        serviceFilms.CategoryId = 0;
                        var listTVShows = serviceFilms.BuildTVShow();
                        var html = new StringBuilder();
                        if (listTVShows != null && listTVShows.Count > 0)
                        {
                            var count = listTVShows.Count % 2;
                            var total = listTVShows.Count - count;
                            for (int i = 1; i < total; i += 2)
                            {
                                var item = listTVShows[i - 1];
                                var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id });
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango member-item\">");
                                html.Append("<li>");
                                html.Append("<div class=\"slide_child_div_dt2col item\">");
                                html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url, item.FilmName);
                                html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\">", item.ImageIcon, item.FilmNameEnglish, item.FilmName);
                                html.Append("<p class=\"title_film_child\">");
                                html.AppendFormat("<span class=\"orange_color\">{0}</span>", item.FilmNameEnglish);
                                html.AppendFormat("<span>{0}</span>", item.FilmName);
                                html.Append("</p>");
                                html.AppendFormat("<span class=\"mask-num-film\">Tập <p>{0}</p></span>", item.EpisodeCount);
                                html.Append("</a>");

                                html.AppendFormat("<div class=\"tooltip_description\" style=\"display:none\" title=\"Item {0} Description\">", i);
                                html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", (string.IsNullOrEmpty(item.FilmNameEnglish) ? item.FilmName : item.FilmNameEnglish), url, item.FilmName);
                                html.Append("<div class=\"film-info\">");
                                html.AppendFormat("<span>Số tập: </span><label>{0}</label></br>", item.EpisodeCount);
                                html.AppendFormat("<span>Thể loại phim: </span><label>{0}</label></br>", item.FilmTypeNames);
                                html.AppendFormat("<span>Quốc gia: </span><label>{0}</label></br>", item.CountryName);
                                html.AppendFormat("<span>Thời lượng: </span><label>{0}</label></br>", item.Time);
                                html.AppendFormat("<span>Dung lượng: </span><label>{0}</label>", item.Capacity);
                                html.Append("</div>");
                                html.Append("<div class=\"film-body\">");
                                html.AppendFormat("<p>{0}</p>", item.Summary);
                                html.Append("</div>");
                                html.Append("</div>");

                                html.Append("</div>");
                                html.Append("</li> ");

                                var item2 = listTVShows[i];
                                var url2 = Url.Action("FilmView", "HomeView", new { @alias = item2.FilmAlias, @id = item2.Id });
                                html.Append("<li>");
                                html.Append("<div class=\"slide_child_div_dt2col item\">");
                                html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url2, item2.FilmName);
                                html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\">", item2.ImageIcon, item2.FilmNameEnglish, item2.FilmName);
                                html.Append("<p class=\"title_film_child\">");
                                html.AppendFormat("<span class=\"orange_color\">{0}</span>", item2.FilmNameEnglish);
                                html.AppendFormat("<span>{0}</span>", item2.FilmName);
                                html.Append("</p>");
                                html.AppendFormat("<span class=\"mask-num-film\">Tập <p>{0}</p></span>", item2.EpisodeCount);
                                html.Append("</a>");

                                html.AppendFormat("<div class=\"tooltip_description\" style=\"display:none\" title=\"Item {0} Description\">", i);
                                html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", (string.IsNullOrEmpty(item2.FilmNameEnglish) ? item2.FilmName : item2.FilmNameEnglish), url2, item2.FilmName);
                                html.Append("<div class=\"film-info\">");
                                html.AppendFormat("<span>Số tập: </span><label>{0}</label></br>", item2.EpisodeCount);
                                html.AppendFormat("<span>Thể loại phim: </span><label>{0}</label></br>", item2.FilmTypeNames);
                                html.AppendFormat("<span>Quốc gia: </span><label>{0}</label></br>", item2.CountryName);
                                html.AppendFormat("<span>Thời lượng: </span><label>{0}</label></br>", item2.Time);
                                html.AppendFormat("<span>Dung lượng: </span><label>{0}</label>", item2.Capacity);
                                html.Append("</div>");
                                html.Append("<div class=\"film-body\">");
                                html.AppendFormat("<p>{0}</p>", item2.Summary);
                                html.Append("</div>");
                                html.Append("</div>");

                                html.Append("</div>");
                                html.Append("</li>");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                            if (count > 0)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango member-item\">");
                                html.Append("<li>");
                                for (int i = 0; i < count; i++)
                                {
                                    var item = listTVShows[i];
                                    var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id });
                                    if (total > 0)
                                    {
                                        item = listTVShows[total + i];
                                    }

                                    html.Append("<div class=\"slide_child_div_dt2col item\">");
                                    html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url, item.FilmName);
                                    html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\">", item.ImageIcon, item.FilmNameEnglish, item.FilmName);
                                    html.Append("<p class=\"title_film_child\">");
                                    html.AppendFormat("<span class=\"orange_color\">{0}</span>", item.FilmNameEnglish);
                                    html.AppendFormat("<span>{0}</span>", item.FilmName);
                                    html.Append("</p>");
                                    html.AppendFormat("<span class=\"mask-num-film\">Tập <p>{0}</p></span>", item.EpisodeCount);
                                    html.Append("</a>");

                                    html.AppendFormat("<div class=\"tooltip_description\" style=\"display:none\" title=\"Item {0} Description\">", listTVShows.Count - 1);
                                    html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", (string.IsNullOrEmpty(item.FilmNameEnglish) ? item.FilmName : item.FilmNameEnglish), url, item.FilmName);
                                    html.Append("<div class=\"film-info\">");
                                    html.AppendFormat("<span>Số tập: </span><label>{0}</label></br>", item.EpisodeCount);
                                    html.AppendFormat("<span>Thể loại phim: </span><label>{0}</label></br>", item.FilmTypeNames);
                                    html.AppendFormat("<span>Quốc gia: </span><label>{0}</label></br>", item.CountryName);
                                    html.AppendFormat("<span>Thời lượng: </span><label>{0}</label></br>", item.Time);
                                    html.AppendFormat("<span>Dung lượng: </span><label>{0}</label>", item.Capacity);
                                    html.Append("</div>");
                                    html.Append("<div class=\"film-body\">");
                                    html.AppendFormat("<p>{0}</p>", item.Summary);
                                    html.Append("</div>");
                                    html.Append("</div>");
                                    html.Append("</div>");
                                }

                                html.Append("</li> ");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                        }

                        return html.ToString();
                    }
                #endregion

                #region Clips
                case HomeDisplayFilmType.Clip:
                    {
                        serviceFilms.CategoryId = 5;
                        var listClips = serviceFilms.BuildClips();
                        var html = new StringBuilder();
                        if (listClips != null && listClips.Count > 0)
                        {
                            var count = listClips.Count % 8;
                            var total = listClips.Count - count;
                            for (int i = 7; i < total; i += 8)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango member-item\">");
                                html.Append("<li>");

                                var index = i - 7;
                                html.Append(BuildItemClip(listClips[index], index));

                                index = i - 6;
                                html.Append(BuildItemClip(listClips[index], index));

                                index = i - 5;
                                html.Append(BuildItemClip(listClips[index], index));

                                index = i - 4;
                                html.Append(BuildItemClip(listClips[index], index));

                                index = i - 3;
                                html.Append(BuildItemClip(listClips[index], index));

                                index = i - 2;
                                html.Append(BuildItemClip(listClips[index], index));

                                index = i - 1;
                                html.Append(BuildItemClip(listClips[index], index));

                                index = i;
                                html.Append(BuildItemClip(listClips[index], index));

                                html.Append("</li> ");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                            if (count > 0)
                            {
                                html.Append("<div>");
                                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango member-item\">");
                                html.Append("<li>");
                                for (int i = 0; i < count; i++)
                                {
                                    var index = i;
                                    if (total > 0)
                                    {
                                        index = total + i;
                                    }
                                    html.Append(BuildItemClip(listClips[index], index));
                                }

                                html.Append("</li> ");
                                html.Append("</ul>");
                                html.Append("</div>");
                            }
                        }

                        return html.ToString();
                    }
                #endregion

                #region Statistical FilmRetail
                case HomeDisplayFilmType.StatisticalFilmRetail:
                    {
                        var listStatisticalFilmRetail = serviceFilms.BuildStatistical1(30, statistical);
                        var html = new StringBuilder();
                        if (listStatisticalFilmRetail != null && listStatisticalFilmRetail.Count > 0)
                        {
                            foreach (var item in listStatisticalFilmRetail)
                            {
                                html.Append(BuildItemStatistical(item));
                            }
                        }

                        return html.ToString();
                    }
                #endregion

                #region Statistical FilmLengthEpisodes
                case HomeDisplayFilmType.StatisticalLengthEpisodes:
                    {
                        var listStatisticalFilmRetail = serviceFilms.BuildStatistical2(30, statistical);
                        var html = new StringBuilder();
                        if (listStatisticalFilmRetail != null && listStatisticalFilmRetail.Count > 0)
                        {
                            foreach (var item in listStatisticalFilmRetail)
                            {
                                html.Append(BuildItemStatistical(item));
                            }
                        }

                        return html.ToString();
                    }
                #endregion

                #region Statistical Shows
                case HomeDisplayFilmType.StatisticalShows:
                    {
                        var listStatisticalShows = serviceFilms.BuildStatistical3(30, statistical);
                        var html = new StringBuilder();
                        if (listStatisticalShows != null && listStatisticalShows.Count > 0)
                        {
                            foreach (var item in listStatisticalShows)
                            {
                                html.Append(BuildItemStatistical(item));
                            }
                        }

                        return html.ToString();
                    }
                #endregion

                #region Statistical Clips
                case HomeDisplayFilmType.StatisticalClips:
                    {
                        var listStatisticalClips = serviceFilms.BuildStatistical4(30, statistical);
                        var html = new StringBuilder();
                        if (listStatisticalClips != null && listStatisticalClips.Count > 0)
                        {
                            foreach (var item in listStatisticalClips)
                            {
                                html.Append(BuildClip(item));
                            }
                        }

                        return html.ToString();
                    }
                #endregion

                #region Statistical Trailer
                case HomeDisplayFilmType.StatisticalTrailer:
                    {
                        var listStatisticalTrailer = serviceFilms.BuildStatistical5(30, statistical);
                        var html = new StringBuilder();
                        if (listStatisticalTrailer != null && listStatisticalTrailer.Count > 0)
                        {
                            foreach (var item in listStatisticalTrailer)
                            {
                                html.Append(BuildTrailer(item));
                            }
                        }

                        return html.ToString();
                    }
                #endregion

                #region Statistical Trailer
                case HomeDisplayFilmType.StatisticalNextFilm:
                    {
                        var listStatisticalTrailer = serviceFilms.BuildStatistical5(30, statistical);
                        var html = new StringBuilder();
                        if (listStatisticalTrailer != null && listStatisticalTrailer.Count > 0)
                        {
                            foreach (var item in listStatisticalTrailer)
                            {
                                html.Append(BuildTrailer(item));
                            }
                        }

                        return html.ToString();
                    }
                #endregion
            }

            return string.Empty;
        }

        [HttpPost, ValidateInput(false)]
        [Url("list-films-next")]
        public virtual ActionResult GetNextFilm(long filmId, string categoryIds, bool isShow, bool isClip, bool isTrailer,bool isFilm)
        {
            var service = WorkContext.Resolve<ISearchService>();
            service.SiteId = (int)Site.Home;
            var condition = new List<SearchCondition>
            {
                new SearchCondition(new[]
                {
                    SearchField.Title.ToString(),
                    SearchField.CategoryIds.ToString()
                }, categoryIds)
            };

            if (isShow)
            {
                condition.Add(new SearchCondition(new[]
                {
                    SearchField.IsShow.ToString()
                }, isShow.ToString())); 
            }

            if (isClip)
            {
                condition.Add(new SearchCondition(new[]
                {
                    SearchField.IsClip.ToString()
                }, isClip.ToString()));
            }

            if (isTrailer)
            {
                condition.Add(new SearchCondition(new[]
                {
                    SearchField.IsTrailer.ToString()
                }, isTrailer.ToString()));
            }

            if (isFilm)
            {
                condition.Add(new SearchCondition(new[]
                {
                    SearchField.IsFilm.ToString()
                }, isFilm.ToString()));
            }

            var total = 0;
            var data = service.Search(condition, 1, 40, ref total);
            var html = new StringBuilder();
            if (data != null && data.Count > 0)
            {
                foreach (var item in data)
                {
                    if (item.SearchId == filmId.ToString())
                    {
                        continue;
                    }

                    html.Append(BuildFilmSearch(item));
                }
            }

            var result = new DataViewerModel
            {
                Status = true,
                Data = html.ToString()
            };

            return Json(result);
        }

        public StringBuilder BuildItemStatistical(FilmInfo item)
        {
            var html = new StringBuilder();
            var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id });
            html.Append("<div class=\"list_category-child\">");
            html.Append("<div class=\"list_category-img\">");
            html.AppendFormat("<a title=\"{0}\" href=\"{1}\">", item.FilmName, url);
            html.AppendFormat("<img alt=\"{0}\" width=\"106\" height=\"80\" src=\"{1}\">",item.FilmAlias, item.ImageIcon);
            html.Append("</a>");
            html.Append("</div>");
            html.Append("<div class=\"list_category-txt\">");
            html.Append("<p class=\"name-en\">");
            html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", item.FilmNameEnglish, url, item.FilmNameEnglish);
            html.Append("</p>");
            html.Append("<p class=\"name-vi\">");    
            html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", item.FilmName, url, item.FilmName);    
            html.Append("</p>");
            html.AppendFormat("<p>Lượt xem phim: {0}</p>", item.ViewCount);    
            html.Append("</div>");
            html.Append("<br class=\"clear_both\">");
            html.Append("</div>"); 
            return html;
        }

        public StringBuilder BuildItem(FilmInfo item, int index, bool showEpisodes)
        {
            var html = new StringBuilder();
            var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id });
            html.Append("<div class=\"slide_child_div_dt item\">");
            html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url, item.FilmName);
            html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\">", item.ImageIcon.Replace("'", string.Empty), item.FilmNameEnglish, item.FilmName);
            html.Append("<p class=\"title_film_child\">");
            html.AppendFormat("<span class=\"orange_color\">{0}</span>", item.FilmNameEnglish);
            html.AppendFormat("<span>{0}</span>", item.FilmName);
            html.Append("</p>");
            if (showEpisodes && item.IsFilmLengthEpisodes)
            {
                html.AppendFormat("<span class=\"mask-num-film\">Tập <p>{0}</p></span>", item.EpisodeCount);
            }
            html.Append("</a>");

            html.AppendFormat("<div class=\"tooltip_description\" style=\"display:none\" title=\"Item {0} Description\">", index);
            html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", (string.IsNullOrEmpty(item.FilmNameEnglish) ? item.FilmName : item.FilmNameEnglish), url, item.FilmName);
            html.Append("<div class=\"film-info\">");
            if (showEpisodes && item.IsFilmLengthEpisodes)
            {
                html.AppendFormat("<span>Số tập: </span><label>{0}</label></br>", item.EpisodeCount);
            }
            html.AppendFormat("<span>Thể loại phim: </span><label>{0}</label></br>", item.FilmTypeNames);
            html.AppendFormat("<span>Quốc gia: </span><label>{0}</label></br>", item.CountryName);
            html.AppendFormat("<span>Thời lượng: </span><label>{0}</label></br>", item.Time);
            html.AppendFormat("<span>Dung lượng: </span><label>{0}</label>", item.Capacity);
            html.Append("</div>");
            html.Append("<div class=\"film-body\">");
            html.AppendFormat("<p>{0}</p>", item.Summary.Replace("'", string.Empty));
            html.Append("</div>");
            html.Append("</div>");

            html.Append("</div>");
            return html;
        }

        private StringBuilder BuildItemClip(FilmInfo item, int index)
        {
            var html = new StringBuilder();
            var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id });

            html.Append("<div class=\"slide_childs item\">");
            html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url, item.FilmName);
            html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\">", item.ImageIcon, item.FilmNameEnglish, item.FilmName);
            html.Append("<p class=\"title_film_child\">");
            html.AppendFormat("<span class=\"orange_color\">{0}</span>", item.FilmNameEnglish);
            html.AppendFormat("<span>{0}</span>", item.FilmName);
            html.Append("</p>");
            html.Append("</a>");

            html.AppendFormat("<div class=\"tooltip_description\" style=\"display:none\" title=\"Item {0} Description\">", index);
            html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", (string.IsNullOrEmpty(item.FilmNameEnglish) ? item.FilmName : item.FilmNameEnglish), url, item.FilmName);
            html.Append("<div class=\"film-info\">");
            html.AppendFormat("<span>Thể loại phim: </span><label>{0}</label></br>", item.FilmTypeNames);
            html.AppendFormat("<span>Quốc gia: </span><label>{0}</label></br>", item.CountryName);
            html.AppendFormat("<span>Thời lượng: </span><label>{0}</label></br>", item.Time);
            html.AppendFormat("<span>Dung lượng: </span><label>{0}</label>", item.Capacity);
            html.Append("</div>");
            html.Append("<div class=\"film-body\">");
            html.AppendFormat("<p>{0}</p>", item.Summary);
            html.Append("</div>");
            html.Append("</div>");

            html.Append("</div>");
            return html;
        }

        private StringBuilder BuildClip(FilmInfo item)
        {
            var html = new StringBuilder();
            var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id });

            html.Append("<div class=\"list_category-child\">");
            html.Append("<div class=\"list_category-img\">");
            html.AppendFormat("<a href=\"{0}\">", url);
            html.AppendFormat("<img alt=\"{0}\" width=\"106\" height=\"80\" src=\"{1}\">", item.FilmName, item.ImageIcon);
            html.Append("</a>");
            html.Append("</div>");
            html.Append("<div class=\"list_category-txt\">");
            html.AppendFormat("<p class=\"name-en\"><a href=\"{0}\">{1}</a></p>", url, item.FilmNameEnglish);
            html.AppendFormat("<p class=\"name-vi\"><a href=\"{0}\">{1}</a></p>", url, item.FilmName);
            html.AppendFormat("<p>Tổng lượt xem: {0}</p>", item.ViewCount);
            html.Append("</div>");
            html.Append("<br class=\"clear_both\">");
            html.Append("</div>");

            return html;
        }

        private StringBuilder BuildTrailer(FilmInfo item)
        {
            var html = new StringBuilder();
            var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id });

            html.Append("<div class=\"list_category-child\">");
            html.Append("<div class=\"list_category-img\">");
            html.AppendFormat("<a href=\"{0}\">", url);
            html.AppendFormat("<img alt=\"{0}\" width=\"106\" height=\"80\" src=\"{1}\">", item.FilmName, item.ImageIcon);
            html.Append("</a>");
            html.Append("</div>");
            html.Append("<div class=\"list_category-txt\">");
            html.AppendFormat("<p class=\"name-en\"><a href=\"{0}\">{1}</a></p>", url, item.FilmNameEnglish);
            html.AppendFormat("<p class=\"name-vi\"><a href=\"{0}\">{1}</a></p>", url, item.FilmName);
            html.Append("</div>");
            html.Append("<br class=\"clear_both\">");
            html.Append("</div>");

            return html;
        }

        private StringBuilder BuildFilmSearch(SearchInfo item)
        {
            var html = new StringBuilder();
            var url = Url.Action("FilmView", "HomeView", new { @alias = item.Alias, @id = item.SearchId });

            html.Append("<div class=\"list_category-child\">");
            html.Append("<div class=\"list_category-img\">");
            html.AppendFormat("<a href=\"{0}\">", url);
            html.AppendFormat("<img alt=\"{0}\" width=\"106\" height=\"80\" src=\"{1}\">", item.Title, item.Images);
            html.Append("</a>");
            html.Append("</div>");
            html.Append("<div class=\"list_category-txt\">");
            html.AppendFormat("<p class=\"name-en\"><a href=\"{0}\">{1}</a></p>", url, item.TitleEnglish);
            html.AppendFormat("<p class=\"name-vi\"><a href=\"{0}\">{1}</a></p>", url, item.Title);
            html.AppendFormat("<p>Lượt xem: {0}</p>", item.ViewCount);
            html.Append("</div>");
            html.Append("<br class=\"clear_both\">");
            html.Append("</div>");

            return html;
        }
        #endregion

        public virtual void BuildModules()
        {

        }

        #region Sliders
        public virtual string BuildSlider(int siteId, int pageId)
        {
            var service = WorkContext.Resolve<ISliderService>();
            var seviceFilm = WorkContext.Resolve<IFilmService>();
            seviceFilm.LanguageCode = WorkContext.CurrentCulture;
            seviceFilm.SiteId = siteId;
            service.LanguageCode = WorkContext.CurrentCulture;
            service.SiteId = siteId;
            var list = service.GetCacheByPageId(pageId);

            var html = new StringBuilder();
            if (list != null && list.Count > 0)
            {
                html.Append("<div class=\"slider-home\" id=\"slider1_container\">");
                html.Append("<div class=\"slider-border\" u=\"slides\">");
                foreach (var slider in list)
                {
                    var film = seviceFilm.GetFilmDetails(slider.FilmId);
                    if (film != null)
                    {
                        var url = Url.Action("FilmView", "HomeView", new { @alias = film.FilmAlias, @id = film.Id });

                        html.Append("<div onmouseout=\"javascript: event_mouseout();\" onmouseover=\"javascript: event_mouseover();\">");
                        html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\" u=\"image\" />", film.ImageThumb, film.FilmAlias, film.FilmNameEnglish);
                        html.Append("<div class=\"caption\">");
                        html.Append("<h3>");
                        html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{0}</a>", film.FilmNameEnglish, url);
                        html.Append("</h3>");
                        html.AppendFormat("<h4>{0}</h4>", film.FilmName);
                        html.Append("<p class=\"description_detail_p\">");
                        html.Append(film.Summary);
                        html.AppendFormat("<a href=\"{0}\" style=\"color:#e74c3c\">Xem thêm</a>", url);
                        html.Append("</p>");
                        html.Append("<ul class=\"description_detail_ul\">");
                        html.AppendFormat("<li><span>Quốc gia</span> {0}</li>", film.CountryName);
                        html.AppendFormat("<li><span>Thể loại</span> {0}</li>", film.FilmTypeNames);
                        html.AppendFormat("<li><span>Diễn viên</span> {0}</li>", film.ActorNames);
                        html.AppendFormat("<li><span>Thời lượng</span> {0}</li>", film.Time);
                        html.Append("</ul>");
                        html.AppendFormat("<a href=\"{0}\" class=\"see_a-link\">Xem phim</a>", url);
                        html.Append("</div>");
                        html.Append("</div>");
                    }
                }

                html.Append("</div>");
                html.Append("<div style=\"bottom: 16px; right: 6px;\" class=\"jssorb03\" u=\"navigator\">");
                html.Append("<div u=\"prototype\">");
                html.Append("<div u=\"numbertemplate\">&nbsp;</div>");
                html.Append("</div>");
                html.Append("</div>");
                html.Append("<span style=\"top: 123px; left: 8px;\" class=\"jssora20l\" onmouseout=\"javascript: event_mouseout();\" onmouseover=\"javascript: event_mouseover();\" u=\"arrowleft\"></span>");
                html.Append("<span style=\"top: 123px; right: 8px;\" class=\"jssora20r\" onmouseout=\"javascript: event_mouseout();\" onmouseover=\"javascript: event_mouseover();\" u=\"arrowright\"></span>");
                html.Append("</div>");
            }
             
            return html.ToString();
        }
        #endregion

        [HttpPost, ValidateInput(false)]
        [Url("get-film-details")]
        public ActionResult FilmDetails()
        {
            var model = new DataViewCategoryModel { HtmlData = string.Empty };
            if (!string.IsNullOrEmpty(Request.Form["txtFilmId"]))
            {
                var id = long.Parse(Request.Form["txtFilmId"]);
                var service = WorkContext.Resolve<IFilmService>();
                service.LanguageCode = WorkContext.CurrentCulture;
                service.SiteId = (int) Site.Home;
                var obj = service.GetFilmDetails(id);
                var html = new StringBuilder();
                if (obj != null)
                {
                    var url = Url.Action("FilmView", "HomeView", new {@alias = obj.FilmAlias, @id = obj.Id});
                    html.Append("<p class=\"name-en\">");
                    html.AppendFormat("<a href=\"{0}\" title=\"{1}\">{1}</a>", url, obj.FilmNameEnglish);
                    html.Append("</p>");

                    html.Append("<p class=\"name-vi\">");
                    html.AppendFormat("<a href=\"{0}\" title=\"{1}\">{1}</a>", url, obj.FilmName);
                    html.Append("</p>");
                    html.AppendFormat("<p>{0}</p>", obj.Summary);

                    html.Append("<ul>");
                    html.AppendFormat("<li><span>Năm phát hành:</span> {0}</li>", obj.ReleaseYear);
                    html.AppendFormat("<li><span>Đạo diễn:</span> {0}</li>", obj.DirectorName);
                    html.AppendFormat("<li><span>Diễn viên:</span> {0}</li>", obj.ActorNames);
                    html.AppendFormat("<li><span>Quốc gia:</span> {0}</li>", obj.CountryName);
                    html.AppendFormat("<li><span>Thể loại:</span> {0}</li>", obj.CategoryNames);
                    html.AppendFormat("<li><span>IMDB:</span> {0}</li>", obj.Capacity);
                    html.AppendFormat("<li><span>Liên quan (tag):</span> {0}</li>", obj.Tags);
                    html.Append("</ul>");

                    html.AppendFormat("<a href=\"{0}\" class=\"see_a-link\">Xem phim<span></span></a>", url);
                    html.Append("<br class=\"clear_both\">");
                }

                model.HtmlData = html.ToString();
            }
            
            return Json(model);
        }

        [HttpPost, ValidateInput(false)]
        [Url("get-data/tim-kiem")]
        public ActionResult Search()
        {
            var keyword = Request.Form["keyword"];
            var service = WorkContext.Resolve<ISearchService>();
            service.SiteId = (int)Site.Home;
            var condition = new List<SearchCondition>
            {
                new SearchCondition(new[]
                {
                    SearchField.Title.ToString(), 
                    SearchField.Keyword.ToString(), 
                    SearchField.KeywordEN.ToString()
                }, keyword)
            };

            var total = 0;
            var data = service.Search(condition, 1, 40, ref total);
            return Json(data);
        }

        #region Rates
        [HttpPost, ValidateInput(false)]
        [Url("danh-gia-bao-loi-phim")]
        public ActionResult RateFilm(int type, long filmId, int rate, int title, string messsages)
        {
            var result = new DataViewerModel();
            if (!IsLogin)
            {
                result = new DataViewerModel
                {
                    Status = false,
                    Data = "Bạn chưa đăng nhập."
                };

                return Json(result);
            }

            var service = WorkContext.Resolve<IRateService>();
            var entity = service.GetByFilmCustomer(filmId, CustomerCode) ?? new RateInfo();
            switch (type)
            {
                case 1: // Đánh giá
                    entity.Rate += rate;
                    entity.Messages = GetRateMessages(rate) + ", ";
                    result.Status = true;
                    result.Data = "Cảm ơn bạn đã đánh giá viphd chúc các bạn xem phim vui vẻ.";
                    var filmService = WorkContext.Resolve<IFilmService>();
                    filmService.UpdateCommentCount(filmId);
                    break;
                case 2: //Báo giật lag
                    entity.AlertLag = messsages + ", ";
                    entity.Messages = "Phim này đang bị khách hàng thông báo giật lag.";
                    result.Status = true;
                    result.Data = "Thông báo lỗi của bạn đã được gửi đi. Chúng tôi đang kiểm tra lại. Cảm ơn bạn đã ủng hộ và hỗ trợ viphd nhé.";
                    break;
                case 3: //Báo lỗi
                    entity.AlertError = EnumExtensions.GetDisplayName((AlertErrorVideo) title);
                    entity.Messages += messsages + ", ";
                    result.Status = true;
                    result.Data = "Thông báo lỗi của bạn đã được gửi đi. Chúng tôi đang kiểm tra lại . Cảm ơn bạn đã ủng hộ và hỗ trợ viphd nhé.";
                    break;
                case 4: //Thích phim
                    entity.LikeFilm = true;
                    entity.Messages = messsages + ", ";
                    result.Status = false;
                    result.Data = "";
                    break;
            }

            entity.Status = 1;
            entity.LanguageCode = WorkContext.CurrentCulture;
            entity.SiteId = (int)Site.Home;
            entity.CustomerId = UserId;
            entity.CustomerCode = CustomerCode;
            entity.FilmId = filmId;

            service.Save(entity);
            return Json(result);
        }

        private string GetRateMessages(int rate) {
            var text = string.Empty;
            if (rate == 1) {
                text = "Hay Chết Liền";
            }

            if (rate == 2) {
                text = "Hay chỗ nào";
            }

            if (rate == 3) {
                text = "Ai Bảo Hay";
            }

            if (rate == 4) {
                text = "Xém nữa thì Hay";
            }

            if (rate == 5) {
                text = "Có vẻ Hay";
            }

            if (rate == 6) {
                text = "Ờ Cũng Hay";
            }

            if (rate == 7) {
                text = "Hơi bị Hay";
            }

            if (rate == 8) {
                text = "Quá Là Hay";
            }

            if (rate == 9) {
                text = "Hay Quá Xá";
            }

            if (rate == 10) {
                text = "Tuyệt đỉnh Hay";
            }

            return text;
        }

        [HttpPost, ValidateInput(false)]
        [Url("download-games")]
        public virtual ActionResult CheckDownload(int id)
        {
            var result = new DataViewerModel();
            result.Status = true;
            result.Data = "Bạn chưa đăng nhập.";
            if (IsLogin)
            {
                result.Data = "Nhiệm vụ đang chờ bạn thực hiện.";
                var service = WorkContext.Resolve<IDownloadGameService>();
                var obj = service.GetById(id);
                if (obj != null)
                {
                    var customerService = WorkContext.Resolve<ICustomerService>();
                    var status = customerService.AddVipXu(UserId, obj.Id, obj.VipXu);
                    if (status == 1)
                    {
                        result.Data = "Bạn cần tải về, cài đặt và mở ứng dụng để nhận được " + obj.VipXu + " VIPXU.";
                    }
                    else
                    {
                        var downloadService = WorkContext.Resolve<IDownloadCustomerService>();
                        var item = downloadService.GetItem(UserId, id);
                        if (item != null)
                        {
                            var displayDay = Utilities.GetStatusDownload(item);
                            result.Data = "Bạn cần tải về, cài đặt và mở ứng dụng để nhận được " + obj.VipXu + " VIPXU (sau " + displayDay + ")";
                        }
                    }
                }
            }

            return Json(result);
        }
        #endregion
    }
}
<file_sep>﻿using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IPromotionCustomersService : IGenericService<PromotionCustomerInfo, long>, IDependency
    {
        IList<PromotionCustomerInfo> GetByPromotion(int promotionId);

        PromotionCustomerInfo GetCode(int promotionId, int customerId);

        PromotionCustomerInfo GetCodeCustomer(int customerId, string code);

        int ActiveCode(int customerId, string code);
    }

    public class PromotionCustomersService : GenericService<PromotionCustomerInfo, long>, IPromotionCustomersService
    {
        public PromotionCustomersService(IRepository<PromotionCustomerInfo, long> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public IList<PromotionCustomerInfo> GetByPromotion(int promotionId)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@PromotionId", promotionId)
            };

            return ExecuteReader<PromotionCustomerInfo>("sp_PromotionCustomers_GetByPromotionId", list.ToArray());
        }

        public PromotionCustomerInfo GetCode(int promotionId, int customerId)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@PromotionId", promotionId),
                AddInputParameter("@CustomerId", customerId)
            };

            return ExecuteReaderRecord<PromotionCustomerInfo>("sp_PromotionCustomers_GetCode", list.ToArray());
        }

        public PromotionCustomerInfo GetCodeCustomer(int customerId, string code)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@CustomerId", customerId),
                AddInputParameter("@Code", code)
            };

            return ExecuteReaderRecord<PromotionCustomerInfo>("sp_PromotionCustomers_GetCodeCustomer", list.ToArray());
        }

        public int ActiveCode(int customerId, string code)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@CustomerId", customerId),
                AddInputParameter("@Code", code)
            };

            return (int)ExecuteReaderResult("sp_TransactionCode_Active", list.ToArray());
        }
    }
}<file_sep>﻿using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IPromotionService : IGenericService<PromotionInfo, int>, IDependency
    {
        IList<PromotionInfo> SearchPaged(
            int status,
            int pageIndex,
            int pageSize,
            out int totalRecord);
    }

    public class PromotionService : GenericService<PromotionInfo, int>, IPromotionService
    {
        public PromotionService(IRepository<PromotionInfo, int> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public IList<PromotionInfo> SearchPaged(int status, int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Status", status),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<PromotionInfo>("sp_Promotions_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }
    }
}<file_sep>﻿using System.ComponentModel;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class SmsMessageInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }

        [DataMember]
        [DisplayName("Code")]
        public string Code { get; set; }

        [DataMember]
        [DisplayName("Message")]
        public string Message { get; set; }

        [DataMember]
        [DisplayName("IsEvent")]
        public bool IsEvent { get; set; }
    }

    public class SmsMessageMap : EntityTypeConfiguration<SmsMessageInfo>, IEntityTypeConfiguration
    {
        public SmsMessageMap()
        {
            ToTable("Modules_SmsMessages");
            HasKey(x => x.Id);
            Property(m => m.LanguageCode).IsRequired().HasMaxLength(50);
            Property(x => x.Code).HasMaxLength(50).IsRequired();
            Property(x => x.Message).IsRequired().HasMaxLength(250);
        }
    }
}<file_sep>﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class TransactionCardInfo : BaseEntity<long>
    {
        [DataMember]
        [DisplayName("CustomerCode")]
        public string CustomerCode { get; set; }

        [DataMember]
        [DisplayName("TransactionCode")]
        public string TransactionCode { get; set; }

        [DataMember]
        [DisplayName("CreateDate")]
        public DateTime CreateDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextStartDate
        {
            get
            {
                return CreateDate.ToString(Extensions.Constants.DateTimeFomatFull);
            }
        }

        [DataMember]
        [DisplayName("CardCode")]
        public string CardCode { get; set; }

        [NotMapped]
        [DisplayName("CardName")]
        public string CardName { get; set; }

        [DataMember]
        [DisplayName("SeriNumber")]
        public string SeriNumber { get; set; }

        [DataMember]
        [DisplayName("PinCode")]
        public string PinCode { get; set; }

        [DataMember]
        [DisplayName("Amount")]
        public string Amount { get; set; }

        [DataMember]
        [DisplayName("Description")]
        public string Description { get; set; }

        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }

        [DataMember]
        [DisplayName("IsLock")]
        public bool IsLock { get; set; }

        [NotMapped]
        [DisplayName("FullName")]
        public string FullName { get; set; }
    }

    public class TransactionCardMap : EntityTypeConfiguration<TransactionCardInfo>, IEntityTypeConfiguration
    {
        public TransactionCardMap()
        {
            ToTable("Modules_TransactionCard");
            HasKey(m => m.Id);
            Property(m => m.CustomerCode).IsRequired().HasMaxLength(50);
            Property(m => m.TransactionCode).IsRequired().HasMaxLength(50);
            Property(m => m.SeriNumber).HasMaxLength(250);
            Property(m => m.PinCode).IsRequired().HasMaxLength(250);
            Property(m => m.Description).HasMaxLength(2000);
            Property(m => m.Amount).HasMaxLength(250);
        }
    }
}<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class FilmVideoModel
    {
        public FilmVideoModel()
        {
            IsActived = true;
        }

        [ControlHidden]
        public long Id { get; set; }
        
        [ControlHidden]
        public string ReturnUrl { get; set; }

        [ControlHidden]
        public long FilmId { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.ServerId + "').empty();")]
        public string LanguageCode { get; set; }

        [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public int SiteId { get; set; }

        [ControlCascadingDropDown(LabelText = "Máy chủ", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public int ServerId { get; set; }

        [ControlCascadingDropDown(LabelText = "Thư mục gốc", ParentControl = "ServerId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public string RootFolders { get; set; }

        [ControlCascadingDropDown(LabelText = "Thư mục ngày", ParentControl = "RootFolders", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public string FolderDay { get; set; }

        [ControlCascadingDropDown(LabelText = "Thư mục theo ngày", ParentControl = "FolderDay", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public string ChildrenFolders { get; set; }

        [ControlCascadingDropDown( AllowMultiple = true, LabelText = "Đường dẫn files", ParentControl = "ChildrenFolders", CssClass = Extensions.Constants.CssControlCustom, EnableChosen = true, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 2)]
        public long[] FileIds { get; set; }

        [ControlText(Type = ControlText.MultiText, Rows = 2, LabelText = "Đường dẫn nguồn album", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 3)]
        public string UrlAlbum { get; set; }

        [ControlText(Type = ControlText.MultiText, Rows = 2, LabelText = "Đường dẫn nguồn video", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 3)]
        public string UrlSource { get; set; }

        [ControlText(Type = ControlText.MultiText, Rows = 2, Required = true, LabelText = "Đường dẫn files subtitle", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)]
        public string Subtitle { get; set; }

        [ControlChoice(ControlChoice.DropDownList, AllowMultiple = true, CssClass = Extensions.Constants.CssControlCustom, EnableChosen = true, Required = true, LabelText = "Chọn tập phim", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 4)]
        public int[] EpisodeIds { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Trailer phim", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)]
        public bool IsTraller { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Sử dụng", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)]
        public bool IsActived { get; set; }

        //[ControlFileUpload(EnableFineUploader = true, LabelText = "Ảnh đại diện", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 4, ShowThumbnail = true)]
        //public string ImageIcon { get; set; }

        public static implicit operator FilmVideoModel(FilmVideoInfo entity)
        {
            return new FilmVideoModel
            {
                Id = entity.Id,
                FilmId = entity.FilmId,
                FileIds = new[] { entity.FileId },
                IsTraller = entity.IsTraller,
                IsActived = entity.IsActived,
                Subtitle = entity.Subtitle,
                UrlSource = entity.UrlSource,
                EpisodeIds = new[]{entity.EpisodeId},
                UrlAlbum = entity.UrlAlbum
            };
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using CMSSolutions.Extensions;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminFilmController : BaseAdminController
    {
        public AdminFilmController(IWorkContextAccessor workContextAccessor) : 
                base(workContextAccessor)
        {
            TableName = "tblFilms";
        }

        private int pageSize = 50;

        [Url("admin/films")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý phim"), Url = "#" });
            var result = new ControlGridFormResult<FilmInfo>
            {
                Title = T("Quản lý phim"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetFilms,
                UpdateActionName = "Update",
                ActionsColumnWidth = 150,
                ClientId = TableName,
                EnablePaginate = true,
                DefaultPageSize = pageSize,
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml
            };

            result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.UserId, "$('#" + Extensions.Constants.UserId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.CategoryId, "$('#" + Extensions.Constants.CategoryId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.DirectorId, "$('#" + Extensions.Constants.DirectorId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.ActorId, "$('#" + Extensions.Constants.ActorId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.FilmGroup, "$('#" + Extensions.Constants.FilmGroup + "').val();", true);
            result.AddCustomVar(Extensions.Constants.FilmTypesId, "$('#" + Extensions.Constants.FilmTypesId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.FromDate, "$('#" + Extensions.Constants.FromDate + "').val();", true);
            result.AddCustomVar(Extensions.Constants.ToDate, "$('#" + Extensions.Constants.ToDate + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true);

            result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(40);
            result.AddColumn(x => x.ImageIcon, T("Ảnh đại diện"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsImage(y => y.ImageIcon, Extensions.Constants.CssThumbsSize);

            result.AddColumn(x => x.FilmName, T("Tên phim"));
            result.AddColumn(x => x.FilmNameEnglish, T("Tên tiếng anh"));
            result.AddColumn(x => x.CollectionName, T("Tên bộ phim"));
            result.AddColumn(x => x.FilmTypeNames, T("Thể loại phim"));
            result.AddColumn(x => x.DisplayDate, T("Ngày tạo"));
            result.AddColumn(x => x.FullName, T("Người đăng"));
            result.AddColumn(x => x.IsPublished)
                .HasHeaderText(T("Đã đăng"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage();
            result.AddColumn(x => x.IsHot)
                .HasHeaderText(T("Phim mới"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage();
            result.AddColumn(x => x.HasCopyright)
                .HasHeaderText(T("Có BQ"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage();

            result.AddAction().HasText(T("Thêm mới"))
                .HasUrl("javascript:  redirectUrl(0, '" + Url.Action("Edit", "AdminFilm") + "');")
                .HasButtonStyle(ButtonStyle.Primary)
                .HasBoxButton(false)
                .HasRow(false)
                .HasCssClass(Constants.RowLeft)
                .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildSites(true, Extensions.Constants.CategoryId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildCategories)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildUsers).HasParentClass(Constants.ContainerCssClassCol3));
            result.AddAction(new ControlFormHtmlAction(BuildDirectors)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildActors)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildFilmTypes)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildFilmGroups)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildFromDate())).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildToDate())).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildHtmlScript)).HasBoxButton(false);

            result.AddRowAction()
                .HasText(T("Sửa"))
                .HasUrl(x => "javascript:  redirectUrl("+x.Id+", '" + Url.Action("Edit", "AdminFilm") + "');")
                .HasButtonStyle(ButtonStyle.Default)
                .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddRowAction()
                .HasText(T("Videos"))
                .HasUrl(x => "javascript:  redirectUrl(" + x.Id + ", '" + Url.Action("Index", "AdminFilmVideos") + "');")
                .HasButtonStyle(ButtonStyle.Info)
                .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddRowAction(true)
                .HasText(T("Xóa"))
                .HasName("Delete")
                .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString()))
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");
            return result;
        }

        private string BuildHtmlScript()
        {
            var sb = new StringBuilder();

            sb.Append("<script type=\"text/javascript\">");
            sb.Append("function redirectUrl(id, url) {");
            sb.Append("var languageCode = $(\"#" + Extensions.Constants.LanguageCode + "\").val();");
            sb.Append("var siteId = $(\"#" + Extensions.Constants.SiteId + "\").val();");
            sb.Append("var categoryId = $(\"#" + Extensions.Constants.CategoryId + "\").val();");
            sb.Append("var userId = $(\"#" + Extensions.Constants.UserId + "\").val();");
            sb.Append("var fromDate = $(\"#" + Extensions.Constants.FromDate + "\").val();");
            sb.Append("var toDate = $(\"#" + Extensions.Constants.ToDate + "\").val();");
            sb.Append("var searchText =  $(\"#" + Extensions.Constants.SearchText + "\").val();");
            sb.Append("var statusId = $(\"#" + Extensions.Constants.StatusId + "\").val();");
            sb.Append("var directorId = $(\"#" + Extensions.Constants.DirectorId + "\").val();");
            sb.Append("var actorId = $(\"#" + Extensions.Constants.ActorId + "\").val();");
            sb.Append("var filmGroup = $(\"#" + Extensions.Constants.FilmGroup + "\").val();");
            sb.Append("var filmTypesId = $(\"#" + Extensions.Constants.FilmTypesId + "\").val();");
            sb.AppendFormat("var returnUrl = languageCode + '{0}' + siteId + '{0}' + categoryId + '{0}' + userId + '{0}'", ",");
            sb.AppendFormat("+ directorId + '{0}' + actorId + '{0}' + filmTypesId + '{0}' + filmGroup + '{0}' + statusId + '{0}'", ",");
            sb.AppendFormat("+ fromDate + '{0}' + toDate + '{0}' + encode_utf8(searchText);", ",");
            sb.Append("var encodedString = btoa(returnUrl);");
            sb.AppendFormat("window.location = url + '{0}' + id + '{1}' + encodedString;", "?id=", "&" + Extensions.Constants.ReturnUrl + "=");
            sb.Append("}");
            sb.Append("</script>");

            return sb.ToString();
        }

        private string GetUrl()
        {
            var pageIndex = 1;
            if (Session[Extensions.Constants.PageIndex] != null)
            {
                pageIndex = int.Parse(Session[Extensions.Constants.PageIndex].ToString());
            }

            Session[Extensions.Constants.BackPageIndex] = "BACKPAGE";
            var returnUrl = Request.QueryString[Extensions.Constants.ReturnUrl];
            var url = Url.Action("Index", "AdminFilm");
            var sb = new StringBuilder();
            sb.Append("<script type=\"text/javascript\">");
            sb.Append("function backUrl() {");
            sb.AppendFormat("window.location = '{0}?{1}={2}&{3}={4}';", url, Extensions.Constants.ReturnUrl, returnUrl, Extensions.Constants.PageIndex, pageIndex);
            sb.Append("}");
            sb.Append("</script>");
            return sb.ToString();
        }

        private ControlGridAjaxData<FilmInfo> GetFilms(ControlGridFormRequest options)
        {
            if (Request.QueryString[Extensions.Constants.PageIndex] != null && Session[Extensions.Constants.BackPageIndex] != null)
            {
                options.PageIndex = int.Parse(Request.QueryString[Extensions.Constants.PageIndex]);
            }

            var languageCode = WorkContext.CurrentCulture;
            if (!string.IsNullOrEmpty(GetQueryString(0)) && Session[Extensions.Constants.BackPageIndex] != null)
            {
                languageCode = GetQueryString(0);
            }

            var siteId = 0;
            if (!string.IsNullOrEmpty(GetQueryString(1)) && Session[Extensions.Constants.BackPageIndex] != null)
            {
                siteId = int.Parse(GetQueryString(1));
            }

            var categoryId = 0;
            if (!string.IsNullOrEmpty(GetQueryString(2)) && Session[Extensions.Constants.BackPageIndex] != null)
            {
                categoryId = Convert.ToInt32(GetQueryString(2));
            }

            long userId = 0;
            if (!string.IsNullOrEmpty(GetQueryString(3)) && Session[Extensions.Constants.BackPageIndex] != null)
            {
                userId = long.Parse(GetQueryString(3));
            }

            var directorId = 0;
            if (!string.IsNullOrEmpty(GetQueryString(4)) && Session[Extensions.Constants.BackPageIndex] != null)
            {
                directorId = int.Parse(GetQueryString(4));
            }

            var actorId = 0;
            if (!string.IsNullOrEmpty(GetQueryString(5)) && Session[Extensions.Constants.BackPageIndex] != null)
            {
                actorId = int.Parse(GetQueryString(5));
            }

            var filmTypesId = 0;
            if (!string.IsNullOrEmpty(GetQueryString(6)) && Session[Extensions.Constants.BackPageIndex] != null)
            {
                filmTypesId = int.Parse(GetQueryString(6));
            }

            var filmGroup = 0;
            if (!string.IsNullOrEmpty(GetQueryString(7)) && Session[Extensions.Constants.BackPageIndex] != null)
            {
                filmGroup = int.Parse(GetQueryString(7));
            }

            var statusId = 0;
            if (!string.IsNullOrEmpty(GetQueryString(8)) && Session[Extensions.Constants.BackPageIndex] != null)
            {
                statusId = int.Parse(GetQueryString(8));
            }

            var fromDate = DateTime.Now.Date;
            if (!string.IsNullOrEmpty(GetQueryString(9)) && Session[Extensions.Constants.BackPageIndex] != null)
            {
                fromDate = DateTime.ParseExact(GetQueryString(9), Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture);
            }

            var toDate = DateTime.Now.Date;
            if (!string.IsNullOrEmpty(GetQueryString(10)) && Session[Extensions.Constants.BackPageIndex] != null)
            {
                toDate = DateTime.ParseExact(GetQueryString(10), Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture);
            }

            var searchText = string.Empty;
            if (!string.IsNullOrEmpty(GetQueryString(11)) && Session[Extensions.Constants.BackPageIndex] != null)
            {
                searchText = GetQueryString(11);
            }

            int countryId = 0;
            int collectionId = 0;
            int articlesId = 0;
            int serverId = 0;
            int releaseYear = 0;
            DateTime createDate = Utilities.DateNull();
            DateTime publishedDate = Utilities.DateNull();
            int isPublished = -1;
            int isHot = -1;
            int isHome = -1;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }
           
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.CategoryId]))
            {
                categoryId = Convert.ToInt32(Request.Form[Extensions.Constants.CategoryId]);
            }
           
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FromDate]))
            {
                fromDate = DateTime.ParseExact(Request.Form[Extensions.Constants.FromDate], "dd/MM/yyyy", CultureInfo.InvariantCulture);
            }
            
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ToDate]))
            {
                toDate = DateTime.ParseExact(Request.Form[Extensions.Constants.ToDate], "dd/MM/yyyy", CultureInfo.InvariantCulture);
            }
           
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText]))
            {
                searchText = Request.Form[Extensions.Constants.SearchText];
            }
            
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.UserId]))
            {
                userId = long.Parse(Request.Form[Extensions.Constants.UserId]);
            }
            
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId]))
            {
                statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]);
            }
            
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.DirectorId]))
            {
                directorId = Convert.ToInt32(Request.Form[Extensions.Constants.DirectorId]);
            }
            
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ActorId]))
            {
                actorId = Convert.ToInt32(Request.Form[Extensions.Constants.ActorId]);
            }
            
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FilmGroup]))
            {
                filmGroup = Convert.ToInt32(Request.Form[Extensions.Constants.FilmGroup]);
            }

            int isFilmRetail = -1;
            int isFilmLengthEpisodes = -1;
            if (filmGroup > 0)
            {
                switch ((FilmGroup)filmGroup)
                {
                    case FilmGroup.FilmRetail:
                        isFilmRetail = 1;
                        isFilmLengthEpisodes = 0;
                        break;
                    case FilmGroup.FilmLengthEpisodes:
                        isFilmRetail = 0;
                        isFilmLengthEpisodes = 1;
                        break;
                }
            }

            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FilmTypesId]))
            {
                filmTypesId = Convert.ToInt32(Request.Form[Extensions.Constants.FilmTypesId]);
            }

            int totals;
            var service = WorkContext.Resolve<IFilmService>();
            var records = service.SearchPaged(
                searchText, languageCode, siteId, categoryId,
                filmTypesId, countryId, directorId,
                actorId, collectionId, articlesId,
                userId, serverId, releaseYear, fromDate,
                toDate, createDate, publishedDate, isPublished,
                isHot, isHome, isFilmRetail, isFilmLengthEpisodes, 
                statusId, options.PageIndex, options.PageSize,
                out totals);

            Session[Extensions.Constants.PageIndex] = options.PageIndex;
            Session[Extensions.Constants.BackPageIndex] = null;

            return new ControlGridAjaxData<FilmInfo>(records, totals);
        }

        [Url("admin/films/edit")]
        public ActionResult Edit()
        {
            var id = int.Parse(Request.QueryString["id"]);            
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý phim"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin phim"), Url = "#" });

            var model = new FilmModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<IFilmService>();
                var obj = service.GetById(id);
                model = obj;
                if (obj.IsFilmRetail)
                {
                    model.FilmGroup = 1;
                }

                if (obj.IsFilmLengthEpisodes)
                {
                    model.FilmGroup = 2;
                }
            }

            var result = new ControlFormResult<FilmModel>(model)
            {
                Title = T("Thông tin phim"),
                UpdateActionName = "Update",
                FormMethod = FormMethod.Post,
                SubmitButtonText = T("Lưu lại"),
                ShowBoxHeader = false,
                ShowCancelButton = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml,
                SetJavascript = GetUrl()
            };

            result.RegisterFileUploadOptions("ImageIcon.FileName", new ControlFileUploadOptions
            {
                AllowedExtensions = "jpg,jpeg,png,gif"
            });

            result.RegisterFileUploadOptions("ImageThumb.FileName", new ControlFileUploadOptions
            {
                AllowedExtensions = "jpg,jpeg,png,gif"
            });

            if (id > 0)
            {
                result.AddAction().HasText(T("Chọn videos"))
                .HasUrl(Url.Action("Index", "AdminFilmVideos", new { @id = id }))
                .HasButtonStyle(ButtonStyle.Info);
            }

            result.AddAction().HasText(T("Làm mới"))
                .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
                .HasButtonStyle(ButtonStyle.Success);

            result.AddAction().HasText(T("Trở về"))
               .HasUrl("javascript: backUrl();")
               .HasButtonStyle(ButtonStyle.Danger);

            result.MakeReadOnlyProperty(x => x.StartDate);
            result.MakeReadOnlyProperty(x => x.EndDate);
            result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages());
            result.RegisterExternalDataSource(x => x.FilmTypeIds, y => BindFilmTypes());
            result.RegisterExternalDataSource(x => x.CountryId, y => BindCountries());
            result.RegisterExternalDataSource(x => x.DirectorId, y => BindDirectors());
            result.RegisterExternalDataSource(x => x.ActorIds, y => BindActors());
            result.RegisterExternalDataSource(x => x.ServerId, y => BindServers());
            result.RegisterExternalDataSource(x => x.FilmGroup, y => BindFilmGroups());
            result.RegisterCascadingDropDownDataSource(x => x.CollectionId, Url.Action("GetCollectionsByType"));
            result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage"));
            result.RegisterCascadingDropDownDataSource(x => x.CategoryIds, Url.Action("GetCategoriesBySite"));
            result.RegisterExternalDataSource(x => x.Status, y => BindStatus());
            result.RegisterExternalDataSource(x => x.VideoType, y => BindVideoTypes());

            return result;
        }

        private IEnumerable<SelectListItem> BindVideoTypes()
        {
            return EnumExtensions.GetListItems<VideoTypes>();
        }

        [Url("admin/get-collections-by-type")]
        public ActionResult GetCollectionsByType()
        {
            var filmGroup = 1;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FilmGroup]))
            {
                filmGroup = Convert.ToInt32(Request.Form[Extensions.Constants.FilmGroup]);
            }

            var result = new List<SelectListItem>();
            if ((FilmGroup)filmGroup == FilmGroup.FilmLengthEpisodes)
            {
                var service = WorkContext.Resolve<ICollectionService>();
                var items = service.GetRecords(x => x.Status == (int)Status.Approved).OrderByDescending(x => x.Id);

                result.AddRange(items.Select(item => new SelectListItem
                {
                    Text = item.Name,
                    Value = item.Id.ToString()
                }));
            }

            result.Insert(0, new SelectListItem { Text = "--- Chọn tên bộ phim ---", Value = "0" });
            return Json(result);
        }

        private IEnumerable<SelectListItem> BindDirectors()
        {
            var service = WorkContext.Resolve<IDirectorService>();
            var items = service.GetRecords(x => x.Status == (int)Status.Approved).OrderByDescending(x => x.Id);
            var result = new List<SelectListItem>();
            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.FullName,
                Value = item.Id.ToString()
            }));
            result.Insert(0, new SelectListItem { Text = "--- Đạo diễn phim ---", Value = "0" });

            return result;
        }

        private IEnumerable<SelectListItem> BindActors()
        {
            var service = WorkContext.Resolve<IActorService>();
            var items = service.GetRecords(x => x.Status == (int)Status.Approved).OrderByDescending(x => x.Id);
            var result = new List<SelectListItem>();
            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.FullName,
                Value = item.Id.ToString()
            }));

            return result;
        }

        private IEnumerable<SelectListItem> BindFilmGroups()
        {
            var items = EnumExtensions.GetListItems<FilmGroup>();
            items.Insert(0, new SelectListItem { Text = "--- Chọn nhóm film ---", Value = "0"});

            return items;
        }

        private IEnumerable<SelectListItem> BindServers()
        {
            var service = WorkContext.Resolve<IFilmServersService>();
            var items = service.GetRecords(x => x.Status == (int)Status.Approved);
            var result = new List<SelectListItem>();
            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.ServerName,
                Value = item.Id.ToString()
            }));
            result.Insert(0, new SelectListItem { Text = "--- Máy chủ phim ---", Value = "0" });

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/films/update")]
        public ActionResult Update(FilmModel model)
        {
            if (!ModelState.IsValid)
            {
				return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var service = WorkContext.Resolve<IFilmService>();
            FilmInfo item;
            if (model.Id == 0)
            {
                item = new FilmInfo();
                item.ViewCount = 20000;
            }
            else
            {
                item = service.GetById(model.Id);
            }

            var alias = model.FilmAlias;
            if (string.IsNullOrEmpty(alias))
            {
                alias = Utilities.GetAlias(model.FilmName);
                if (service.CheckAlias(0, alias))
                {
                    alias += "-" + DateTime.Now.ToString("ddMMyyyyhhmm");
                }
            }

            if (model.Id == 0 && service.CheckName(model.FilmName))
            {
                return new AjaxResult().Alert(T("Đã tồn tại phim này!"));
            }

            if (model.Id == 0)
            {
                item.FilmCode = service.GetLatestFilmCode();
            }

            item.FilmNameEnglish = model.FilmNameEnglish;
            item.FilmName = model.FilmName;
            item.FilmAlias = alias;
            item.LanguageCode = model.LanguageCode;
            item.SiteId = model.SiteId;
            item.CategoryIds = Utilities.ParseString(model.CategoryIds);
            item.FilmTypeIds = Utilities.ParseString(model.FilmTypeIds);
            item.CountryId = model.CountryId;
            item.DirectorId = model.DirectorId;
            item.ActorIds = Utilities.ParseString(model.ActorIds);
            item.CollectionId = model.CollectionId;
            item.ArticlesId = 0;
            item.Time = model.Time;
            item.Capacity = model.Capacity;
            item.ReleaseYear = model.ReleaseYear;
            item.CreateByUserId = WorkContext.CurrentUser.Id;
            item.CreateDate = DateTime.Now;
            item.Contents = model.Contents;
            item.Summary = model.Summary;
            item.Description = model.Description;
            item.Tags = model.Tags;
            item.IsPublished = model.IsPublished;
            if (string.IsNullOrEmpty(model.PublishedDate))
            {
                model.PublishedDate = Extensions.Constants.DateTimeMin;
            }
            item.PublishedDate = DateTime.ParseExact(model.PublishedDate, Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture);
            item.IsHot = model.IsHot;
            item.IsHome = model.IsHome;
            item.Prices = (decimal)model.Prices;
            item.HasCopyright = model.HasCopyright;

            item.StartDate = DateTime.Now;

            //if (string.IsNullOrEmpty(model.StartDate))
            //{
            //    model.StartDate = Extensions.Constants.DateTimeMin;
            //}
            //item.StartDate = DateTime.ParseExact(model.StartDate, Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture);

            item.EndDate = DateTime.Now;
            //if (string.IsNullOrEmpty(model.EndDate))
            //{
            //    model.EndDate = Extensions.Constants.DateTimeMin;
            //}
            //item.EndDate = DateTime.ParseExact(model.EndDate, Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture);

            item.ImageIcon = model.ImageIcon;
            item.ImageThumb = model.ImageThumb;
            item.ServerId = model.ServerId;
            var server = WorkContext.Resolve<IFilmServersService>().GetById(model.ServerId);
            if (server != null)
            {
                item.ServerIp = server.ServerIP;
            }
            item.Status = model.Status;
            bool isFilmRetail = false;
            bool isFilmLengthEpisodes = false;
            switch ((FilmGroup)model.FilmGroup)
            {
                case FilmGroup.FilmRetail:
                    isFilmRetail = true;
                    break;
                case FilmGroup.FilmLengthEpisodes:
                    isFilmLengthEpisodes = true;
                    break;
            }
            item.IsFilmRetail = isFilmRetail;
            item.IsFilmLengthEpisodes = isFilmLengthEpisodes;
            item.IsTheater = model.IsTheater;
            switch ((VideoTypes)model.VideoType)
            {
                case VideoTypes.IsFilm:
                    item.IsFilm = true;
                    item.IsClip = false;
                    item.IsShow = false;
                    item.IsTrailer = false;
                    break;
                case VideoTypes.IsShow:
                    item.IsFilm = false;
                    item.IsClip = false;
                    item.IsShow = true;
                    item.IsTrailer = false;
                    break;
                case VideoTypes.IsClip:
                    item.IsFilm = false;
                    item.IsClip = true;
                    item.IsShow = false;
                    item.IsTrailer = false;
                    break;
                case VideoTypes.IsTrailer:
                    item.IsFilm = false;
                    item.IsClip = false;
                    item.IsShow = false;
                    item.IsTrailer = true;
                    break;
            }

            service.Save(item);

            try
            {
                #region Add Search
                var service2 = WorkContext.Resolve<ISearchService>();
                var searchObject = service2.GetBySearchId(item.Id.ToString(), (int)SearchType.Film);
                long id = 0;
                if (searchObject != null)
                {
                    id = searchObject.Id;
                }

                var search = new SearchInfo
                {
                    Id = id,
                    Title = item.FilmName,
                    Alias = item.FilmAlias,
                    CategoryIds = item.CategoryIds,
                    CreateDate = item.CreateDate,
                    IsBlock = !item.IsPublished,
                    LanguageCode = item.LanguageCode,
                    SearchId = item.Id.ToString(),
                    SiteId = item.SiteId,
                    Sumary = item.Summary,
                    Tags = item.Tags,
                    Type = (int)SearchType.Film,
                    TitleEnglish = item.FilmNameEnglish,
                    Images = item.ImageIcon,
                    ViewCount = item.ViewCount.ToString(),
                    Processed = 0
                };

                service2.Save(search);

                var cacheSearch = new LuceneService();
                cacheSearch.UpdateLuceneIndex(search);
                #endregion
            }
            catch (Exception)
            {
                return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE")
                    .Alert(T("Không thể thêm dữ liệu tìm kiếm."));
            }

            return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"));
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<IFilmService>();
            var item = service.GetById(id);
            item.Status = (int)Status.Deleted;
            service.Update(item);

            return new AjaxResult()
                .NotifyMessage("DELETE_ENTITY_COMPLETE")
                .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!"));
        }
    }
}
<file_sep>﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class LogInfo : BaseEntity<long>
    {
        [DataMember]
        [DisplayName("CreateDate")]
        public DateTime CreateDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextCreateDate
        {
            get
            {
                return CreateDate.ToString(Extensions.Constants.DateTimeFomatFull);
            }
        }

        [DataMember]
        [DisplayName("Type")]
        public int Type { get; set; }

        [DataMember]
        [DisplayName("Messages")]
        public string Messages { get; set; }

        [DataMember]
        [DisplayName("Keyword")]
        public string Keyword { get; set; }

        [DataMember]
        [DisplayName("Contents")]
        public string Contents { get; set; }

        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }
    }

    public class LogMap : EntityTypeConfiguration<LogInfo>, IEntityTypeConfiguration
    {

        public LogMap()
        {
            ToTable("Modules_Logs");
            HasKey(m => m.Id);
            Property(m => m.CreateDate).IsRequired();
            Property(m => m.Messages).IsRequired();
            Property(m => m.Keyword).HasMaxLength(250);
            Property(m => m.Contents).HasMaxLength(250);
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Web.Mvc;
using CMSSolutions.Extensions;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminLogController : BaseAdminController
    {
        public AdminLogController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
            TableName = "tblLogs";
        }

        [Url("admin/logs")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý logs"), Url = "#" });

            var result = new ControlGridFormResult<LogInfo>
            {
                Title = T("Quản lý logs"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetLogs,
                UpdateActionName = "Update",
                ActionsColumnWidth = 100,
                ClientId = TableName,
                EnablePaginate = true,
                DefaultPageSize = WorkContext.DefaultPageSize,
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml
            };

            result.AddCustomVar(Extensions.Constants.FromDate, "$('#" + Extensions.Constants.FromDate + "').val();", true);
            result.AddCustomVar(Extensions.Constants.ToDate, "$('#" + Extensions.Constants.ToDate + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true);
            result.AddCustomVar(Extensions.Constants.TypeSearch, "$('#" + Extensions.Constants.TypeSearch + "').val();", true);
            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true);

            result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(60);
            result.AddColumn(x => x.Keyword, T("Thực hiện bởi"));
            result.AddColumn(x => x.TextCreateDate, T("Ngày tạo"));
            result.AddColumn(x => x.Messages, T("Thông báo"));

            result.AddAction(new ControlFormHtmlAction(() => BuildFromDate())).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildToDate())).HasParentClass(Constants.ContainerCssClassCol3).HasRow(true);
            result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildLogTypes)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildLogStatus)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
                .HasText(T("Chi tiết"))
                .HasUrl(x => Url.Action("ViewDetails", RouteData.Values.Merge(new { id = x.Id })))
                .HasButtonStyle(ButtonStyle.Info)
                .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");

            return result;
        }

        [Url("admin/logs/view/{id}")]
        public ActionResult ViewDetails(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý logs"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin log"), Url = "#" });

            var service = WorkContext.Resolve<ILogService>();
            var model = new LogModel();
            if (id > 0)
            {
                model = service.GetById(id);
            }

            var result = new ControlFormResult<LogModel>(model)
            {
                Title = T("Thông tin log"),
                ShowSubmitButton = false,
                ShowCancelButton = true,
                ShowBoxHeader = false,
                CancelButtonText = T("Trở về"),
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };
            result.ReadOnly = true;

            result.RegisterExternalDataSource(x => x.Type, y => BindLogTypes());
            result.RegisterExternalDataSource(x => x.Status, y => BindLogStatus());

            return result;
        }

        private string BuildLogTypes()
        {
            var list = EnumExtensions.GetListItems<LogType>();
            var sb = new StringBuilder();
            sb.AppendFormat(T("Loại") + " <select id=\"" + Extensions.Constants.TypeSearch + "\" name=\"" + Extensions.Constants.TypeSearch + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var status in list)
            {
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        private IEnumerable<SelectListItem> BindLogTypes()
        {
            var items = EnumExtensions.GetListItems<LogType>();
            items[0].Selected = true;
            return items;
        }

        private string BuildLogStatus()
        {
            var list = EnumExtensions.GetListItems<LogStatus>();
            var sb = new StringBuilder();
            sb.AppendFormat(T("Trạng thái") + " <select id=\"" + Extensions.Constants.StatusId + "\" name=\"" + Extensions.Constants.StatusId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var status in list)
            {
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        private IEnumerable<SelectListItem> BindLogStatus()
        {
            var items = EnumExtensions.GetListItems<LogStatus>();
            items[0].Selected = true;
            return items;
        }

        private ControlGridAjaxData<LogInfo> GetLogs(ControlGridFormRequest options)
        {
            var searchText = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText]))
            {
                searchText = Request.Form[Extensions.Constants.SearchText];
            }

            var fromDate = DateTime.Now.Date;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FromDate]))
            {
                fromDate = DateTime.ParseExact(Request.Form[Extensions.Constants.FromDate], "dd/MM/yyyy", CultureInfo.InvariantCulture);
            }

            var toDate = DateTime.Now.Date;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ToDate]))
            {
                toDate = DateTime.ParseExact(Request.Form[Extensions.Constants.ToDate], "dd/MM/yyyy", CultureInfo.InvariantCulture);
            }

            var type = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.TypeSearch]))
            {
                type = Convert.ToInt32(Request.Form[Extensions.Constants.TypeSearch]);
            }

            var status = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId]))
            {
                status = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]);
            }

            int totals;
            var items = WorkContext.Resolve<ILogService>().GetPaged(searchText, fromDate,toDate, type,status, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<LogInfo>(items, totals);
            return result;
        }
    }
}
<file_sep>using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IFilmVideoService : IGenericService<FilmVideoInfo, long>, IDependency
    {
        IList<FilmVideoInfo> GetByFilm(long filmId, int pageIndex, int pageSize, out int totalRecord);

        FilmVideoInfo GetByFilmFile(long filmId, long fileId);

        IList<FilmVideoInfo> GetFilesByFile(string folderPath);
    }

    public class FilmVideoService : GenericService<FilmVideoInfo, long>, IFilmVideoService
    {
        public FilmVideoService(IRepository<FilmVideoInfo, long> repository, IEventBus eventBus)
            : base(repository, eventBus)
        {

        }

        public IList<FilmVideoInfo> GetByFilm(long filmId, int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@FilmId", filmId),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmVideoInfo>("sp_FilmVideos_GetByFilm", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public FilmVideoInfo GetByFilmFile(long filmId, long fileId)
        {
             var list = new List<SqlParameter>
            {
                AddInputParameter("@FilmId", filmId),
                AddInputParameter("@FileId", fileId)
            };

            return ExecuteReaderRecord<FilmVideoInfo>("sp_FilmVideos_GetByFilmFile", list.ToArray());
        }

        public IList<FilmVideoInfo> GetFilesByFile(string folderPath)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@FolderPath", folderPath)
            };

            return ExecuteReader<FilmVideoInfo>("sp_FilmVideos_GetFilesByFolder", list.ToArray());
        }
    }
}
<file_sep>using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    public class RateInfo : BaseEntity<long>
    {
        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }

        [DataMember]
        [DisplayName("SiteId")]
        public int SiteId { get; set; }

        [DataMember]
        [DisplayName("FilmId")]
        public long FilmId { get; set; }

        [NotMapped]
        [DisplayName("FilmName")]
        public string FilmName { get; set; }

        [DataMember]
        [DisplayName("Rate")]
        public int Rate { get; set; }

        [DataMember]
        [DisplayName("CustomerId")]
        public int CustomerId { get; set; }

        [DataMember]
        [DisplayName("CustomerCode")]
        public string CustomerCode { get; set; }

        [NotMapped]
        [DisplayName("CustomerName")]
        public string CustomerName { get; set; }

        [DataMember]
        [DisplayName("AlertError")]
        public string AlertError { get; set; }

        [DataMember]
        [DisplayName("AlertLag")]
        public string AlertLag { get; set; }

        [DataMember]
        [DisplayName("Messages")]
        public string Messages { get; set; }

        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }
        
        [DataMember]
        [DisplayName("LikeFilm")]
        public bool LikeFilm { get; set; }
    }

    public class RateMap : EntityTypeConfiguration<RateInfo>, IEntityTypeConfiguration
    {

        public RateMap()
        {
            ToTable("Modules_Rates");
            HasKey(m => m.Id);
            Property(m => m.LanguageCode).HasMaxLength(50);
            Property(m => m.CustomerCode).HasMaxLength(250);
            Property(m => m.AlertError).HasMaxLength(250);
            Property(m => m.AlertLag).HasMaxLength(250);
            Property(m => m.Messages).HasMaxLength(2000);
        }
    }
}
<file_sep># CMS_WatchMovieSite
Demo for CMSSolutions
<file_sep>using System.ComponentModel;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{    
    [DataContract]
    public class FilmServerInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("SiteId")]
        public int SiteId { get; set; }

        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }

        [DataMember]
        [DisplayName("ServerName")]
        public string ServerName { get; set; }
        
        [DataMember]
        [DisplayName("ServerIP")]
        public string ServerIP { get; set; }

        [DataMember]
        [DisplayName("FolderRoot")]
        public string FolderRoot { get; set; }

        [DataMember]
        [DisplayName("Locations")]
        public string Locations { get; set; }

        [DataMember]
        [DisplayName("Description")]
        public string Description { get; set; }

        [DataMember]
        [DisplayName("IsVip")]
        public bool IsVip { get; set; }

        [DataMember]
        [DisplayName("IsDefault")]
        public bool IsDefault { get; set; }

        [DataMember]
        [DisplayName("UserName")]
        public string UserName { get; set; }

        [DataMember]
        [DisplayName("Password")]
        public string Password { get; set; }

        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }
    }

    public class FilmServerMap : EntityTypeConfiguration<FilmServerInfo>, IEntityTypeConfiguration
    {

        public FilmServerMap()
        {
            ToTable("Modules_FilmServers");
            HasKey(m => m.Id);
            Property(m => m.LanguageCode).IsRequired().HasMaxLength(50);
            Property(m => m.SiteId).IsRequired();
            Property(m => m.ServerName).HasMaxLength(250).IsRequired();
            Property(m => m.ServerIP).HasMaxLength(50).IsRequired();
            Property(m => m.Locations).HasMaxLength(250);
            Property(m => m.IsVip).IsRequired();
            Property(m => m.IsDefault).IsRequired();
            Property(m => m.UserName).IsRequired().HasMaxLength(400);
            Property(m => m.Password).IsRequired().HasMaxLength(400);
        }
    }
}
<file_sep>﻿using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface ITagService : IGenericService<TagInfo, int>, IDependency
    {
        bool CheckExist(int id, string keyword);

        IList<TagInfo> GetPaged(string keyword, int status, int pageIndex, int pageSize, out int totals);

        IList<TagInfo> GetDisplayTags();
    }

    public class TagService : GenericService<TagInfo, int>, ITagService
    {
        public TagService(IRepository<TagInfo, int> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public bool CheckExist(int id, string keyword)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Id", id),
                AddInputParameter("@Keyword", keyword)
            };
            var result = (int)ExecuteReaderResult("sp_Tags_CheckName", list.ToArray());

            return result > 0;
        }

        public IList<TagInfo> GetPaged(string keyword, int status, int pageIndex, int pageSize, out int totals)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Keyword", keyword),
                AddInputParameter("@Status", status),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<TagInfo>("sp_Tags_Search_Paged", "@TotalRecord", out totals, list.ToArray());
        }

        public IList<TagInfo> GetDisplayTags()
        {
            return ExecuteReader<TagInfo>("sp_Tags_GetDisplay");
        }
    }
}<file_sep>using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class VastInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("SiteId")]
        public int SiteId { get; set; }

        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }

        [DataMember]
        [DisplayName("KeyCode")]
        public string KeyCode { get; set; }

        [DataMember]
        [DisplayName("AdId")]
        public int AdId { get; set; }

        [NotMapped]
        [DisplayName("AdName")]
        public string AdName { get; set; }

        [DataMember]
        [DisplayName("AdSystemVersion")]
        public string AdSystemVersion { get; set; }

        [DataMember]
        [DisplayName("AdSystemValue")]
        public string AdSystemValue { get; set; }

        [DataMember]
        [DisplayName("AdTitle")]
        public string AdTitle { get; set; }

        [DataMember]
        [DisplayName("LinkError")]
        public string LinkError { get; set; }

        [DataMember]
        [DisplayName("LinkImpression")]
        public string LinkImpression { get; set; }

        [DataMember]
        [DisplayName("Skipoffset")]
        public string Skipoffset { get; set; }

        [DataMember]
        [DisplayName("Duration")]
        public string Duration { get; set; }

        [DataMember]
        [DisplayName("LinkClickThrough")]
        public string LinkClickThrough { get; set; }

        [DataMember]
        [DisplayName("TrackingEvent1")]
        public string TrackingEvent1 { get; set; }

        [DataMember]
        [DisplayName("TrackingValue1")]
        public string TrackingValue1 { get; set; }

        [DataMember]
        [DisplayName("TrackingEvent2")]
        public string TrackingEvent2 { get; set; }

        [DataMember]
        [DisplayName("TrackingValue2")]
        public string TrackingValue2 { get; set; }

        [DataMember]
        [DisplayName("TrackingEvent3")]
        public string TrackingEvent3 { get; set; }

        [DataMember]
        [DisplayName("TrackingValue3")]
        public string TrackingValue3 { get; set; }

        [DataMember]
        [DisplayName("TrackingEvent4")]
        public string TrackingEvent4 { get; set; }

        [DataMember]
        [DisplayName("TrackingValue4")]
        public string TrackingValue4 { get; set; }

        [DataMember]
        [DisplayName("TrackingEvent5")]
        public string TrackingEvent5 { get; set; }

        [DataMember]
        [DisplayName("TrackingValue5")]
        public string TrackingValue5 { get; set; }

        [DataMember]
        [DisplayName("TrackingEvent6")]
        public string TrackingEvent6 { get; set; }

        [DataMember]
        [DisplayName("TrackingValue6")]
        public string TrackingValue6 { get; set; }

        [DataMember]
        [DisplayName("MediaFileBitrate")]
        public int MediaFileBitrate { get; set; }

        [DataMember]
        [DisplayName("MediaFileDelivery")]
        public string MediaFileDelivery { get; set; }

        [DataMember]
        [DisplayName("MediaFileHeight")]
        public int MediaFileHeight { get; set; }

        [DataMember]
        [DisplayName("MediaFileWidth")]
        public int MediaFileWidth { get; set; }

        [DataMember]
        [DisplayName("MediaFileMaintainAspectRatio")]
        public bool MediaFileMaintainAspectRatio { get; set; }

        [DataMember]
        [DisplayName("MediaFileScalable")]
        public bool MediaFileScalable { get; set; }

        [DataMember]
        [DisplayName("MediaFileType")]
        public string MediaFileType { get; set; }

        [DataMember]
        [DisplayName("MediaFileValue")]
        public string MediaFileValue { get; set; }
    }

    public class VastMap : EntityTypeConfiguration<VastInfo>, IEntityTypeConfiguration
    {

        public VastMap()
        {
            ToTable("Modules_Vast");
            HasKey(m => m.Id);
            Property(m => m.LanguageCode).HasMaxLength(50);
            Property(m => m.KeyCode).HasMaxLength(50);
            Property(m => m.AdSystemVersion).HasMaxLength(50);
            Property(m => m.AdSystemValue).HasMaxLength(250);
            Property(m => m.AdTitle).HasMaxLength(250);
            Property(m => m.LinkError).HasMaxLength(500);
            Property(m => m.LinkImpression).HasMaxLength(500);
            Property(m => m.Skipoffset).HasMaxLength(50);
            Property(m => m.Duration).HasMaxLength(50);
            Property(m => m.LinkClickThrough).HasMaxLength(500);
            Property(m => m.TrackingEvent1).HasMaxLength(50);
            Property(m => m.TrackingValue1).HasMaxLength(500);
            Property(m => m.TrackingEvent2).HasMaxLength(50);
            Property(m => m.TrackingValue2).HasMaxLength(500);
            Property(m => m.TrackingEvent3).HasMaxLength(50);
            Property(m => m.TrackingValue3).HasMaxLength(500);
            Property(m => m.TrackingEvent4).HasMaxLength(50);
            Property(m => m.TrackingValue4).HasMaxLength(500);
            Property(m => m.TrackingEvent5).HasMaxLength(50);
            Property(m => m.TrackingValue5).HasMaxLength(500);
            Property(m => m.TrackingEvent6).HasMaxLength(50);
            Property(m => m.TrackingValue6).HasMaxLength(500);
            Property(m => m.MediaFileDelivery).HasMaxLength(50);
            Property(m => m.MediaFileType).HasMaxLength(50);
            Property(m => m.MediaFileValue).HasMaxLength(500);
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using CMSSolutions.Extensions;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminSliderController : BaseAdminController
    {
        public AdminSliderController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
            TableName = "tblSlider";
        }

        [Url("admin/slider")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý slider"), Url = "#" });

            var result = new ControlGridFormResult<SliderInfo>
            {
                Title = T("Quản lý slider"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetSlider,
                UpdateActionName = "Update",
                ActionsColumnWidth = 100,
                ClientId = TableName,
                DefaultPageSize = WorkContext.DefaultPageSize,
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml
            };

            result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.PageId, "$('#" + Extensions.Constants.PageId + "').val();", true);

            result.AddColumn(x => x.OrderBy, T("Vị trí")).AlignCenter().HasWidth(60);
            result.AddColumn(x => EnumExtensions.GetDisplayName((SliderPages)x.PageId), T("Trang hiển thị"));
            result.AddColumn(x => x.CategoryName, T("Chuyên mục"));
            result.AddColumn(x => x.FilmName, T("Tên phim"));
          
            result.AddAction().HasText(T("Thêm mới"))
               .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
               .HasButtonStyle(ButtonStyle.Primary)
               .HasBoxButton(false)
               .HasCssClass(Constants.RowLeft)
               .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildSites(false, null))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildPages)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
                .HasText(T("Sửa"))
                .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                .HasButtonStyle(ButtonStyle.Default)
                .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddRowAction(true)
                .HasText(T("Xóa"))
                .HasName("Delete")
                .HasValue(x => x.Id)
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");
            return result;
        }

        protected ControlGridAjaxData<SliderInfo> GetSlider(ControlGridFormRequest options)
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var pageId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.PageId]))
            {
                pageId = Convert.ToInt32(Request.Form[Extensions.Constants.PageId]);
            }

            int totals;
            var service = WorkContext.Resolve<ISliderService>();
            service.LanguageCode = languageCode;
            service.SiteId = siteId;
            var records = service.GetPaged(
                pageId,
                options.PageIndex,
                options.PageSize,
                out totals);

            return new ControlGridAjaxData<SliderInfo>(records, totals);
        }

        private string BuildPages()
        {
            var list = EnumExtensions.GetListItems<SliderPages>();
            var sb = new StringBuilder();
            sb.AppendFormat(T("Trang hiển thị") + " <select id=\"" + Extensions.Constants.PageId + "\" name=\"" + Extensions.Constants.PageId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var item in list)
            {
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", item.Text, item.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        [Url("admin/slider/edit/{id}")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý slider"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin slider"), Url = "#" });

            var model = new SliderModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<ISliderService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<SliderModel>(model)
            {
                Title = T("Thông tin slider"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                CancelButtonText = T("Đóng"),
                ShowBoxHeader = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.RegisterFileUploadOptions("Images.FileName", new ControlFileUploadOptions
            {
                AllowedExtensions = "jpg,jpeg,png,gif"
            });

            result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages());
            result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage"));
            result.RegisterCascadingDropDownDataSource(x => x.CategoryId, Url.Action("GetCategoriesBySite"));
            result.RegisterCascadingDropDownDataSource(x => x.FilmId, Url.Action("GetFilmsByCategory"));
            result.RegisterExternalDataSource(x => x.PageId, y => BindPages());

            return result;
        }

        [Url("admin/get-films-by-category")]
        public ActionResult GetFilmsByCategory()
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = int.Parse(Request.Form[Extensions.Constants.SiteId]);
            }

            var categoryId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.CategoryId]))
            {
                categoryId = int.Parse(Request.Form[Extensions.Constants.CategoryId]);
            }

            var service = WorkContext.Resolve<IFilmService>();
            service.SiteId = siteId;
            service.LanguageCode = languageCode;
            service.CategoryId = categoryId;
            var items = service.GetAllByCategoryId();
            var result = new List<SelectListItem>();
            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.FilmName,
                Value = item.Id.ToString()
            }));

            result.Insert(0, new SelectListItem { Text = "--- Chọn phim ---", Value = "0" });

            return Json(result);
        }


        private IEnumerable<SelectListItem> BindPages()
        {
            var items = EnumExtensions.GetListItems<SliderPages>();
            return items;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/slider/update")]
        public ActionResult Update(SliderModel model)
        {
            var service = WorkContext.Resolve<ISliderService>();
            var service2 = WorkContext.Resolve<IFilmService>();
            var film = service2.GetById(model.FilmId);
            SliderInfo item = model.Id == 0 ? new SliderInfo() : service.GetById(model.Id);
            item.LanguageCode = model.LanguageCode;
            item.SiteId = model.SiteId;
            item.CategoryId = model.CategoryId;
            item.FilmId = model.FilmId;
            item.Images = model.Images;
            if (film != null && string.IsNullOrEmpty(model.Images))
            {
                item.Images = film.ImageThumb; 
            }
            item.PageId = model.PageId;
            item.OrderBy = model.OrderBy;

            service.Save(item);

            return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE").Alert(T("Cập nhật thành công!"));
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<ISliderService>();
            var model = service.GetById(id);
            service.Delete(model);

            return new AjaxResult().NotifyMessage("DELETE_ENTITY_COMPLETE");
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using CMSSolutions.ContentManagement.Widgets.Services;
using CMSSolutions.DisplayManagement;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Themes;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = false)]
    public class HomeViewController : BaseHomeController
    {
        private readonly dynamic shapeFactory;
        public HomeViewController(IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory) 
            : base(workContextAccessor)
        {
            this.shapeFactory = shapeFactory;
        }

        [Url("xem-phim/{alias}/f{id}.html")]
        public ActionResult FilmView(string alias, long id, int tap = 0, int trang = 1)
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            SiteId = (int)Site.Home;
            BuildFilmModules(id, tap, trang);

            return View("FilmView");
        }

        [HttpPost, ValidateInput(false)]
        [Url("xem-tap/phan-trang.html")]
        public ActionResult EpisodesPager()
        {
            var pageIndex = Convert.ToInt32(Request.Form["pageIndex"]);
            var siteId = Convert.ToInt32(Request.Form["siteId"]);
            var filmId = long.Parse(Request.Form["filmId"]);
            var pageSize = Convert.ToInt32(Request.Form["pageSize"]);
            var episodeId = Convert.ToInt32(Request.Form["episodeId"]);
            int totalRow;
            var service = WorkContext.Resolve<IFilmService>();
            service.LanguageCode = WorkContext.CurrentCulture;
            service.SiteId = siteId;
            var model = new DataViewerModel();
            var listData = service.GetFilmEpisodes(filmId, pageIndex, pageSize, out  totalRow);
            if (listData != null && listData.Count > 0)
            {
                var html = new StringBuilder();
                for (int i = 0; i < listData.Count; i ++)
                {
                    html.Append(BuildItem(listData[i], episodeId, pageIndex));
                }

                model = new DataViewerModel
                {
                    Status = true,
                    PageSize = pageSize,
                    TotalRow = totalRow,
                    Data = html.ToString()
                };
            }

            return Json(model);
        }

        private void BuildFilmModules(long filmId, int episodeId, int pageIndex)
        {
            var widget = WorkContext.Resolve<IWidgetService>();
            var viewRenderer = new ViewRenderer { Context = ControllerContext };
            if (!IsVip)
            {
                #region BannerPageLeft
                var bannerPageLeft = widget.GetWidget(HomeWidgets.BannerPageLeft.ToString());
                if (bannerPageLeft != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageLeft;
                    WorkContext.Layout.AdBannerPageLeft(widgetShape);
                }
                #endregion

                #region BannerPageCenter
                var bannerPageCenter = widget.GetWidget(HomeWidgets.BannerPageCenter.ToString());
                if (bannerPageCenter != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageCenter;
                    WorkContext.Layout.AdBannerPageCenter(widgetShape);
                }
                #endregion

                #region BannerPageRight
                var bannerPageRight = widget.GetWidget(HomeWidgets.BannerPageRight.ToString());
                if (bannerPageRight != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageRight;
                    WorkContext.Layout.AdBannerPageRight(widgetShape);
                }
                #endregion
            }
            else
            {
                #region BannerPageLeftVip
                var bannerPageLeftVip = widget.GetWidget(HomeWidgets.BannerPageLeftVip.ToString());
                if (bannerPageLeftVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageLeftVip;
                    WorkContext.Layout.AdBannerPageLeftVip(widgetShape);
                }
                #endregion

                #region BannerPageCenterVip
                var bannerPageCenterVip = widget.GetWidget(HomeWidgets.BannerPageCenterVip.ToString());
                if (bannerPageCenterVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageCenterVip;
                    WorkContext.Layout.AdBannerPageCenterVip(widgetShape);
                }
                #endregion

                #region BannerPageRightVip
                var bannerPageRightVip = widget.GetWidget(HomeWidgets.BannerPageRightVip.ToString());
                if (bannerPageRightVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageRightVip;
                    WorkContext.Layout.AdBannerPageRightVip(widgetShape);
                }
                #endregion
            }

            var model = new DataViewerModel();
            model.CustomerCode = CustomerCode;
            #region HomeSliderBanner
            var service = WorkContext.Resolve<IFilmService>();
            service.LanguageCode = WorkContext.CurrentCulture;
            service.SiteId = SiteId;

            model.Skin = Extensions.Constants.JWplayerSkin;
            model.JwplayerKey = Extensions.Constants.JWplayerKey;
            model.FilmDetails = service.GetFilmsMovie(filmId, episodeId) ?? service.GetFilmDetails(filmId);
            model.DataType = (int)LinkType.Streaming;
            var trailer = service.GetTrailerMovie(filmId);
            if (trailer != null)
            {
                model.Url = trailer.EncodeSourceUrl;
            }

            ViewData[Extensions.Constants.HeaderTitle] = model.FilmDetails.FilmName;
            ViewData[Extensions.Constants.HeaderDescription] = model.FilmDetails.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = model.FilmDetails.Tags;
            service.UpdateViewCount(model.FilmDetails.Id);

            var advertisementService = WorkContext.Resolve<IAdvertisementGroupService>();
            model.Advertisement = advertisementService.GetAdByCategories(WorkContext.CurrentCulture, SiteId, model.FilmDetails.CategoryIds);
            model.AdvertisementsPath = Convert.ToBase64String(Encoding.UTF8.GetBytes("/"));
            if (model.Advertisement != null)
            {
                model.AdvertisementsPath = model.Advertisement.EncodeFullPath;
            }

            if (!string.IsNullOrEmpty(model.FilmDetails.UrlAlbum))
            {
                model.DataType = (int)LinkType.Picasa;
                var picasaService = new PicasaService();
                model.ListFilmsPicasa = picasaService.ParseRssFile(model.FilmDetails.UrlAlbum, model.FilmDetails.UrlSource);
            }

            if (model.FilmDetails.IsClip)
            {
                model.DataType = (int)LinkType.Youtube;
                model.Url = model.FilmDetails.EncodeSourceUrl;
            }

            var viewSliderBanner = viewRenderer.RenderPartialView(Extensions.Constants.MoviesFilePath, model);
            WorkContext.Layout.SliderBanner.Add(new MvcHtmlString(viewSliderBanner));
            #endregion

            #region CategoryContentLeftFirst
            model.SliderName = "ShowListEpisodes";
            if (model.FilmDetails.IsFilmLengthEpisodes)
            {
                model.IsShow = true;
            }

            if (model.FilmDetails.IsFilm && model.FilmDetails.IsFilmLengthEpisodes)
            {
                model.Title = "Tập phim:";
            }

            if (model.FilmDetails.IsShow && model.FilmDetails.IsFilmLengthEpisodes)
            {
                model.Title = "Tập show:";
            }

            model.EpisodeId = model.FilmDetails.EpisodeId;
            model.SiteId = SiteId;
            model.PageSize = 99999;
            model.PageIndex = 1;

            var totalRow = 0;
            var listData = service.GetFilmEpisodes(filmId, 1, 99999, out  totalRow);
            if (listData != null && listData.Count > 0)
            {
                var html = new StringBuilder();
                for (int i = 0; i < listData.Count; i++)
                {
                    html.Append(BuildItem2(listData[i], episodeId, pageIndex));
                }

                model.Status = true;
                model.PageSize = 99999;
                model.TotalRow = totalRow;
                model.Data = html.ToString();
            }

            var viewFirst = viewRenderer.RenderPartialView(Extensions.Constants.ListMoviesViewFilePath, model);
            WorkContext.Layout.CategoryContentLeftFirst.Add(new MvcHtmlString(viewFirst));
            #endregion

            var viewModel = new DataViewCategoryModel();
            viewModel.UrlNext = "http://" + Extensions.Constants.HomeDomainName + Url.Action("FilmView", "HomeView", new { @alias = model.FilmDetails.FilmAlias, @id = model.FilmDetails.Id, @tap = model.FilmDetails.EpisodeId });
            
            #region CategoryContentLeftSecond
            var viewCommentSecond = viewRenderer.RenderPartialView(Extensions.Constants.FacebookCommentsFilePath, viewModel);
            WorkContext.Layout.CategoryContentLeftSecond.Add(new MvcHtmlString(viewCommentSecond));
            #endregion

            #region CategoryContentFirst
            var modelFirst = new DataViewCategoryModel
            {
                Type = (int)HomeDisplayFilmType.FilmHot,
                Title = "Sự kiện: Phim Đang HOT",
                TextNext = "Còn nữa ››",
                UrlNext = Url.Action("FilmHot", "HomeCategory"),
                SliderName = "FilmFirst"
            };
            modelFirst.HtmlFilmHot = GetFilmHtml(modelFirst.Type);
            var viewFilmFirst = viewRenderer.RenderPartialView(Extensions.Constants.CategoryContentFirstViewFilePath, modelFirst);
            WorkContext.Layout.CategoryContentLeftThird.Add(new MvcHtmlString(viewFilmFirst));
            #endregion

            #region BannerRightFirst
            viewModel.FilmDetails = model.FilmDetails;
            viewModel.Breadcrumb = BuildBreadcrumb(Utilities.ParseListInt(model.FilmDetails.CategoryIds)[0], model.FilmDetails);
            var bannerRightFirst = viewRenderer.RenderPartialView(Extensions.Constants.FilmRateFilePath, viewModel);
            WorkContext.Layout.AdBannerRightFirst.Add(new MvcHtmlString(bannerRightFirst));
            #endregion

            #region DisplayStatistic3
            var modelStatistic3 = new DataViewCategoryModel
            {
                Type = (int)HomeDisplayFilmType.StatisticalNextFilm,
                Title = "PHIM LIÊN QUAN",
                FilmDetails = model.FilmDetails
            };
            if (model.FilmDetails.IsClip)
            {
                modelStatistic3.Title = "CLIP LIÊN QUAN";
            }
            if (model.FilmDetails.IsShow)
            {
                modelStatistic3.Title = "SHOW LIÊN QUAN";
            }
            if (model.FilmDetails.IsTrailer)
            {
                modelStatistic3.Title = "TRAILER LIÊN QUAN";
            }
            var viewStatistic3 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic6FilePath, modelStatistic3);
            WorkContext.Layout.DisplayStatistic1.Add(new MvcHtmlString(viewStatistic3));
            #endregion
        }

        private string BuildBreadcrumb(int cateId, FilmInfo film)
        {
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;
            serviceCategory.SiteId = SiteId;
            CategoryInfo category = serviceCategory.GetByIdCache(cateId);

            var html = new StringBuilder();
            html.Append("<div class=\"mh-breadcrumb-dv\">");
            html.Append("<div>");
            html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span><img width=\"22\" src=\"/Images/themes/ico-homesm.png\"></span></a>", "Dành cho víp", "/");
            html.Append("</div>/ ");
            if (category.ParentId > 0)
            {
                var parent = serviceCategory.GetByIdCache(category.ParentId);
                html.Append("<div>");
                html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span>{0}</span></a>", parent.ShortName, Url.Action("Index", "HomeCategory", new { @alias = parent.Alias, @id = parent.Id }));
                html.Append("</div>/ ");
            }
            html.Append("<div>");
            html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span>{0}</span></a>", category.ShortName, "#");
            html.Append("</div>");
            html.AppendFormat("<h1 class=\"title_h1_st3\">{0}</h1>", film.FilmName);
            html.AppendFormat("<p>{0}</p>", film.Summary);
            html.Append("</div>");

            return html.ToString();
        }

        private string BuildItem(FilmInfo item, int episodeId, int trang)
        {
            var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id, @tap = item.EpisodeId, @trang = trang });
            var html = new StringBuilder();
            if (episodeId == item.EpisodeId)
            {
                html.Append("<div class=\"show_tv-epi-img film-actived\">");
            }
            else
            {
                html.Append("<div class=\"show_tv-epi-img\">");
            }
            html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url, item.FilmName);
            html.AppendFormat("<img alt=\"{0}\" width=\"106\" height=\"80\" src=\"{1}\">", item.FilmAlias, item.ImageIcon);
            html.AppendFormat("<span class=\"epi_span\">{0}</span>", item.EpisodeName);
            html.Append("</a>");
            html.Append(" </div>");

            return html.ToString();
        }

        private string BuildItem2(FilmInfo item, int episodeId, int trang)
        {
            var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id, @tap = item.EpisodeId, @trang = trang });
            var html = new StringBuilder();
            html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url, item.FilmName);
            if (episodeId == item.EpisodeId)
            {
                html.Append("<div class=\"show_tv-epi-img film-actived\">");
            }
            else
            {
                html.Append("<div class=\"show_tv-epi-img\">");
            }
           
            html.AppendFormat("<span class=\"epi_span\">{0}</span>", item.EpisodeIndex);
            html.Append(" </div>");
            html.Append("</a>");

            return html.ToString();
        }
    }
}
<file_sep>using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class CustomerHistoriesModel
    {
        [ControlHidden()]
        public long Id { get; set; }
        
        [ControlNumeric(LabelText="Customer Id", Order=0, Required=true)]
        public int CustomerId { get; set; }
        
        [ControlDatePicker(LabelText="Create Date", Order=0, Required=true)]
        public System.DateTime CreateDate { get; set; }
        
        [ControlText(Required=true, MaxLength=250)]
        public string Action { get; set; }
        
        [ControlText(Required=true, MaxLength=2000)]
        public string Description { get; set; }
        
        [ControlNumeric(LabelText="Status", Order=0, Required=false)]
        public int Status { get; set; }

        public static implicit operator CustomerHistoriesModel(CustomerHistoriesInfo entity)
        {
            return new CustomerHistoriesModel
            {
                Id = entity.Id,
                CustomerId = entity.CustomerId,
                CreateDate = entity.CreateDate,
                Action = entity.Action,
                Description = entity.Description,
                Status = entity.Status
            };
        }

    }
}
<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class LogModel
    {
        [ControlHidden]
        public long Id { get; set; }

        [ControlText(LabelText = "Ngày tạo", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public string TextCreateDate { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Loại", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public int Type { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public int Status { get; set; }

        [ControlText(LabelText = "Thực hiện bởi", Type = ControlText.TextBox, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)]
        public string Keyword { get; set; }

        [ControlText(LabelText = "Thông báo", Type = ControlText.MultiText, Rows = 3, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 2)]
        public string Messages { get; set; }

        [ControlText(LabelText = "Nội dung thực hiện", Type = ControlText.MultiText, Rows = 2, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)]
        public string Contents { get; set; }

        public static implicit operator LogModel(LogInfo entity)
        {
            return new LogModel
            {
                Id = entity.Id,
                TextCreateDate = entity.TextCreateDate,
                Type = entity.Type,
                Messages = entity.Messages,
                Contents = entity.Contents,
                Keyword = entity.Keyword,
                Status = entity.Status
            };
        }
    }
}<file_sep>﻿using System.ComponentModel;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class SupportInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("SiteId")]
        public int SiteId { get; set; }

        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }

        [DataMember]
        [DisplayName("Title")]
        public string Title { get; set; }

        [DataMember]
        [DisplayName("Messages")]
        public string Messages { get; set; }

        [DataMember]
        [DisplayName("IsGroup")]
        public bool IsGroup { get; set; }

        [DataMember]
        [DisplayName("OrderBy")]
        public int OrderBy { get; set; }

        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }

        [DataMember]
        [DisplayName("ParentId")]
        public int ParentId { get; set; }
    }

    public class SupportMap : EntityTypeConfiguration<SupportInfo>, IEntityTypeConfiguration
    {
        public SupportMap()
        {
            ToTable("Modules_Supports");
            HasKey(x => x.Id);
            Property(x => x.LanguageCode).HasMaxLength(50).IsRequired();
            Property(x => x.Title).IsRequired().HasMaxLength(250);
            Property(x => x.Messages).HasMaxLength(2000);
        }
    }
}<file_sep>﻿using System;

namespace CMSSolutions.Websites.Entities
{
    public class PicasaInfo
    {
        public string Medium { get; set; }

        public string Url { get; set; }

        public string Type { get; set; }

        public int Width { get; set; }

        public int Height { get; set; }

        public string EncodeUrl
        {
            get
            {
                if (!string.IsNullOrEmpty(Url))
                {
                    return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Url));
                }

                return string.Empty;
            }
        }
    }
}<file_sep>﻿using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface ICityService : IGenericService<CityInfo, int>, IDependency
    {

    }

    public class CityService : GenericService<CityInfo, int>, ICityService
    {
        public CityService(IRepository<CityInfo, int> repository, IEventBus eventBus) : base(repository, eventBus)
        {

        }
    }
}<file_sep>﻿using System;
using System.Web;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Payments;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.API
{
    public class SmsService : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            string partnerid = context.Request["partnerid"];
            string moid = context.Request["moid"];
            string userid = context.Request["userid"];
            string shortcode = context.Request["shortcode"];
            string keyword = context.Request["keyword"];
            string subkeyword = context.Request["subkeyword"];
            string content = context.Request["content"];
            string transdate = context.Request["transdate"];
            string checksum = context.Request["checksum"];
            string amount = context.Request["amount"];
            var service = new APISmsService();
            var request = new APISms();
            string url = request.UrlSMSMT;
            var transactionCode = Utilities.GenerateUniqueNumber();
            var code = HttpUtility.UrlDecode(content);
            var entityMO = new TransactionSmsInfo
            {
                Id = 0,
                PartnerId = partnerid,
                MoId = moid,
                UserId = userid,
                ShortCode = shortcode,
                Keyword = keyword,
                Subkeyword = subkeyword,
                Content = content,
                TransDate = transdate,
                CheckSum = checksum,
                Amount = amount,
                CreateDate = DateTime.Now,
                Status = (int)RequestStatus.Messages01,
                Type = (int)SMSType.MO,
                MtId = "",
                CustomerCode = "",
                TransactionCode = transactionCode,
                StartDate = new DateTime(1900,01,01),
                EndDate = new DateTime(1900, 01, 01),
                IsLock = false
            };
            try
            {
                LogFiles.WriteLogSms(string.Format("MO URL: {0}", context.Request.Url.AbsoluteUri));
                service.InsertLog(new LogInfo
                {
                    CreateDate = DateTime.Now,
                    Messages = string.Format("MO URL: {0}", context.Request.Url.AbsoluteUri),
                    Keyword = userid,
                    Contents = code + " " + shortcode,
                    Type = (int)LogType.SMS,
                    Status = (int)LogStatus.Information
                });


                int totalDate;
                DateTime? startDate;
                DateTime? endDate;
                var totalMoney = service.Amount(shortcode, out totalDate, out startDate, out endDate);
                entityMO.TotalDay = totalDate;
                entityMO.StartDate = startDate;
                entityMO.EndDate = endDate;

                var list = code.Split(' ');
                if (list.Length <= 1)
                {
                    LogFiles.WriteLogSms(string.Format("MO: CUSTOMERCODE NOT FOUND IN CONTENT: {0}", content));
                    entityMO.IsLock = true;
                    service.SmsProcessing(entityMO);
                    request.SentMT(moid, shortcode, keyword, userid, string.Format(Extensions.Constants.SMSCustomerNotFound , transactionCode), ref url);
                    service.InsertLog(new LogInfo
                    {
                        CreateDate = DateTime.Now, 
                        Messages = string.Format("MO: CUSTOMERCODE NOT FOUND IN CONTENT: {0}", content),
                        Keyword = userid,
                        Contents = code + " " + shortcode,
                        Type = (int)LogType.SMS,
                        Status = (int)LogStatus.Error
                    });
                    context.Response.Write(string.Format("message:requeststatus=200"));
                    return;
                }

                var helpKey = list[1].Trim().ToUpper();
                var customerCode = list[1];
                var rejectShortCode = (ShortCode)int.Parse(shortcode);
                if (rejectShortCode == ShortCode.DauSo8376 && helpKey.ToUpper() == "HD")
                {
                    LogFiles.WriteLogSms(string.Format("MO: HELP USER: {0}", Extensions.Constants.SMSUserHelp));
                    service.SmsProcessing(entityMO);
                    request.SentMT(moid, shortcode, keyword, userid, Extensions.Constants.SMSUserHelp, ref url);
                    service.InsertLog(new LogInfo
                    {
                        CreateDate = DateTime.Now,
                        Messages = string.Format("MO: HELP USER: {0}", Extensions.Constants.SMSUserHelp),
                        Keyword = userid,
                        Contents = code + " " + shortcode,
                        Type = (int)LogType.SMS,
                        Status = (int)LogStatus.Error
                    });
                    context.Response.Write(string.Format("message:requeststatus=200"));
                    return;
                }

                var customer = service.GetByCustomerCode(customerCode);
                if (customer == null)
                {
                    entityMO.IsLock = true;
                    service.SmsProcessing(entityMO);
                    request.SentMT(moid, shortcode, keyword, userid, string.Format(Extensions.Constants.SMSCustomerNotFound, transactionCode), ref url);
                    service.InsertLog(new LogInfo
                    {
                        CreateDate = DateTime.Now,
                        Messages = string.Format("MO: CUSTOMERCODE NOT FOUND: {0}", customerCode),
                        Keyword = userid,
                        Contents = code + " " + shortcode,
                        Type = (int)LogType.SMS,
                        Status = (int)LogStatus.Error
                    });
                    LogFiles.WriteLogSms(string.Format("SYSTEM SAVE SUCCESS"));
                    context.Response.Write(string.Format("message:requeststatus=200"));
                    return;
                }

                var currentSum = request.Md5(moid + shortcode + keyword + content + transdate + request.Password).ToLower();
                if (checksum.Length != currentSum.Length)
                {
                    LogFiles.WriteLogSms(string.Format("MO: CHECKSUM FAILED {0} - {1}", checksum.Length, currentSum.Length));
                    service.SmsProcessing(entityMO);
                    request.SentMT(moid, shortcode, keyword, userid, Extensions.Constants.SMSSyntax, ref url);
                    service.InsertLog(new LogInfo
                    {
                        CreateDate = DateTime.Now,
                        Messages = string.Format("MO: CHECKSUM FAILED {0} - {1}", checksum.Length, currentSum.Length),
                        Keyword = userid,
                        Contents = code + " " + shortcode,
                        Type = (int)LogType.SMS,
                        Status = (int)LogStatus.Error
                    });
                    context.Response.Write(string.Format("message:requeststatus=200"));
                    return;
                }

                if (rejectShortCode != ShortCode.DauSo8576 
                    && rejectShortCode != ShortCode.DauSo8676 
                    && rejectShortCode != ShortCode.DauSo8776)
                {
                    LogFiles.WriteLogSms(string.Format("MO: SHORTCODE {0}", shortcode));
                    request.SentMT(moid, shortcode, keyword, userid, Extensions.Constants.SMSSyntax, ref url);
                    service.InsertLog(new LogInfo
                    {
                        CreateDate = DateTime.Now,
                        Messages = string.Format("MO: SHORTCODE {0}", shortcode),
                        Keyword = userid,
                        Contents = code + " " + shortcode,
                        Type = (int)LogType.SMS,
                        Status = (int)LogStatus.Error
                    });
                    context.Response.Write(string.Format("message:requeststatus=200"));
                    return;
                }

                var status = Send(url, moid, userid, shortcode, keyword, entityMO.Amount, subkeyword, transdate, checksum, customer, totalDate, startDate, endDate, transactionCode);
                if (status == RequestStatus.Messages200)
                {
                    entityMO.Amount = totalMoney;
                    entityMO.Status = (int)RequestStatus.Messages200;
                    entityMO.CustomerCode = customer.CustomerCode;
                    service.SmsProcessing(entityMO);
                }
                else
                {
                    entityMO.Status = (int)RequestStatus.Messages01;
                    service.SmsProcessing(entityMO);
                }
                LogFiles.WriteLogSms(string.Format("MO INSERT: {0} SUCCESSFUL", (int)status));
                service.InsertLog(new LogInfo
                {
                    CreateDate = DateTime.Now,
                    Messages = string.Format("MO: INSERT: {0} SUCCESSFUL", (int)status),
                    Keyword = userid,
                    Contents = code + " " + shortcode,
                    Type = (int)LogType.SMS,
                    Status = (int)LogStatus.Information
                });
                context.Response.Write(string.Format("message:requeststatus=200"));
            }
            catch (Exception ex)
            {
                entityMO.Status = (int)RequestStatus.Messages01;
                service.SmsProcessing(entityMO);
                var st = request.SentMT(moid, shortcode, keyword, userid, Extensions.Constants.SMSSystemError, ref url);
                LogFiles.WriteLogSms(string.Format("Error: {0} - {1} ", ex.Message, st));
                service.InsertLog(new LogInfo
                {
                    CreateDate = DateTime.Now,
                    Messages = string.Format("Error: {0}", ex.Message),
                    Keyword = userid,
                    Contents = code + " " + shortcode,
                    Type = (int)LogType.SMS,
                    Status = (int)LogStatus.Error
                });
                context.Response.Write(string.Format("message:requeststatus=200"));
            }
        }

        private RequestStatus Send(string url, string moid, string userid, string shortcode,
            string keyword, string amount,
            string subkeyword, string transdate, string checksum, CustomerInfo customer,
            int totalDate, DateTime? startDate, DateTime? endDate, string transactionCode)
        {
            var service = new APISmsService();
            var request = new APISms();
            var messages = string.Format("VIPHD.VN: Xin chuc mung ban da dang ky thanh cong goi tai tro {0} ngay cho tai khoan {1} tren VIPHD! Chan thanh cam on!", totalDate, customer.CustomerCode);
            var status = (RequestStatus)request.SentMT(moid, shortcode, keyword, userid, messages, ref url);
            LogFiles.WriteLogSms(string.Format("Day: {0} - StartDate: {1} - EndDate: {2} - MT URL - {3}: {4}", totalDate, startDate != null ? startDate.Value.ToString() : "", endDate != null ? endDate.Value.ToString() : "", url, customer.CustomerCode));
            service.InsertLog(new LogInfo
            {
                CreateDate = DateTime.Now,
                Messages = string.Format("MT: REQUEST SUCCESSFUL: Day: {0} - StartDate: {1} - EndDate: {2} - CUSTOMERCODE: {3} - MT URL - {4}", totalDate, startDate != null ? startDate.Value.ToString() : "", endDate != null ? endDate.Value.ToString() : "", customer.CustomerCode, url),
                Keyword = userid,
                Contents = keyword + " " + shortcode,
                Type = (int)LogType.SMS,
                Status = (int)LogStatus.Success
            });

            var entityMT = new TransactionSmsInfo
            {
                Id = 0,
                PartnerId = request.PartnerId,
                MoId = moid,
                MtId = request.CreateMTId(),
                UserId = userid,
                ShortCode = shortcode,
                Keyword = keyword,
                Subkeyword = subkeyword,
                Content = messages,
                CreateDate = DateTime.Now,
                Status = (int)status,
                Type = (int)SMSType.MT,
                TransDate = transdate,
                CheckSum = checksum,
                Amount = amount,
                CustomerCode = customer.CustomerCode,
                TotalDay = totalDate,
                StartDate = startDate,
                EndDate = endDate,
                TransactionCode = transactionCode
            };

            service.SmsProcessing(entityMT);
            service.InsertLog(new LogInfo
            {
                CreateDate = DateTime.Now,
                Messages = string.Format("MT: INSERT {0} SUCCESSFUL", (int)status),
                Keyword = userid,
                Contents = keyword + " " + shortcode,
                Type = (int)LogType.SMS,
                Status = (int)LogStatus.Information
            });

            return status;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}<file_sep>﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class PromotionCustomerInfo : BaseEntity<long>
    {
        [DataMember]
        [DisplayName("PromotionId")]
        public int PromotionId { get; set; }

        [NotMapped]
        [DisplayName("Title")]
        public string Title { get; set; }

        [DataMember]
        [DisplayName("CustomerId")]
        public int CustomerId { get; set; }

        [DataMember]
        [DisplayName("CustomerCode")]
        public string CustomerCode { get; set; }

        [NotMapped]
        [DisplayName("FullName")]
        public string FullName { get; set; }

        [DataMember]
        [DisplayName("CreateDate")]
        public DateTime CreateDate { get; set; }

        [DataMember]
        [DisplayName("Code")]
        public string Code { get; set; }

        [DataMember]
        [DisplayName("Value")]
        public string Value { get; set; }

        [DataMember]
        [DisplayName("Description")]
        public string Description { get; set; }

        [DataMember]
        [DisplayName("IsUsed")]
        public bool IsUsed { get; set; }

        [DataMember]
        [DisplayName("UsedDate")]
        public DateTime? UsedDate { get; set; }

        [DataMember]
        [DisplayName("IsSendMessages")]
        public bool IsSendMessages { get; set; }

        [DataMember]
        [DisplayName("SendDate")]
        public DateTime? SendDate { get; set; }
    }

    public class PromotionCustomerMap : EntityTypeConfiguration<PromotionCustomerInfo>, IEntityTypeConfiguration
    {
        public PromotionCustomerMap()
        {
            ToTable("Modules_PromotionCustomers");
            HasKey(m => m.Id);
            Property(m => m.CustomerCode).IsRequired().HasMaxLength(50);
            Property(m => m.Code).IsRequired().HasMaxLength(50);
            Property(m => m.Value).IsRequired().HasMaxLength(50);
            Property(m => m.PromotionId).IsRequired();
            Property(m => m.CustomerId).IsRequired();
        }
    }
}<file_sep>﻿using System;
using System.Web.Mvc;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminTagController : BaseAdminController
    {
        public AdminTagController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
            TableName = "tblTags";
        }

        [Url("admin/tags")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý tags"), Url = "#" });

            var result = new ControlGridFormResult<TagInfo>
            {
                Title = T("Quản lý tags"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetTags,
                UpdateActionName = "Update",
                ActionsColumnWidth = 100,
                ClientId = TableName,
                EnablePaginate = true,
                DefaultPageSize = WorkContext.DefaultPageSize,
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml
            };

            result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true);
            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true);

            result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(60);
            result.AddColumn(x => x.Name, T("Tiêu đề"));
            result.AddColumn(x => x.Alias, T("Tên không dấu"));
            result.AddColumn(x => x.IsDisplay)
                .HasHeaderText(T("Hiển thị"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage();

            result.AddAction().HasText(T("Thêm mới"))
               .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
               .HasButtonStyle(ButtonStyle.Primary)
               .HasBoxButton(false)
               .HasCssClass(Constants.RowLeft)
               .HasRow(true)
               .ShowModalDialog();

            result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
                .HasText(T("Sửa"))
                .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                .HasButtonStyle(ButtonStyle.Default)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .ShowModalDialog();

            result.AddRowAction(true)
                .HasText(T("Xóa"))
                .HasName("Delete")
                .HasValue(x => x.Id)
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");

            return result;
        }

        private ControlGridAjaxData<TagInfo> GetTags(ControlGridFormRequest options)
        {
            var searchText = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText]))
            {
                searchText = Request.Form[Extensions.Constants.SearchText];
            }

            var status = -1;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId]))
            {
                var display = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]);
                if (display == (int)Status.Approved)
                {
                    status = 1;
                }
                else
                {
                    status = 0;
                }
            }

            int totals;
            var items = WorkContext.Resolve<ITagService>().GetPaged(searchText,status, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<TagInfo>(items, totals);
            return result;
        }

        [Themed(false)]
        [Url("admin/tags/edit/{id}")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý tags"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin tags"), Url = "#" });

            var service = WorkContext.Resolve<ITagService>();
            var model = new TagModel();
            if (id > 0)
            {
                model = service.GetById(id);
            }

            var result = new ControlFormResult<TagModel>(model)
            {
                Title = T("Thông tin tags"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                ShowCancelButton = true,
                ShowBoxHeader = false,
                CancelButtonText = T("Đóng"),
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };
            result.MakeReadOnlyProperty(x => x.Alias);

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/tags/update")]
        public ActionResult Update(TagModel model)
        {
            if (!ModelState.IsValid)
            {
                return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }
           
            var service = WorkContext.Resolve<ITagService>();
            TagInfo item = model.Id == 0 ? new TagInfo() : service.GetById(model.Id);
            if (service.CheckExist(model.Id, model.Name))
            {
                return new AjaxResult()
                    .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                    .Alert(T("Tiêu đề đã tồn tại!"));
            }

            var alias = Utilities.GetCharUnsigned(model.Name);
            if (service.CheckExist(model.Id, alias))
            {
                return new AjaxResult()
                    .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                    .Alert(T("Tên không dấu đã tồn tại!"));
            }

            item.Alias = Utilities.GetAlias(model.Name);
            item.Name = model.Name;
            item.IsDisplay = model.IsDisplay;

            service.Save(item);
            return new AjaxResult()
                .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"))
                .CloseModalDialog();
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<ITagService>();
            var item = service.GetById(id);
            item.IsDisplay = false;
            service.Update(item);

            return new AjaxResult()
                .NotifyMessage("DELETE_ENTITY_COMPLETE")
                .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!"));
        }
    }
}
<file_sep>using System.ComponentModel;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class BankCardInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("BankCode")]
        public string BankCode { get; set; }
        
        [DataMember]
        [DisplayName("BankName")]
        public string BankName { get; set; }
        
        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }
    }
    
    public class BankCardMap : EntityTypeConfiguration<BankCardInfo>, IEntityTypeConfiguration
    {

        public BankCardMap()
        {
            ToTable("Modules_BankCards");
            HasKey(m => m.Id);
            Property(m => m.BankCode).IsRequired().HasMaxLength(50);
            Property(m => m.BankName).IsRequired().HasMaxLength(250);
        }
    }
}
<file_sep>﻿using System.Web.Mvc;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminDownloadGamesController : BaseAdminController
    {
        public AdminDownloadGamesController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
            TableName = "tblDownloadGames";
        }

        [Url("admin/download-games")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Sự kiện đào xu"), Url = "#" });

            var result = new ControlGridFormResult<DownloadGameInfo>
            {
                Title = T("Sự kiện đào xu"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetDownloadGames,
                DefaultPageSize = WorkContext.DefaultPageSize,
                EnablePaginate = true,
                UpdateActionName = "Update",
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml,
                ClientId = TableName,
                ActionsColumnWidth = 100
            };

            result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true);
            result.AddColumn(x => x.Id, T("Mã")).HasWidth(60);
            result.AddColumn(x => x.Logo, T("Logo"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsImage(y => y.Logo, Extensions.Constants.CssThumbsSize);

            result.AddColumn(x => x.Title, T("Tiêu đề"));
            result.AddColumn(x => x.VipXu, T("VIPXU"));
            result.AddColumn(x => x.IsActived)
                .HasHeaderText(T("Đã sử dụng"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage(true);

            result.AddAction().HasText(T("Thêm mới"))
               .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
               .HasButtonStyle(ButtonStyle.Primary)
               .HasBoxButton(false)
               .HasCssClass(Constants.RowLeft)
               .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
                 .HasText(T("Sửa"))
                 .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                 .HasButtonStyle(ButtonStyle.Default)
                 .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddRowAction(true)
                .HasText(T("Xóa"))
                .HasName("Delete")
                .HasValue(x => x.Id)
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");

            return result;
        }

        private ControlGridAjaxData<DownloadGameInfo> GetDownloadGames(ControlGridFormRequest options)
        {
            var searchText = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText]))
            {
                searchText = Request.Form[Extensions.Constants.SearchText];
            }

            int totals;
            var items = WorkContext.Resolve<IDownloadGameService>().SearchPaged(searchText, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<DownloadGameInfo>(items, totals);
            return result;
        }

        [Url("admin/download-games/edit/{id}")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Sự kiện đào xu"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin sự kiện"), Url = "#" });

            var model = new DownloadGameModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<IDownloadGameService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<DownloadGameModel>(model)
            {
                Title = T("Thông tin sự kiện"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                ShowCancelButton = true,
                ShowBoxHeader = false,
                CancelButtonText = T("Trở về"),
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };
            result.MakeReadOnlyProperty(x => x.Code);

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/download-games/update")]
        public ActionResult Update(DownloadGameModel model)
        {
            if (!ModelState.IsValid)
            {
                return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var service = WorkContext.Resolve<IDownloadGameService>();
            DownloadGameInfo item = model.Id == 0 ? new DownloadGameInfo() : service.GetById(model.Id);

            item.Title = model.Title;
            item.Code = model.Code;
            item.UrlBanner = model.UrlBanner;
            item.Logo = model.Logo;
            item.GooglePlayUrl = model.GooglePlayUrl;
            item.WebsiteUrl = model.WebsiteUrl;
            item.VipXu = model.VipXu;
            item.IsActived = model.IsActived;

            service.Save(item);

            return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"));
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<IDownloadGameService>();
            var item = service.GetById(id);
            service.Delete(item);

            return new AjaxResult()
                .NotifyMessage("DELETE_ENTITY_COMPLETE")
                .Alert(T("Đã xóa dữ liệu này thành công!"));
        }
    }
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface ICustomerHistoriesService : IGenericService<CustomerHistoriesInfo, long>, IDependency
    {
        IList<CustomerHistoriesInfo> GetPaged(int customerId, DateTime fromDate, DateTime toDate, int type, int status, int pageIndex, int pageSize, out int totalRecord);

        List<NapVipCustomerLogs> GetNapVipByCustomer(int customerId);

        List<TransactioCustomerLogs> GetDoiXuByCustomer(string customerCode);
    }

    public class CustomerHistoriesService : GenericService<CustomerHistoriesInfo, long>, ICustomerHistoriesService
    {
        public CustomerHistoriesService(IRepository<CustomerHistoriesInfo, long> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public IList<CustomerHistoriesInfo> GetPaged(int customerId, DateTime fromDate, DateTime toDate, 
            int type, int status, int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@CustomerId", customerId),
                AddInputParameter("@Type", type),
                AddInputParameter("@FromDate", fromDate),
                AddInputParameter("@ToDate", toDate),
                AddInputParameter("@Status", status),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<CustomerHistoriesInfo>("sp_CustomerHistories_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public List<NapVipCustomerLogs> GetNapVipByCustomer(int customerId)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@CustomerId", customerId)
            };

            return ExecuteReader<NapVipCustomerLogs>("sp_NapVipLogs", list.ToArray());
        }

        public List<TransactioCustomerLogs> GetDoiXuByCustomer(string customerCode)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@CustomerCode", customerCode)
            };

            return ExecuteReader<TransactioCustomerLogs>("sp_TransactioLogs", list.ToArray());
        }
    }
}
<file_sep>﻿using System.Web.Mvc;
using CMSSolutions.ContentManagement.Widgets.Services;
using CMSSolutions.DisplayManagement;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Themes;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = false)]
    public class HomeSupportController : BaseHomeController
    {
        private readonly dynamic shapeFactory;
        public HomeSupportController(IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory) 
            : base(workContextAccessor)
        {
            this.shapeFactory = shapeFactory;
        }

        [Url("ho-tro.html")]
        public ActionResult Index()
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            SiteId = (int)Site.Home;
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;
            serviceCategory.SiteId = SiteId;
            var category = serviceCategory.GetByIdCache((int)FixCategories.Support);
            ViewData[Extensions.Constants.HeaderTitle] = category.Name;
            ViewData[Extensions.Constants.HeaderDescription] = category.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = category.Tags;

            BuildModules();

            return View();
        }

        public override void BuildModules()
        {
            var widget = WorkContext.Resolve<IWidgetService>();
            var viewRenderer = new ViewRenderer { Context = ControllerContext };
            if (!IsVip)
            {
                #region BannerRightFifth
                var bannerRightFifth = widget.GetWidget(HomeWidgets.BannerRightFifth.ToString());
                if (bannerRightFifth != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerRightFifth;
                    WorkContext.Layout.AdBannerRightFifth(widgetShape);
                }
                #endregion
            }
            else
            {
                #region BannerPageLeftVip
                var bannerPageLeftVip = widget.GetWidget(HomeWidgets.BannerPageLeftVip.ToString());
                if (bannerPageLeftVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageLeftVip;
                    WorkContext.Layout.AdBannerPageLeftVip(widgetShape);
                }
                #endregion

                #region BannerPageCenterVip
                var bannerPageCenterVip = widget.GetWidget(HomeWidgets.BannerPageCenterVip.ToString());
                if (bannerPageCenterVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageCenterVip;
                    WorkContext.Layout.AdBannerPageCenterVip(widgetShape);
                }
                #endregion

                #region BannerPageRightVip
                var bannerPageRightVip = widget.GetWidget(HomeWidgets.BannerPageRightVip.ToString());
                if (bannerPageRightVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageRightVip;
                    WorkContext.Layout.AdBannerPageRightVip(widgetShape);
                }
                #endregion
            }

            #region HomeFooterLogoInformation
            var homeFooterLogoInformation = widget.GetWidget(HomeWidgets.HomeFooterLogoInformation.ToString());
            if (homeFooterLogoInformation != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = homeFooterLogoInformation;
                WorkContext.Layout.FooterLogoInformation(widgetShape);
            }
            #endregion

            #region BannerRightFirst
            var view = viewRenderer.RenderPartialView(Extensions.Constants.DivDisplayFilePath, null);
            WorkContext.Layout.AdBannerRightFirst.Add(new MvcHtmlString(view));
            #endregion

            #region HomeFacebookFanpage
            var homeFacebookFanpage = widget.GetWidget(HomeWidgets.HomeFacebookFanpage.ToString());
            if (homeFacebookFanpage != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = homeFacebookFanpage;
                WorkContext.Layout.AdFacebookFanpage(widgetShape);
            }
            #endregion

            #region SocialNetwork
            var socialNetwork = widget.GetWidget(HomeWidgets.DisplaySocialNetwork.ToString());
            if (socialNetwork != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = socialNetwork;
                WorkContext.Layout.DisplaySocialNetwork(widgetShape);
            }
            #endregion

            #region News
            var viewNews = viewRenderer.RenderPartialView(Extensions.Constants.NewsViewFilePath, null);
            WorkContext.Layout.DisplayNews.Add(new MvcHtmlString(viewNews));
            #endregion

            #region DisplayStatistic1
            var modelStatistic1 = new DataViewCategoryModel
            {
                Type = (int)HomeDisplayFilmType.StatisticalFilmRetail,
                Title = "PHIM LẺ XEM NHIỀU NHẤT"
            };
            var viewStatistic1 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic1FilePath, modelStatistic1);
            WorkContext.Layout.DisplayStatistic1.Add(new MvcHtmlString(viewStatistic1));
            #endregion

            #region DisplayStatistic2
            var modelStatistic2 = new DataViewCategoryModel
            {
                Type = (int)HomeDisplayFilmType.StatisticalLengthEpisodes,
                Title = "PHIM BỘ XEM NHIỀU NHẤT"
            };
            var viewStatistic2 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic2FilePath, modelStatistic2);
            WorkContext.Layout.DisplayStatistic2.Add(new MvcHtmlString(viewStatistic2));
            #endregion

            #region DisplayStatistic3
            var modelStatistic3 = new DataViewCategoryModel
            {
                Type = (int)HomeDisplayFilmType.StatisticalTrailer,
                Title = "PHIM SẮP CHIẾU"
            };
            var viewStatistic3 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic5FilePath, modelStatistic3);
            WorkContext.Layout.AdBannerRightSecond.Add(new MvcHtmlString(viewStatistic3));
            #endregion

            #region Tags
            var serviceTags = WorkContext.Resolve<ITagService>();
            var modelTags = new TagViewModel { ListTags = serviceTags.GetDisplayTags() };
            var viewTags = viewRenderer.RenderPartialView(Extensions.Constants.TagViewFilePath, modelTags);
            WorkContext.Layout.DisplayTags.Add(new MvcHtmlString(viewTags));
            #endregion

            #region HomeFacebookFollow
            var facebookFollow = widget.GetWidget(HomeWidgets.HomeFacebookFollow.ToString());
            if (facebookFollow != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = facebookFollow;
                WorkContext.Layout.AdBannerRightThird(widgetShape);
            }
            #endregion

            #region HomeFacebookActivity
            var facebookActivity = widget.GetWidget(HomeWidgets.HomeFacebookActivity.ToString());
            if (facebookActivity != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = facebookActivity;
                WorkContext.Layout.DisplayTags(widgetShape);
            }
            #endregion

            #region HomeGoogleBadge
            var googleBadge = widget.GetWidget(HomeWidgets.HomeGoogleBadge.ToString());
            if (googleBadge != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = googleBadge;
                WorkContext.Layout.AdBannerRightFourth(widgetShape);
            }
            #endregion

            #region CategoryContentFirst
            var modelFirst = new DataViewCategoryModel();
            var service = WorkContext.Resolve<ISupportService>();
            modelFirst.Title = "FAQs / Những câu hỏi thường gặp";
            service.SiteId = SiteId;
            service.LanguageCode = WorkContext.CurrentCulture;
            modelFirst.ListSupportParents = service.GetAllParents((int) Status.Approved);
            modelFirst.ListSupportChildren = service.GetAllChildren((int) Status.Approved);
            var viewFilmFirst = viewRenderer.RenderPartialView(Extensions.Constants.SupportsViewFilePath, modelFirst);
            WorkContext.Layout.CategoryContentLeftFirst.Add(new MvcHtmlString(viewFilmFirst));
            #endregion
        }
    }
}
<file_sep>﻿using System;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class AdvertisementModel
    {
        public AdvertisementModel()
        {
            KeyCode = Guid.NewGuid().ToString().Replace("-", string.Empty);
            Code = "pre-blueseed";
            Type = "tags";
            Position = 0;
            Price = 0;
            Duration = 15;
            Skip = 5;
            IsBlock = false;
        }

        [ControlHidden]
        public int Id { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.CategoryId + "').empty();")]
        public string LanguageCode { get; set; }

        [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public int SiteId { get; set; }

        [ControlText(Type = ControlText.TextBox, ReadOnly = true, LabelText = "Mã quảng cáo", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public string KeyCode { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Tiêu đề", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)]
        public string Title { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn VAST", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 2)]
        public string Link { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Key", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)]
        public string Code { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Loại", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)]
        public string Type { get; set; }

        [ControlNumeric(LabelText = "Thời gian", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)]
        public int Duration { get; set; }

        [ControlNumeric(LabelText = "Vị trí bắt đầu", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)]
        public int Position { get; set; }

        [ControlNumeric(LabelText = "Thời gian skip", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)]
        public int Skip { get; set; }

        [ControlNumeric(LabelText = "Chi phí", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)]
        public float Price { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Tạm khóa", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 5)]
        public bool IsBlock { get; set; }

        public static implicit operator AdvertisementModel(AdvertisementInfo entity)
        {
            if (entity == null)
            {
                return null;
            }

            return new AdvertisementModel
            {
                Id = entity.Id,
                LanguageCode = entity.LanguageCode,
                SiteId = entity.SiteId,
                Title = entity.Title,
                KeyCode = entity.KeyCode,
                Price = (float)entity.Price,
                Code = entity.Code,
                Link = entity.Link,
                Type = entity.Type,
                Duration = entity.Duration,
                Position = entity.Position,
                Skip = entity.Skip,
                IsBlock = entity.IsBlock
            };
        }
    }
}<file_sep>﻿using System.Web.Mvc;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminSmsMessageController : BaseAdminController
    {
        public AdminSmsMessageController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
            TableName = "tblSmsMessages";
        }

        [Url("admin/sms-messages")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý tin nhắn"), Url = "#" });

            var result = new ControlGridFormResult<SmsMessageInfo>
            {
                Title = T("Quản lý tin nhắn"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetSmsMessages,
                UpdateActionName = "Update",
                ActionsColumnWidth = 100,
                ClientId = TableName,
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml
            };

            result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true);

            result.AddColumn(x => x.Code, T("Mã"));
            result.AddColumn(x => x.Message, T("Thông báo"));
            result.AddColumn(x => (x.IsEvent ? "Sự kiện" :"Không sự kiện"), T("Loại tin"));

            result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(false, string.Empty))).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
                .HasText(T("Sửa"))
                .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                .HasButtonStyle(ButtonStyle.Default)
                .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            return result;
        }

        private ControlGridAjaxData<SmsMessageInfo> GetSmsMessages(ControlGridFormRequest options)
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var items = WorkContext.Resolve<ISmsMessageService>().GetRecords(x => x.LanguageCode == languageCode);
            var result = new ControlGridAjaxData<SmsMessageInfo>(items);
            return result;
        }

        [Url("admin/sms-messages/edit/{id}")]
        public ActionResult Edit(int id)
        {
            var model = new SmsMessageModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<ISmsMessageService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<SmsMessageModel>(model)
            {
                Title = T("Thông tin tin nhắn"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                ShowCancelButton = false,
                ShowBoxHeader = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.AddAction().HasText(T("Trở về"))
               .HasUrl(Url.Action("Index"))
               .HasCssClass("btn btn-danger");

            result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages());

            return result;
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using CMSSolutions.Caching;
using CMSSolutions.ContentManagement.Messages.Domain;
using CMSSolutions.ContentManagement.Messages.Services;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;

namespace CMSSolutions.Websites.Services
{
    public interface ICustomerService : IGenericService<CustomerInfo, int>, IDependency
    {
        string GetLatestCustomerCode();

        List<CustomerInfo> SearchPaged(
            string searchText,
            int filmTypeId,
            int countryId,
            DateTime fromDate,
            DateTime toDate,
            int isBlock,
            int status,
            int pageIndex,
            int pageSize,
            out int totalRecord);

        CustomerInfo Login(string userName, string password);

        CustomerInfo CheckRegister(string userName);

        CustomerInfo GetByCustomerCode(string customerCode);

        int ExchangeDay(int customerId, int day, int vipXu, string transactionCode, string package);

        IList<CustomerInfo> GetPromotions(int promotionId);

        int ChangePassword(string userName, string passwordOld, string password);

        CustomerInfo ResetTotalDay(int customerId);

        void ResetCacheCustomers();

        CustomerInfo GetCustomerByCacheId(int customerId);

        int AddVipXu(int customerId, int downloadId, int vipXu);

        IList<CustomerInfo> ExportExcel();

        CustomerInfo GetMemberForgetPassword(string newPassword, string email);

        void AddEmailMessages();

        List<CustomerInfo> GetPaged(int pageIndex, int pageSize, out int totalRecord);

        IList<QueuedEmail> GetQueuedEmails(int sentTries, DateTime sentOnUtc, int pageIndex, int pageSize, out int totalRecord);
    }

    public class CustomerService : GenericService<CustomerInfo, int>, ICustomerService
    {
        private readonly ICacheInfo cacheManager;
        private readonly IMessageService messageService;
        private readonly IFilmService filmService;
        public CustomerService(IRepository<CustomerInfo, int> repository, 
            IEventBus eventBus, ICacheInfo cacheManager, 
            IMessageService messageService, IFilmService filmService) 
            : base(repository, eventBus)
        {
            this.cacheManager = cacheManager;
            this.messageService = messageService;
            this.filmService = filmService;
        }

        public string GetLatestCustomerCode()
        {
            return (string)ExecuteReaderResult("NextCustomerCode");
        }

        public List<CustomerInfo> SearchPaged(
            string searchText, int filmTypeId, int countryId, 
            DateTime fromDate, DateTime toDate, int isBlock,
            int status, int pageIndex, int pageSize, 
            out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SearchText", searchText),
                AddInputParameter("@FilmTypeId", filmTypeId),
                AddInputParameter("@CountryId", countryId),
                AddInputParameter("@FromDate", fromDate),
                AddInputParameter("@ToDate", toDate),
                AddInputParameter("@IsBlock", isBlock),
                AddInputParameter("@Status", status),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<CustomerInfo>("sp_Customers_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public CustomerInfo Login(string userName, string password)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@UserName", userName),
                AddInputParameter("@Password", <PASSWORD>),
            };

            return ExecuteReaderRecord<CustomerInfo>("sp_Customers_Login", list.ToArray());
        }

        public CustomerInfo CheckRegister(string userName)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@UserName", userName),
            };

            return ExecuteReaderRecord<CustomerInfo>("sp_Customers_CheckRegister", list.ToArray());
        }

        public CustomerInfo GetByCustomerCode(string customerCode)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@CustomerCode", customerCode),
            };

            return ExecuteReaderRecord<CustomerInfo>("sp_Customers_GetByCustomerCode", list.ToArray());
        }

        public int ExchangeDay(int customerId, int day, int vipXu, string transactionCode, string package)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@CustomerId", customerId),
                AddInputParameter("@Day", day),
                AddInputParameter("@VipXu", vipXu),
                AddInputParameter("@TransactionCode", transactionCode),
                AddInputParameter("@Package", package)
            };

            return (int)ExecuteReaderResult("sp_Customers_ExchangeDay", list.ToArray());
        }

        public IList<CustomerInfo> GetPromotions(int promotionId)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@PromotionId", promotionId)
            };

            return ExecuteReader<CustomerInfo>("sp_Customers_GetPromotions", list.ToArray());
        }

        public int ChangePassword(string userName, string passwordOld, string password)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@UserName", userName),
                AddInputParameter("@PasswordOld", <PASSWORD>Old),
                AddInputParameter("@Password", <PASSWORD>)
            };

            return (int)ExecuteReaderResult("sp_Customers_ChangePassword", list.ToArray());
        }

        public CustomerInfo ResetTotalDay(int customerId)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@CustomerId", customerId),
            };

            return ExecuteReaderRecord<CustomerInfo>("sp_Customers_ResetTotalDay", list.ToArray());
        }

        public void ResetCacheCustomers()
        {
            cacheManager.Remove(Extensions.Constants.CacheKeys.CUSTOMERS_DATA_CARD);
            cacheManager.Add(Extensions.Constants.CacheKeys.CUSTOMERS_DATA_CARD, GetAllCustomers());
        }

        public CustomerInfo GetCustomerByCacheId(int customerId)
        {
            var data = cacheManager.Get(Extensions.Constants.CacheKeys.CUSTOMERS_DATA_CARD);
            if (data == null)
            {
                ResetCacheCustomers();
                data = cacheManager.Get(Extensions.Constants.CacheKeys.CUSTOMERS_DATA_CARD);
            }

            var items = ((IList<CustomerInfo>) data);
            return items.FirstOrDefault(x => x.Id == customerId);
        }

        private IList<CustomerInfo> GetAllCustomers()
        {
            return ExecuteReader<CustomerInfo>("sp_Customers_GetAllCustomerCache");
        }


        private string BuildHtmlEmail()
        {
            var html = new StringBuilder();
            filmService.SiteId = (int)Site.Home;
            filmService.LanguageCode = "vi-VN";
            var listFilms = filmService.BuildFilmHot();
            if (listFilms != null && listFilms.Count > 0)
            {
                foreach (var filmInfo in listFilms)
                {
                    var url = string.Format("http://viphd.vn/xem-phim/{0}/f{1}.html", filmInfo.FilmAlias, filmInfo.Id);
                    var urlImage = string.Format("http://viphd.vn{0}", filmInfo.ImageIcon);
                   
                    html.Append("<div style=\"margin-right: 15px;padding: 8px 0px;width: 250px;float: left;\">");
                    html.Append("<div style=\"float: left;background-color: #FFF;box-shadow: 0px 0px 5px #999;-moz-box-shadow: 0px 0px 5px #999;-webkit-box-shadow: 0px 0px 5px #999;margin-right: 8px;\">");
                    html.AppendFormat("<a style=\"text-decoration: none;\" title=\"{0}\" href=\"{1}\">", filmInfo.FilmNameEnglish, url);
                    html.AppendFormat("<img alt=\"{0}\" width=\"106\" height=\"80\" src=\"{1}\">", filmInfo.FilmName, urlImage);
                    html.Append("</a>");
                    html.Append("</div>");
                    html.Append("<div style=\"float: left;\">");
                    html.Append("<p style=\"max-height: 35px;overflow: hidden;color: #44619d;font-family: 'SFUGillSansRegular';font-size: 14px;font-style: normal;font-weight: 200;text-transform: capitalize;line-height: 16px;\">");
                    html.AppendFormat("<a style=\"color: #44619d;font-family: 'SFUGillSansRegular';font-size: 14px;font-style: normal;font-weight: 200;text-transform: capitalize;line-height: 16px;text-transform: uppercase;\" title=\"{0}\" href=\"{1}\">{0}</a>", filmInfo.FilmNameEnglish, url);
                    html.Append("</p>");
                    html.Append("<p style=\"max-height: 36px;overflow: hidden;line-height: 18px;color: #666666;font-family: 'SFUGillSansRegular';font-size: 12px;font-style: normal;font-weight: 200;text-transform: capitalize;\">");
                    html.AppendFormat("<a style=\"color: #666666;font-family: 'SFUGillSansRegular';font-size: 12px;font-style: normal;font-weight: 200;text-transform: capitalize;line-height: 14px;\" title=\"{0}\" href=\"{1}\">{0}</a>", filmInfo.FilmName, url);
                    html.Append("</p>");
                    html.Append("<p style=\"color: #696969;font-size: 11px;font-family: Arial, Helvetica, sans-serif;line-height: 14px;overflow: hidden;\">");
                    html.Append(filmInfo.Summary);
                    html.Append("</p>");
                    html.Append("</div>");
                    html.Append("<br class=\"clear_both\">");
                    html.Append("</div>");
                }
            }

            return html.ToString();
        }

        public int AddVipXu(int customerId, int downloadId, int vipXu)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@CustomerId", customerId),
                AddInputParameter("@DownloadId", downloadId),
                AddInputParameter("@VipXu", vipXu)
            };

            return (int)ExecuteReaderResult("sp_Customers_UpdateVipXu", list.ToArray());
        }

        public IList<CustomerInfo> ExportExcel()
        {
            return ExecuteReader<CustomerInfo>("sp_Customers_GetAllCustomers");
        }

        public CustomerInfo GetMemberForgetPassword(string newPassword, string email)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@NewPassword", newPassword),
                AddInputParameter("@Email", email)
            };

            return ExecuteReaderRecord<CustomerInfo>("sp_Customers_ForgetPassword", list.ToArray());
        }

        public List<CustomerInfo> GetPaged(int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<CustomerInfo>("sp_Customers_GetPaged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public void AddEmailMessages()
        {
            try
            {
                int pageIndex = 1;
                int pageSize = 200;
                int totalRecord = 0;
                int totalPage = 1;

                var htmlBody = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/Media/Default/EmailTemplates/FilmHot.html"));
                var customers = GetPaged(pageIndex, pageSize, out totalRecord);
                if (customers != null && totalRecord > 0)
                {
                    if (totalRecord <= pageSize)
                    {
                        totalPage = 1;
                    }
                    else
                    {
                        var count = totalRecord % pageSize;
                        if ((count == 0))
                        {
                            totalPage = totalRecord / pageSize;
                        }
                        else
                        {
                            totalPage = ((totalRecord - count) / pageSize) + 1;
                        }
                    }

                    for (int i = 1; i <= totalPage; i++)
                    {
                        try
                        {
                            if (i > 1)
                            {
                                customers = GetPaged(pageIndex, pageSize, out totalRecord);
                            }

                            htmlBody = htmlBody.Replace("[LIST_FILM]", BuildHtmlEmail());
                            foreach (var customer in customers)
                            {
                                try
                                {
                                    var mailMessage = new MailMessage
                                    {
                                        Subject = "Phim hot nhất trong ngày",
                                        SubjectEncoding = Encoding.UTF8,
                                        Body = htmlBody,
                                        BodyEncoding = Encoding.UTF8,
                                        IsBodyHtml = true,
                                        Sender = new MailAddress(customer.Email)
                                    };

                                    mailMessage.To.Add(customer.Email);
                                    mailMessage.Bcc.Add("<EMAIL>");
                                    messageService.SendEmailMessage(mailMessage);
                                }
                                catch (Exception)
                                {
                                    
                                }
                                
                            }
                        }
                        catch (Exception)
                        {
                           
                        }

                        pageIndex++;
                    }
                }
            }
            catch (Exception)
            {

            }
        }

        public IList<QueuedEmail> GetQueuedEmails(int sentTries, DateTime sentOnUtc, int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SentTries", sentTries),
                AddInputParameter("@SentOnUtc", sentOnUtc),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<QueuedEmail>("sp_QueuedEmails_GetMessages_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Store;

namespace CMSSolutions.Websites.Services
{
    public class SearchCondition
    {
        public string[] SearchField { get; set; }

        public string Keyword { get; set; }

        public bool ConditionForField { get; set; }

        public SearchCondition(string[] fields, string keyword, bool condition)
        {
            this.ConditionForField = condition;
            this.SearchField = fields;
            this.Keyword = keyword;
        }

        public SearchCondition(string[] fields, string keyword)
        {
            this.ConditionForField = true;
            this.SearchField = fields;
            this.Keyword = keyword;
        }

        public SearchCondition(string fields, string keyword)
        {
            this.ConditionForField = true;
            this.SearchField = new string[] { fields };
            this.Keyword = keyword;
        }
    }

    public interface ILuceneService
    {

    }

    public class LuceneService : ILuceneService
    {
        public LuceneService()
        {
            SiteId = (int)Site.Home;
        }

        public int SiteId { get; set; }

        private string _luceneDir
        {
            get
            {
                return Path.Combine(Extensions.Constants.SearchEngineDBPath, SiteId.ToString());
            }
        }

        private FSDirectory _directoryTemp;
        private FSDirectory _directory
        {
            get
            {
                if (_directoryTemp == null) _directoryTemp = FSDirectory.Open(new DirectoryInfo(_luceneDir));
                if (IndexWriter.IsLocked(_directoryTemp)) IndexWriter.Unlock(_directoryTemp);
                var lockFilePath = Path.Combine(_luceneDir, "write.lock");
                if (File.Exists(lockFilePath)) File.Delete(lockFilePath);
                return _directoryTemp;
            }
        }

        public bool ClearLuceneIndexRecord(int record_id)
        {
            var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
            using (var writer = new IndexWriter(_directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED))
            {
                try
                {
                    var searchQuery = new TermQuery(new Term("Id", record_id.ToString()));
                    writer.DeleteDocuments(searchQuery);
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
                finally
                {
                    analyzer.Close();
                    writer.Close();
                    writer.Dispose();
                }
            }
        }

        public bool AddUpdateLuceneIndex(DataTable table)
        {
            var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
            using (var writer = new IndexWriter(_directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED))
            {
                try
                {
                    writer.DeleteAll();
                    foreach (DataRow row in table.Rows)
                    {
                        var document = new Document();
                       
                        document.Add(new Field("Id", row["Id"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("LanguageCode", row["LanguageCode"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("SiteId", row["SiteId"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("CategoryIds", row["CategoryIds"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("CategoryNames", row["CategoryNames"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("Type", row["Type"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("SearchId", row["SearchId"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("Title", row["Title"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("Alias", row["Alias"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("Sumary", row["Sumary"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("Tags", row["Tags"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("CreateDate", DateTime.Parse(row["CreateDate"].ToString()).ToString(Extensions.Constants.DateTimeFomat), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("TitleEnglish", row["TitleEnglish"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("Images", row["Images"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("IsBlock", row["IsBlock"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("IsClip", row["IsClip"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("IsTrailer", row["IsTrailer"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("IsFilm", row["IsFilm"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("IsShow", row["IsShow"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("ViewCount", row["ViewCount"].ToString(), Field.Store.YES, Field.Index.ANALYZED));
                        var keyword = Utilities.GetCharUnsigned(row["Title"].ToString());
                        var keyworden = Utilities.GetCharUnsigned(row["TitleEnglish"].ToString());
                        document.Add(new Field("Keyword", keyword, Field.Store.YES, Field.Index.ANALYZED));
                        document.Add(new Field("KeywordEN", keyworden, Field.Store.YES, Field.Index.ANALYZED));

                        writer.AddDocument(document);
                    }

                    return true;
                }
                catch
                {
                    return false;
                }
                finally
                {
                    analyzer.Close();
                    writer.Close();
                    writer.Dispose();
                }
            }
        }

        public bool AddUpdateLuceneIndex(List<SearchInfo> listData)
        {
            var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
            using (var writer = new IndexWriter(_directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED))
            {
                try
                {
                    foreach (var sampleData in listData)
                    {
                        AddToLuceneIndex(sampleData, writer);
                    }

                    return true;
                }
                catch
                {
                    return false;
                }
                finally
                {
                    analyzer.Close();
                    writer.Close();
                    writer.Dispose();
                }
            }
        }

        public bool UpdateLuceneIndex(SearchInfo dataObject)
        {
            var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
            using (var writer = new IndexWriter(_directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED))
            {
                try
                {
                    writer.DeleteAll();
                    var doc = CreateDoc(dataObject);
                    writer.UpdateDocument(new Term("Id", dataObject.Id.ToString()), doc);
                    return true;
                }
                catch
                {
                    return false;
                }
                finally
                {
                    analyzer.Close();
                    writer.Close();
                    writer.Dispose();
                }
            }
        }

        public bool AddUpdateLuceneIndex(SearchInfo data)
        {
            return AddUpdateLuceneIndex(new List<SearchInfo> { data });
        }

        private void AddToLuceneIndex(SearchInfo dataObject, IndexWriter writer)
        {
            var searchQuery = new TermQuery(new Term("Id", dataObject.Id.ToString()));
            writer.DeleteDocuments(searchQuery);
            var doc = CreateDoc(dataObject);
            writer.AddDocument(doc);
        }

        private Document CreateDoc(SearchInfo row)
        {
            var doc = new Document();
            doc.Add(new Field("Id", row.Id.ToString(), Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("LanguageCode", row.LanguageCode, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("SiteId", row.SiteId.ToString(), Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("CategoryIds", row.CategoryIds, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("CategoryNames", row.CategoryNames, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("Type", row.Type.ToString(), Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("SearchId", row.SearchId, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("Title", row.Title, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("Alias", row.Alias, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("Sumary", row.Sumary, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("Tags", row.Tags, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("CreateDate", row.CreateDate.ToString(Extensions.Constants.DateTimeFomat), Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("TitleEnglish", row.TitleEnglish, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("Images", row.Images, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("IsBlock", row.IsBlock.ToString(), Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("IsClip", row.IsClip.ToString(), Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("IsTrailer", row.IsTrailer.ToString(), Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("IsFilm", row.IsFilm.ToString(), Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("IsShow", row.IsShow.ToString(), Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("ViewCount", row.ViewCount, Field.Store.YES, Field.Index.ANALYZED));
            var keyword = Utilities.GetCharUnsigned(row.Title);
            var keyworden = Utilities.GetCharUnsigned(row.TitleEnglish);
            doc.Add(new Field("Keyword", keyword, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("KeywordEN", keyworden, Field.Store.YES, Field.Index.ANALYZED));

            return doc;
        }

        public bool ClearLuceneIndex()
        {
            try
            {
                var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
                using (var writer = new IndexWriter(_directory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED))
                {
                    writer.DeleteAll();
                    analyzer.Close();
                    writer.Close();
                    writer.Dispose();
                }
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        public void Optimize()
        {
            var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
            using (var writer = new IndexWriter(_directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED))
            {
                analyzer.Close();
                writer.Optimize();
                writer.Close();
                writer.Dispose();
            }
        }

        public List<SearchInfo> Search(List<SearchCondition> conditions, int pgIndex, int pgSize, ref int nResult)
        {
            return Search(conditions, false, pgIndex, pgSize, ref nResult);
        }

        public List<SearchInfo> Search(SearchCondition condition, int pgIndex, int pgSize, ref int nResult)
        {
            return Search(new List<SearchCondition> { condition }, pgIndex, pgSize, ref nResult);
        }

        public List<SearchInfo> Search(List<SearchCondition> conditions, bool haveKeyword, int pgIndex, int pgSize, ref int nResult)
        {
            if (conditions == null || conditions.Count == 0)
            {
                throw new ArgumentNullException("searchTerms");
            }
            try
            {
                var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
                var directory = FSDirectory.Open(new DirectoryInfo(_luceneDir));
                if (!IndexReader.IndexExists(directory))
                {
                    return null;
                }

                var mainQuery = new BooleanQuery();
                foreach (var pair in conditions)
                {
                    string searchQuery = pair.Keyword;
                    if (string.IsNullOrEmpty(searchQuery.Replace("*", "").Replace("?", "")))
                    {
                        searchQuery = searchQuery.Replace("*", "").Replace("?", "");
                    }

                    for (int i = 0; i < pair.SearchField.Length; i++)
                    {
                        var query = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, pair.SearchField[i], analyzer).Parse(searchQuery);
                        mainQuery.Add(query, BooleanClause.Occur.SHOULD);
                    }
                }

                var searcher = new IndexSearcher(directory, true);
                try
                {
                    int endItem = pgIndex * pgSize;
                    int startItem = (pgIndex - 1) * pgSize;
                    var hits = searcher.Search(mainQuery, null, endItem, haveKeyword ? Sort.RELEVANCE : new Sort(CreateSort()));
                    nResult = hits.TotalHits;
                    return LuceneToDataList(hits.ScoreDocs.Skip(startItem).Take(pgSize), searcher).ToList();
                }
                finally
                {
                    searcher.Close();
                    analyzer.Close();
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }

        public List<SearchInfo> Search(SearchCondition condition, bool haveKeyword, int pgIndex, int pgSize, ref int nResult)
        {
            return Search(new List<SearchCondition>() { condition }, haveKeyword, pgIndex, pgSize, ref nResult);
        }

        private SortField[] CreateSort()
        {
            var sortFields = new List<SortField>();
            sortFields.Add(new SortField(SearchField.Id.ToString(), SortField.LONG, true));
            sortFields.Add(new SortField(SearchField.SiteId.ToString(), SortField.INT, true));
            sortFields.Add(new SortField(SearchField.CategoryIds.ToString(), SortField.STRING, true));
            sortFields.Add(new SortField(SearchField.CategoryNames.ToString(), SortField.STRING, false));
            sortFields.Add(new SortField(SearchField.Type.ToString(), SortField.INT, true));
            sortFields.Add(new SortField(SearchField.SearchId.ToString(), SortField.STRING, false));
            sortFields.Add(new SortField(SearchField.Title.ToString(), SortField.STRING, false));
            sortFields.Add(new SortField(SearchField.Alias.ToString(), SortField.STRING, false));
            sortFields.Add(new SortField(SearchField.Sumary.ToString(), SortField.STRING, false));
            sortFields.Add(new SortField(SearchField.Tags.ToString(), SortField.STRING, false));
            sortFields.Add(new SortField(SearchField.TitleEnglish.ToString(), SortField.STRING, false));
            sortFields.Add(new SortField(SearchField.IsClip.ToString(), SortField.STRING, false));
            sortFields.Add(new SortField(SearchField.IsFilm.ToString(), SortField.STRING, false));
            sortFields.Add(new SortField(SearchField.IsTrailer.ToString(), SortField.STRING, false));
            sortFields.Add(new SortField(SearchField.IsShow.ToString(), SortField.STRING, false));
            sortFields.Add(new SortField(SearchField.Keyword.ToString(), SortField.STRING, false));
            sortFields.Add(new SortField(SearchField.KeywordEN.ToString(), SortField.STRING, false));

            return sortFields.ToArray();
        }

        public int Count(SearchCondition condition)
        {
            return Count(new List<SearchCondition>() {condition});
        }

        public int Count(List<SearchCondition> conditions)
        {
            if (conditions == null || conditions.Count == 0)
                throw new ArgumentNullException("searchTerms");

            var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
            var directory = FSDirectory.Open(new DirectoryInfo(_luceneDir));
            if (!IndexReader.IndexExists(directory))
            {
                return 0;
            }

            var mainQuery = new BooleanQuery();
            foreach (var pair in conditions)
            {
                string searchQuery = pair.Keyword;
                if (string.IsNullOrEmpty(searchQuery.Replace("*", "").Replace("?", "")))
                {
                    searchQuery = searchQuery.Replace("*", "").Replace("?", "");
                }

                for (int i = 0; i < pair.SearchField.Length; i++)
                {
                    var query = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, pair.SearchField[i], analyzer).Parse(searchQuery);
                    mainQuery.Add(query, BooleanClause.Occur.MUST);
                }
            }
            var searcher = new IndexSearcher(directory, true);
            try
            {
                return searcher.Search(mainQuery, 1).TotalHits;
            }
            finally
            {
                searcher.Close();
                analyzer.Close();
            }
        }

        private static IEnumerable<SearchInfo> LuceneToDataList(IEnumerable<ScoreDoc> hits, IndexSearcher searcher)
        {
            return hits.Select(hit => LuceneDocumentToData(searcher.Doc(hit.doc))).ToList();
        }

        private static SearchInfo LuceneDocumentToData(Document doc)
        {
            try
            {
                DateTime createDate = DateTime.ParseExact(doc.Get("CreateDate"), 
                    Extensions.Constants.DateTimeFomat,
                    System.Globalization.CultureInfo.InvariantCulture);
                var item = new SearchInfo
                {
                    Id = int.Parse(doc.Get("Id")),
                    LanguageCode = doc.Get("LanguageCode"),
                    SiteId = int.Parse(doc.Get("SiteId")),
                    CategoryIds = doc.Get("CategoryIds"),
                    CategoryNames = doc.Get("CategoryNames"),
                    Type = int.Parse(doc.Get("Type")),
                    SearchId = doc.Get("SearchId"),
                    Title = doc.Get("Title"),
                    Alias = doc.Get("Alias"),
                    Sumary = doc.Get("Sumary"),
                    Tags = doc.Get("Tags"),
                    CreateDate = createDate,
                    TitleEnglish = doc.Get("TitleEnglish"),
                    Images = doc.Get("Images"),
                    IsBlock = bool.Parse(doc.Get("IsBlock")),
                    IsClip = bool.Parse(doc.Get("IsClip")),
                    IsTrailer = bool.Parse(doc.Get("IsTrailer")),
                    IsFilm = bool.Parse(doc.Get("IsFilm")),
                    IsShow = bool.Parse(doc.Get("IsShow")),
                    ViewCount = doc.Get("ViewCount")
                };

                return item;
            }
            catch (Exception)
            {
                return new SearchInfo();
            }
        }
    }
}<file_sep>﻿using System.ComponentModel;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class TagInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("Name")]
        public string Name { get; set; }

        [DataMember]
        [DisplayName("Alias")]
        public string Alias { get; set; }

        [DataMember]
        [DisplayName("IsDisplay")]
        public bool IsDisplay { get; set; }
    }

    public class TagMap : EntityTypeConfiguration<TagInfo>, IEntityTypeConfiguration
    {
        public TagMap()
        {
            ToTable("Modules_Tags");
            HasKey(x => x.Id);
            Property(x => x.Alias).HasMaxLength(250).IsRequired();
            Property(x => x.Name).IsRequired().HasMaxLength(250);
            Property(x => x.IsDisplay).IsRequired();
        }
    }
}<file_sep>﻿using System;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class FilmFilesModel
    {
        public FilmFilesModel()
        {
            FileCode = Guid.NewGuid().ToString().Replace("-", string.Empty);
        }

        [ControlHidden]
        public long Id { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.ServerId + "').empty();")]
        public string LanguageCode { get; set; }

        [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public int SiteId { get; set; }

        [ControlCascadingDropDown(LabelText = "Máy chủ", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public int ServerId { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Mã file", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public string FileCode { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Tên videos", PlaceHolder = "Tối đa 250 ký tự", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol9, ContainerRowIndex = 1)]
        public string Name { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Thư mục gốc", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)]
        public string FolderName { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn thư mục", MaxLength = 300, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)]
        public string FolderPath { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Tên file", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)]
        public string FileName { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Đôi mở rộng", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)]
        public string Extentions { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn đầy đủ", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)]
        public string FullPath { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Kích thước", MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)]
        public string Size { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "Đang sử dụng", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)]
        public bool HasUse { get; set; }

        public static implicit operator FilmFilesModel(FilmFilesInfo entity)
        {
            return new FilmFilesModel
            {
                Id = entity.Id,
                LanguageCode = entity.LanguageCode,
                Name = entity.Name,
                SiteId = entity.SiteId,
                FolderName = entity.FolderName,
                FolderPath = entity.FolderPath,
                FileName = entity.FileName,
                Extentions = entity.Extentions,
                FullPath = entity.FullPath,
                Size = entity.Size,
                HasUse = entity.HasUse
            };
        }
    }
}
<file_sep>﻿using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface ISmsMessageService : IGenericService<SmsMessageInfo, int>, IDependency
    {

    }

    public class SmsMessageService : GenericService<SmsMessageInfo, int>, ISmsMessageService
    {
        public SmsMessageService(IRepository<SmsMessageInfo, int> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }
    }
}<file_sep>using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{ 
    public interface IActorService : IGenericService<ActorInfo, int>, IDependency
    {
        bool CheckExist(int id, string keyword);

        List<ActorInfo> SearchPaged(
            string searchText,
            int status,
            int pageIndex,
            int pageSize,
            out int totalRecord);
    }

    public class ActorService : GenericService<ActorInfo, int>, IActorService
    {
        public ActorService(IRepository<ActorInfo, int> repository, IEventBus eventBus)
            : base(repository, eventBus)
        {

        }

        public bool CheckExist(int id, string keyword)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Id", id),
                AddInputParameter("@Keyword", keyword)
            };
            var result = (int)ExecuteReaderResult("sp_Actors_CheckName", list.ToArray());

            return result > 0;
        }

        public List<ActorInfo> SearchPaged(string searchText, int status,int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Keyword", searchText),
                AddInputParameter("@Status", status),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<ActorInfo>("sp_Actors_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }
    }
}
<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class SiteModel
    {
        public SiteModel()
        {
            IsActived = true;
        }

        [ControlHidden]
        public int Id { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public string LanguageCode { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Sử dụng", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public bool IsActived { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Tên trang web", PlaceHolder = "Tối đa 250 ký tự", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)]
        public string Name { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn", PlaceHolder = "Tối đa 250 ký tự", MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 2)]
        public string Url { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Tên miền", PlaceHolder = "Tối đa 50 ký tự", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)]
        public string Domain { get; set; }

        [ControlText(LabelText = "Mô tả", PlaceHolder = "Tối đa 2000 ký tự", Type = ControlText.MultiText, Rows = 2, MaxLength = 2000, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 4)]
        public string Description { get; set; }

        public static implicit operator SiteModel(SiteInfo entity)
        {
            return new SiteModel
            {
                Id = entity.Id,
                LanguageCode = entity.LanguageCode,
                Name = entity.Name,
                Url = entity.Url,
                Domain = entity.Domain,
                IsActived = entity.IsActived,
                Description = entity.Description
            };
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminFilmVideosController : BaseAdminController
    {
        public AdminFilmVideosController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {

        }

        [Url("admin/films/select-videos")]
        public ActionResult Index()
        {
            var id = int.Parse(Request.QueryString["id"]);
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý phim"), Url = Url.Action("Index", "AdminFilm") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin phim"), Url = Url.Action("Edit", "AdminFilm", new { id }) });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Chọn video hoặc trailer cho phim"), Url = "#" });
            
            var returnUrl = Request.QueryString[Extensions.Constants.ReturnUrl];
            var model = new FilmVideoModel { FilmId = id, ReturnUrl = returnUrl };
            var result = new ControlFormResult<FilmVideoModel>(model)
            {
                Title = T("Chọn video hoặc trailer cho phim"),
                UpdateActionName = "Update",
                FormMethod = FormMethod.Post,
                SubmitButtonText = T("Lưu lại"),
                ShowBoxHeader = false,
                CancelButtonText = T("Trở về"),
                CancelButtonUrl = "javascript: backUrl();",
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml,
                SetJavascript = GetUrl()
            };

            result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages());
            result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage"));
            result.RegisterCascadingDropDownDataSource(x => x.ServerId, Url.Action("GetServersBySite"));
            result.RegisterCascadingDropDownDataSource(x => x.RootFolders, Url.Action("GetRootFolders"));
            result.RegisterCascadingDropDownDataSource(x => x.FolderDay, Url.Action("GetDayFolders"));
            result.RegisterCascadingDropDownDataSource(x => x.ChildrenFolders, Url.Action("GetChildrenFolders"));
            result.RegisterCascadingDropDownDataSource(x => x.FileIds, Url.Action("GetFilesByFolder"));
            result.RegisterExternalDataSource(x => x.EpisodeIds, y => BindEpisodes());

            var result2 = new ControlGridFormResult<FilmVideoInfo>
            {
                Title = T("Danh sách phim và trailer"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetFilmVideos,
                DefaultPageSize = WorkContext.DefaultPageSize,
                EnablePaginate = true,
                UpdateActionName = "Update",
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml,
                ClientId = TableName,
                ActionsColumnWidth = 100
            };

            result2.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(60);
            result2.AddColumn(x => x.FileName, T("Tên video"));
            result2.AddColumn(x => x.EpisodeName, T("Tập phim"));
            result2.AddColumn(x => x.FullPath, T("Đường dẫn"));
            result2.AddColumn(x => x.IsTraller)
               .HasHeaderText(T("Traller"))
               .AlignCenter()
               .HasWidth(100)
               .RenderAsStatusImage();
            result2.AddColumn(x => x.IsActived)
               .HasHeaderText(T("Sử dụng"))
               .AlignCenter()
               .HasWidth(100)
               .RenderAsStatusImage();

            result2.AddRowAction(true)
                .HasText(T("Xóa"))
                .HasName("Delete")
                .HasValue(x => x.Id)
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result2.AddCustomVar(Extensions.Constants.Id, id);
            result2.AddReloadEvent("DELETE_ENTITY_COMPLETE");

            return new ControlFormsResult(result, result2);
        }

        private string GetUrl()
        {
            var pageIndex = 1;
            if (Session[Extensions.Constants.PageIndex] != null)
            {
                pageIndex = int.Parse(Session[Extensions.Constants.PageIndex].ToString());
            }

            Session[Extensions.Constants.BackPageIndex] = "BACKPAGE";
            var returnUrl = Request.QueryString[Extensions.Constants.ReturnUrl];
            var url = Url.Action("Index", "AdminFilm");
            var sb = new StringBuilder();
            sb.Append("<script type=\"text/javascript\">");
            sb.Append("function backUrl() {");
            sb.AppendFormat("window.location = '{0}?{1}={2}&{3}={4}';", url, Extensions.Constants.ReturnUrl, returnUrl, Extensions.Constants.PageIndex, pageIndex);
            sb.Append("}");
            sb.Append("</script>");
            return sb.ToString();
        }

        private IEnumerable<SelectListItem> BindEpisodes()
        {
            var service = WorkContext.Resolve<IEpisodesService>();
            var items = service.GetAll(WorkContext.CurrentCulture, 0, (int)Status.Approved);
            var result = new List<SelectListItem>();
            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.EpisodeName,
                Value = item.Id.ToString()
            }));

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/select-videos/update")]
        public ActionResult Update(FilmVideoModel model)
        {
            if (!ModelState.IsValid)
            {
                return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var service = WorkContext.Resolve<IFilmVideoService>();
            var service2 = WorkContext.Resolve<IFilmFilesService>();
            var service3 = WorkContext.Resolve<IFilmService>();
            var film = service3.GetById(model.FilmId);
            if (model.Subtitle == null)
            {
                return new AjaxResult().Alert(T("Bạn chưa nhập Subtitle."));
            }
            var listSub = model.Subtitle.Split(',');
            if (listSub.Length != model.EpisodeIds.Length)
            {
                return new AjaxResult().Alert(T("Kiểm tra lại số lượng Subtitle so với số tập phim."));
            }

            var index = 0;
            if (model.FileIds != null && model.FileIds.Length > 0)
            {
                if (listSub.Length != model.FileIds.Length)
                {
                    return new AjaxResult().Alert(T("Kiểm tra lại số lượng Subtitle so với số phim."));
                }

                var server = WorkContext.Resolve<IFilmServersService>().GetById(model.ServerId);
                foreach (var fileId in model.FileIds)
                {
                    var item = service.GetByFilmFile(model.FilmId, fileId) ?? new FilmVideoInfo();
                    var file = service2.GetById(fileId);
                    if (file != null)
                    {
                        item.FileId = file.Id;
                        item.FullPath = file.FullPath;
                        item.BaseUrl = file.FullPath;
                        item.StreamingUrl = string.Format(Extensions.Constants.StreamingUrl, server.ServerIP, file.FolderPath + "/" + file.FileName);
                    }
                    item.FilmId = model.FilmId;
                    item.EpisodeId = model.EpisodeIds[index];
                    item.IsTraller = model.IsTraller;
                    item.IsActived = model.IsActived;
                    item.ImageIcon = film.ImageIcon;
                    item.Subtitle = listSub[index];
                    item.UrlAlbum = string.Empty;
                    
                    service.Save(item);

                    #region Update name
                    if (file != null)
                    {
                        file.Name = film.FilmName;
                        file.HasUse = true;
                        service2.Update(file);
                    }
                    #endregion

                    index++;
                }
            }
            else
            {
                var listFilms = model.UrlSource.Split(',');
                if (listSub.Length != listFilms.Length)
                {
                    return new AjaxResult().Alert(T("Kiểm tra lại số lượng Subtitle so với số url phim."));
                }

                foreach (var url in listFilms)
                {
                    var item = new FilmVideoInfo
                    {
                        FilmId = model.FilmId,
                        EpisodeId = model.EpisodeIds[index],
                        IsTraller = model.IsTraller,
                        IsActived = model.IsActived,
                        ImageIcon = film.ImageIcon,
                        UrlSource = url,
                        Subtitle = listSub[index],
                        FullPath = url,
                        BaseUrl = url,
                        StreamingUrl = url,
                        UrlAlbum = model.UrlAlbum
                    };

                    service.Save(item);
                    index++;
                }
            }

            var redirectUrl = string.Format("{0}?id={1}", Url.Action("Index", "AdminFilmVideos"), film.Id); 
            if (!string.IsNullOrEmpty(model.ReturnUrl))
            {
                redirectUrl = string.Format("{0}?id={1}&{2}={3}", Url.Action("Index", "AdminFilmVideos"), film.Id, Extensions.Constants.ReturnUrl, model.ReturnUrl);  
            }

            return new AjaxResult()
                .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"))
                .Redirect(redirectUrl);
        }

        [Url("admin/film-files/get-files-by-folders")]
        public ActionResult GetFilesByFolder()
        {
            var folderPath = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ChildrenFolders]))
            {
                folderPath = Request.Form[Extensions.Constants.ChildrenFolders];
            }

            var service = WorkContext.Resolve<IFilmVideoService>();
            var items = new List<SelectListItem>();
            var listFiles = service.GetFilesByFile(folderPath);
            if (listFiles != null && listFiles.Count > 0)
            {
                items.AddRange(listFiles.Select(item => new SelectListItem
                {
                    Text = item.FullPath,
                    Value = item.Id.ToString()
                }));
            }

            return Json(items);
        }

        [Url("admin/film-files/get-day-folders")]
        public ActionResult GetDayFolders()
        {
            var folderName = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.RootFolders]))
            {
                folderName = Request.Form[Extensions.Constants.RootFolders];
            }

            var service = WorkContext.Resolve<IFilmFilesService>();
            var items = new List<SelectListItem>();
            var listFolders = service.GetDayFolderByRoot(folderName);
            if (listFolders != null && listFolders.Count > 0)
            {
                items.AddRange(listFolders.Select(item => new SelectListItem
                {
                    Text = item.FolderDay,
                    Value = item.FolderDay
                }));
            }

            return Json(items);
        }

        [Url("admin/film-files/get-children-folders")]
        public ActionResult GetChildrenFolders()
        {
            var folderName = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FolderDay]))
            {
                folderName = Request.Form[Extensions.Constants.FolderDay];
            }

            var service = WorkContext.Resolve<IFilmFilesService>();
            var items = new List<SelectListItem>();
            var listFolders = service.GetChildrenByRootFolders(folderName);
            if (listFolders != null && listFolders.Count > 0)
            {
                items.AddRange(listFolders.Select(item => new SelectListItem
                {
                    Text = item.FolderPath,
                    Value = item.FolderPath
                }));
            }

            return Json(items);
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<IFilmVideoService>();
            var item = service.GetById(id);
            if (item.FileId > 0)
            {
                var fileService = WorkContext.Resolve<IFilmFilesService>();
                var file = fileService.GetById(item.FileId);
                if (file != null)
                {
                    file.HasUse = false;
                    file.Name = string.Empty;
                    fileService.Update(file); 
                }
            }
            service.Delete(item);

            return new AjaxResult().NotifyMessage("DELETE_ENTITY_COMPLETE");
        }

        private ControlGridAjaxData<FilmVideoInfo> GetFilmVideos(ControlGridFormRequest options)
        {
            var filmId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.Id]))
            {
                filmId = Convert.ToInt32(Request.Form[Extensions.Constants.Id]);
            }

            var totals = 0;
            var items = WorkContext.Resolve<IFilmVideoService>().GetByFilm(filmId, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<FilmVideoInfo>(items, totals);

            return result;
        }
    }
}
<file_sep>﻿using System;
using System.Web.Mvc;
using CMSSolutions.ContentManagement.Widgets.Services;
using CMSSolutions.DisplayManagement;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Themes;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;
using Microsoft.Web.WebPages.OAuth;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = false)]
    public class HomeController : BaseHomeController
    {
        private readonly dynamic shapeFactory;
        public HomeController(IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory) 
            : base(workContextAccessor)
        {
            this.shapeFactory = shapeFactory;
        }

        [Url("", Priority = 10)]
        public ActionResult Index()
        {
            UrlLogin = Url.Action("Index", "Home");
            if (IsLogin)
            {
                var customerService = WorkContext.Resolve<ICustomerService>();
                CustomerInfo customer = customerService.GetCustomerByCacheId(UserId);
                SetCustomerState(customer);
            }

            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;
            if (WorkContext.DomainName == Extensions.Constants.JJDomainName)
            {
                SiteId = (int)Site.JJHome;
                serviceCategory.SiteId = (int)Site.JJHome;
                var jjHome = serviceCategory.GetHomePage();
                ViewData[Extensions.Constants.HeaderTitle] = jjHome.Name;
                ViewData[Extensions.Constants.HeaderDescription] = jjHome.Description;
                ViewData[Extensions.Constants.HeaderKeywords] = jjHome.Tags;
                ViewBag.ReturnUrl = "";

                return View("JJIndex", OAuthWebSecurity.RegisteredClientData);
            }

            SiteId = (int)Site.Home;
            serviceCategory.SiteId = (int)Site.Home;
            var home = serviceCategory.GetHomePage();
            ViewData[Extensions.Constants.HeaderTitle] = home.Name;
            ViewData[Extensions.Constants.HeaderDescription] = home.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = home.Tags;

            BuildModules();

            return View("Index", OAuthWebSecurity.RegisteredClientData);
        }

        public override void BuildModules()
        {
            var widget = WorkContext.Resolve<IWidgetService>();
            var viewRenderer = new ViewRenderer { Context = ControllerContext };
            if (!IsVip)
            {
                #region BannerPageLeft
                var bannerPageLeft = widget.GetWidget(HomeWidgets.BannerPageLeft.ToString());
                if (bannerPageLeft != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageLeft;
                    WorkContext.Layout.AdBannerPageLeft(widgetShape);
                }
                #endregion

                #region BannerPageCenter
                var bannerPageCenter = widget.GetWidget(HomeWidgets.BannerPageCenter.ToString());
                if (bannerPageCenter != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageCenter;
                    WorkContext.Layout.AdBannerPageCenter(widgetShape);
                }
                #endregion

                #region BannerPageRight
                var bannerPageRight = widget.GetWidget(HomeWidgets.BannerPageRight.ToString());
                if (bannerPageRight != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageRight;
                    WorkContext.Layout.AdBannerPageRight(widgetShape);
                }
                #endregion

                #region BannerContentLeftFirst
                var bannerContentLeftFirst = widget.GetWidget(HomeWidgets.BannerContentLeftFirst.ToString());
                if (bannerContentLeftFirst != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerContentLeftFirst;
                    WorkContext.Layout.AdBannerContentLeftFirst(widgetShape);
                }
                #endregion

                #region BannerContentLeftSecond
                var bannerContentLeftSecond = widget.GetWidget(HomeWidgets.BannerContentLeftSecond.ToString());
                if (bannerContentLeftSecond != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerContentLeftSecond;
                    WorkContext.Layout.AdBannerContentLeftSecond(widgetShape);
                }
                #endregion

                #region BannerContentLeftThird
                var bannerContentLeftThird = widget.GetWidget(HomeWidgets.BannerContentLeftThird.ToString());
                if (bannerContentLeftThird != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerContentLeftThird;
                    WorkContext.Layout.AdBannerContentLeftThird(widgetShape);
                }
                #endregion

                #region BannerContentLeftFourth
                var bannerContentLeftFourth = widget.GetWidget(HomeWidgets.BannerContentLeftFourth.ToString());
                if (bannerContentLeftFourth != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerContentLeftFourth;
                    WorkContext.Layout.AdBannerContentLeftFourth(widgetShape);
                }
                #endregion

                #region BannerContentLeftFifth
                var bannerContentLeftFifth = widget.GetWidget(HomeWidgets.BannerContentLeftFifth.ToString());
                if (bannerContentLeftFifth != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerContentLeftFifth;
                    WorkContext.Layout.AdBannerContentLeftFifth(widgetShape);
                }
                #endregion

                #region BannerContentLeftSixth
                var bannerContentLeftSixth = widget.GetWidget(HomeWidgets.BannerContentLeftSixth.ToString());
                if (bannerContentLeftSixth != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerContentLeftSixth;
                    WorkContext.Layout.AdBannerContentLeftSixth(widgetShape);
                }
                #endregion

                #region BannerContentLeftSeventh
                var bannerContentLeftSeventh = widget.GetWidget(HomeWidgets.BannerContentLeftSeventh.ToString());
                if (bannerContentLeftSeventh != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerContentLeftSeventh;
                    WorkContext.Layout.AdBannerContentLeftSeventh(widgetShape);
                }
                #endregion

                #region BannerRightFirst
                var bannerRightFirst = widget.GetWidget(HomeWidgets.BannerRightFirst.ToString());
                if (bannerRightFirst != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerRightFirst;
                    WorkContext.Layout.AdBannerRightFirst(widgetShape);
                }
                #endregion

                #region BannerRightSecond
                var bannerRightSecond = widget.GetWidget(HomeWidgets.BannerRightSecond.ToString());
                if (bannerRightSecond != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerRightSecond;
                    WorkContext.Layout.AdBannerRightSecond(widgetShape);
                }
                #endregion

                #region BannerRightSixth
                var bannerRightSixth = widget.GetWidget(HomeWidgets.BannerRightSixth.ToString());
                if (bannerRightSixth != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerRightSixth;
                    WorkContext.Layout.AdBannerRightSixth(widgetShape);
                }
                #endregion

                #region BannerRightThird
                var bannerRightThird = widget.GetWidget(HomeWidgets.BannerRightThird.ToString());
                if (bannerRightThird != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerRightThird;
                    WorkContext.Layout.AdBannerRightThird(widgetShape);
                }
                #endregion

                #region BannerRightFourth
                var bannerRightFourth = widget.GetWidget(HomeWidgets.BannerRightFourth.ToString());
                if (bannerRightFourth != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerRightFourth;
                    WorkContext.Layout.AdBannerRightFourth(widgetShape);
                }
                #endregion
            }
            else
            {
                #region BannerPageLeftVip
                var bannerPageLeftVip = widget.GetWidget(HomeWidgets.BannerPageLeftVip.ToString());
                if (bannerPageLeftVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageLeftVip;
                    WorkContext.Layout.AdBannerPageLeftVip(widgetShape);
                }
                #endregion

                #region BannerPageCenterVip
                var bannerPageCenterVip = widget.GetWidget(HomeWidgets.BannerPageCenterVip.ToString());
                if (bannerPageCenterVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageCenterVip;
                    WorkContext.Layout.AdBannerPageCenterVip(widgetShape);
                }
                #endregion

                #region BannerPageRightVip
                var bannerPageRightVip = widget.GetWidget(HomeWidgets.BannerPageRightVip.ToString());
                if (bannerPageRightVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageRightVip;
                    WorkContext.Layout.AdBannerPageRightVip(widgetShape);
                }
                #endregion
            }
            #region HomeSliderBanner

            var modelSlider = new DataViewerModel {Data = BuildSlider(SiteId, (int) SliderPages.Home)};
            var viewSlider = viewRenderer.RenderPartialView(Extensions.Constants.SliderBannerFilePath, modelSlider);
            WorkContext.Layout.SliderBanner.Add(new MvcHtmlString(viewSlider));

            var viewRegisterResource = viewRenderer.RenderPartialView(Extensions.Constants.RegisterResourceFilePath, null);
            WorkContext.Layout.RegisterResource.Add(new MvcHtmlString(viewRegisterResource));
            #endregion

            #region HomeFooterLogoInformation
            var homeFooterLogoInformation = widget.GetWidget(HomeWidgets.HomeFooterLogoInformation.ToString());
            if (homeFooterLogoInformation != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = homeFooterLogoInformation;
                WorkContext.Layout.FooterLogoInformation(widgetShape);
            }
            #endregion

            #region HomeFacebookFanpage
            var homeFacebookFanpage = widget.GetWidget(HomeWidgets.HomeFacebookFanpage.ToString());
            if (homeFacebookFanpage != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = homeFacebookFanpage;
                WorkContext.Layout.AdFacebookFanpage(widgetShape);
            }
            #endregion

            #region SocialNetwork
            var socialNetwork = widget.GetWidget(HomeWidgets.DisplaySocialNetwork.ToString());
            if (socialNetwork != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = socialNetwork;
                WorkContext.Layout.DisplaySocialNetwork(widgetShape);
            }
            #endregion

            #region News
            var viewNews = viewRenderer.RenderPartialView(Extensions.Constants.NewsViewFilePath, null);
            WorkContext.Layout.DisplayNews.Add(new MvcHtmlString(viewNews));
            #endregion

            #region Tags
            var serviceTags = WorkContext.Resolve<ITagService>();
            var modelTags = new TagViewModel { ListTags = serviceTags.GetDisplayTags() };
            var viewTags = viewRenderer.RenderPartialView(Extensions.Constants.TagViewFilePath, modelTags);
            WorkContext.Layout.DisplayTags.Add(new MvcHtmlString(viewTags));
            #endregion

            #region CategoryContentFirst
            var modelFirst = new DataViewCategoryModel
            {
                Type = (int)HomeDisplayFilmType.FilmHot,
                Title = "Sự kiện: Phim Đang HOT",
                TextNext = "Còn nữa ››",
                UrlNext = Url.Action("FilmHot", "HomeCategory"),
                SliderName = "FilmFirst"
            };
            modelFirst.HtmlFilmHot = GetFilmHtml(modelFirst.Type);
            var viewFilmFirst = viewRenderer.RenderPartialView(Extensions.Constants.CategoryContentFirstViewFilePath, modelFirst);
            WorkContext.Layout.CategoryContentLeftFirst.Add(new MvcHtmlString(viewFilmFirst));
            #endregion

            #region CategoryContentSecond
            var modelSecond = new DataViewCategoryModel
            {
                Type = (int)HomeDisplayFilmType.FilmRetail,
                Title = "Phim lẻ mới up",
                TextNext = "Tất Tần Tật ››",
                UrlNext = Url.Action("Index", "HomeCategory", new { @alias = "phim-le", @id = 2 }),
                SliderName = "FilmSecond"
            };
            modelSecond.HtmlFilmRetail = GetFilmHtml(modelSecond.Type);
            var viewFilmSecond = viewRenderer.RenderPartialView(Extensions.Constants.CategoryContentSecondViewFilePath, modelSecond);
            WorkContext.Layout.CategoryContentLeftSecond.Add(new MvcHtmlString(viewFilmSecond));
            #endregion

            #region CategoryContentThird
            var modelThird = new DataViewCategoryModel
            {
                Type = (int)HomeDisplayFilmType.FilmLengthEpisodes,
                Title = "Phim bộ mới up",
                TextNext = "Tất Tần Tật ››",
                UrlNext = Url.Action("Index", "HomeCategory", new { @alias = "phim-bo", @id = 3 }),
                SliderName = "FilmThird"
            };
            modelThird.HtmlFilmLengthEpisodes = GetFilmHtml(modelThird.Type);
            var viewFilmThird = viewRenderer.RenderPartialView(Extensions.Constants.CategoryContentThirdViewFilePath, modelThird);
            WorkContext.Layout.CategoryContentLeftThird.Add(new MvcHtmlString(viewFilmThird));
            #endregion

            #region CategoryContentFourth
            var modelFourth = new DataViewCategoryModel
            {
                Type = (int)HomeDisplayFilmType.FilmJJChannelIntroduce,
                Title = "JJ Channel giới thiệu",
                TextNext = "Tất Tần Tật ››",
                UrlNext = Url.Action("Index", "HomeJJChannel", new { @alias = "jj-channel-viphd", @id = 9 }),
                SliderName = "FilmFourth"
            };
            modelFourth.HtmlFilmJJChannelIntroduce = GetFilmHtml(modelFourth.Type);
            var viewFilmFourth = viewRenderer.RenderPartialView(Extensions.Constants.CategoryContentFourthViewFilePath, modelFourth);
            WorkContext.Layout.CategoryContentLeftFourth.Add(new MvcHtmlString(viewFilmFourth));
            #endregion

            #region CategoryContentFifth
            var modelFifth = new DataViewCategoryModel
            {
                Type = (int)HomeDisplayFilmType.FilmTheater,
                Title = "Phim chiếu rạp",
                TextNext = "Tất Tần Tật ››",
                UrlNext = Url.Action("Index", "HomeTheater"),
                SliderName = "FilmFifth"
            };
            modelFifth.HtmlFilmTheater = GetFilmHtml(modelFifth.Type);
            var viewFilmFifth = viewRenderer.RenderPartialView(Extensions.Constants.CategoryContentFifthViewFilePath, modelFifth);
            WorkContext.Layout.CategoryContentLeftFifth.Add(new MvcHtmlString(viewFilmFifth));
            #endregion

            #region CategoryContentSixth
            var modelSixth = new DataViewCategoryModel
            {
                Type = (int)HomeDisplayFilmType.TVShow,
                Title = "TV Show",
                TextNext = "Tất Tần Tật ››",
                UrlNext = Url.Action("Index", "HomeShow", new { @alias = "shows", @id = 4 }),
                SliderName = "TVShows"
            };
            modelSixth.HtmlTVShow = GetFilmHtml(modelSixth.Type);
            var viewFilmSixth = viewRenderer.RenderPartialView(Extensions.Constants.CategoryContentSixthViewFilePath, modelSixth);
            WorkContext.Layout.CategoryContentLeftSixth.Add(new MvcHtmlString(viewFilmSixth));
            #endregion

            #region CategoryContentSeventh
            var modelSeventh = new DataViewCategoryModel
            {
                Type = (int)HomeDisplayFilmType.Clip,
                Title = "Clip",
                TextNext = "Tất Tần Tật ››",
                UrlNext = Url.Action("Index", "HomeClip", new { @alias = "clip-hay", @id = 5 }),
                SliderName = "Clip"
            };
            modelSeventh.HtmlClip = GetFilmHtml(modelSeventh.Type);
            var viewFilmSeventh = viewRenderer.RenderPartialView(Extensions.Constants.CategoryContentSeventhViewFilePath, modelSeventh);
            WorkContext.Layout.CategoryContentLeftSeventh.Add(new MvcHtmlString(viewFilmSeventh));
            #endregion

            #region DisplayStatistic1
            var modelStatistic1 = new DataViewCategoryModel
            {
                Type = (int)HomeDisplayFilmType.StatisticalFilmRetail,
                Title = "PHIM LẺ XEM NHIỀU NHẤT"
            };
            var viewStatistic1 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic1FilePath, modelStatistic1);
            WorkContext.Layout.DisplayStatistic1.Add(new MvcHtmlString(viewStatistic1));
            #endregion

            #region DisplayStatistic2
            var modelStatistic2 = new DataViewCategoryModel
            {
                Type = (int)HomeDisplayFilmType.StatisticalLengthEpisodes,
                Title = "PHIM BỘ XEM NHIỀU NHẤT"
            };
            var viewStatistic2 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic2FilePath, modelStatistic2);
            WorkContext.Layout.DisplayStatistic2.Add(new MvcHtmlString(viewStatistic2));
            #endregion
        }
    }
}
<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class RateModel
    {
        [ControlHidden]
        public long Id { get; set; }

        [ControlText(Type = ControlText.TextBox, MaxLength = 250, LabelText = "Tên phim", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 0)]
        public string FilmName { get; set; }

        [ControlNumeric(LabelText = "Đánh giá", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public int Rate { get; set; }

        [ControlText(Type = ControlText.TextBox, MaxLength = 50, LabelText = "Mã khách hàng", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public string CustomerCode { get; set; }

        [ControlText(Type = ControlText.TextBox, MaxLength = 250, LabelText = "Họ và Tên", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public string CustomerName { get; set; }

        [ControlText(Type = ControlText.TextBox, MaxLength = 250, LabelText = "Thông báo giật lag", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 2)]
        public string AlertLag { get; set; }

        [ControlText(Type = ControlText.TextBox, MaxLength = 250, LabelText = "Thông báo lỗi", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)]
        public string AlertError { get; set; }

        [ControlText(Type = ControlText.MultiText, Rows = 2, MaxLength = 2000, LabelText = "Nội dung thông báo lỗi", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 4)]
        public string Messages { get; set; }
        
        public static implicit operator RateModel(RateInfo entity)
        {
            return new RateModel
            {
                Id = entity.Id,
                FilmName = entity.FilmName,
                Rate = entity.Rate,
                CustomerCode = entity.CustomerCode,
                CustomerName = entity.CustomerName,
                AlertError = entity.AlertError,
                AlertLag = entity.AlertLag,
                Messages = entity.Messages
            };
        }

    }
}
<file_sep>﻿using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web.Mvc;
using CMSSolutions.Extensions;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;
using GemBox.Spreadsheet;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminCustomerController : BaseAdminController
    {
        public AdminCustomerController(IWorkContextAccessor workContextAccessor) : 
                base(workContextAccessor)
        {
            TableName = "tblCustomers";
        }
        
        [Url("admin/customers")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý khách hàng"), Url = "#" });

            var result = new ControlGridFormResult<CustomerInfo>
            {
                Title = T("Quản lý khách hàng"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetCustomers,
                DefaultPageSize = WorkContext.DefaultPageSize,
                EnablePaginate = true,
                UpdateActionName = "Update",
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml,
                ClientId = TableName,
                ActionsColumnWidth = 200
            };

            result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true);
            result.AddCustomVar(Extensions.Constants.FilmTypesId, "$('#" + Extensions.Constants.FilmTypesId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.CountryId, "$('#" + Extensions.Constants.CountryId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.FromDate, "$('#" + Extensions.Constants.FromDate + "').val();", true);
            result.AddCustomVar(Extensions.Constants.ToDate, "$('#" + Extensions.Constants.ToDate + "').val();", true);

            result.AddColumn(x => x.CustomerCode, T("Mã KH")).HasWidth(100).AlignCenter();
            result.AddColumn(x => x.FullName, T("<NAME>"));
            result.AddColumn(x => x.Email, T("Email"));
            result.AddColumn(x => x.VipXu, T("VIP Xu"));
            result.AddColumn(x => x.TotalDay, T("Tổng ngày"));
            result.AddColumn(x => x.TextStartDate, T("Từ ngày"));
            result.AddColumn(x => x.TextEndDate, T("Đến ngày"));

            result.AddAction().HasText(T("Thêm mới"))
              .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
              .HasButtonStyle(ButtonStyle.Primary)
              .HasCssClass(Constants.RowLeft);

            result.AddAction().HasText(T("Xuất danh sách KH"))
                .HasUrl(Url.Action("ExportExcel"))
                .HasButtonStyle(ButtonStyle.Info)
                .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildFilmTypes)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildCountries)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildFromDate())).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildToDate())).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction(true)
                .HasText(T("Kích hoạt"))
                .HasName("SetActived")
                .HasValue(x => x.Id)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .HasButtonStyle(ButtonStyle.Success)
                .EnableWhen(x => x.IsBlock);

            result.AddRowAction()
                 .HasText(T("Sửa"))
                 .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                 .HasButtonStyle(ButtonStyle.Default)
                 .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddRowAction()
                 .HasText(T("Lịch sử"))
                 .HasUrl(x => Url.Action("History", RouteData.Values.Merge(new { id = x.Id })))
                 .HasButtonStyle(ButtonStyle.Warning)
                 .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");

            return result;
        }

        private ControlGridAjaxData<CustomerInfo> GetCustomers(ControlGridFormRequest options)
        {
            var searchText = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText]))
            {
                searchText = Request.Form[Extensions.Constants.SearchText];
            }

            var fromDate = DateTime.Now.Date;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FromDate]))
            {
                fromDate = DateTime.ParseExact(Request.Form[Extensions.Constants.FromDate], "dd/MM/yyyy", CultureInfo.InvariantCulture);
            }

            var toDate = DateTime.Now.Date;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ToDate]))
            {
                toDate = DateTime.ParseExact(Request.Form[Extensions.Constants.ToDate], "dd/MM/yyyy", CultureInfo.InvariantCulture);
            }

            var filmTypesId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FilmTypesId]))
            {
                filmTypesId = Convert.ToInt32(Request.Form[Extensions.Constants.FilmTypesId]);
            }

            var countryId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.CountryId]))
            {
                countryId = Convert.ToInt32(Request.Form[Extensions.Constants.CountryId]);
            }

            var status = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId]))
            {
                status = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]);
            }

            int totals;
            var service = WorkContext.Resolve<ICustomerService>();
            var records = service.SearchPaged(
                searchText, 
                filmTypesId, countryId, fromDate,
                toDate, -1, status, options.PageIndex, options.PageSize,
                out totals);

            return new ControlGridAjaxData<CustomerInfo>(records, totals);
        }

        [ActionName("Update")]
        [HttpPost, FormButton("SetActived")]
        public ActionResult SetDefault(int id)
        {
            var service = WorkContext.Resolve<ICustomerService>();
            var item = service.GetById(id);
            item.IsBlock = false;
            service.Update(item);

            return new AjaxResult()
                .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Đã kích hoạt tài khoản " + item.UserName));
        }
        
        [Url("admin/customers/history")]
        public ActionResult History(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý khách hàng"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Lịch sử khách hàng"), Url = "#" });
            TableName = "tblHistories";

            var result = new ControlGridFormResult<CustomerHistoriesInfo>
            {
                Title = T("Lịch sử khách hàng"),
                CssClass = "table table-bordered table-striped",
                FetchAjaxSource = (x => GetHistories(id, x)),
                ActionsColumnWidth = 100,
                EnablePaginate = true,
                DefaultPageSize = 50,
                ClientId = TableName,
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml
            };

            result.AddCustomVar(Extensions.Constants.FromDate, "$('#" + Extensions.Constants.FromDate + "').val();", true);
            result.AddCustomVar(Extensions.Constants.ToDate, "$('#" + Extensions.Constants.ToDate + "').val();", true);
            result.AddCustomVar(Extensions.Constants.TypeSearch, "$('#" + Extensions.Constants.TypeSearch + "').val();", true);
            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true);

            result.AddColumn(x => x.TransactionCode, T("Mã giao dịch"));
            result.AddColumn(x => x.Action, T("Hành động"));
            result.AddColumn(x => x.TextCreateDate, T("Ngày thực hiện"));
            result.AddColumn(x => x.Description, T("Nội dung thực hiện"));
            result.AddColumn(x => EnumExtensions.GetDisplayName((CustomerLogType)x.Type), T("Loại log"));

            result.AddAction().HasText(T("Trở về"))
               .HasUrl(Url.Action("Index"))
               .HasButtonStyle(ButtonStyle.Danger)
               .HasBoxButton(false)
               .HasCssClass(Constants.RowLeft)
               .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(() => BuildFromDate(false))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildToDate(false))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildTypes)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3);

            return result;
        }

        private string BuildTypes()
        {
            var list = EnumExtensions.GetListItems<CustomerLogType>();
            var sb = new StringBuilder();
            sb.AppendFormat(T("Loại log") + " <select id=\"" + Extensions.Constants.TypeSearch + "\" name=\"" + Extensions.Constants.TypeSearch + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var status in list)
            {
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        private ControlGridAjaxData<CustomerHistoriesInfo> GetHistories(int id, ControlGridFormRequest options)
        {
            var fromDate = Utilities.DateNull();
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FromDate]))
            {
                fromDate = DateTime.ParseExact(Request.Form[Extensions.Constants.FromDate], "dd/MM/yyyy", CultureInfo.InvariantCulture);
            }

            var toDate = Utilities.DateNull();
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ToDate]))
            {
                toDate = DateTime.ParseExact(Request.Form[Extensions.Constants.ToDate], "dd/MM/yyyy", CultureInfo.InvariantCulture);
            }

            var type = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.TypeSearch]))
            {
                type = Convert.ToInt32(Request.Form[Extensions.Constants.TypeSearch]);
            }

            var status = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId]))
            {
                status = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]);
            }

            int totals;
            var service = WorkContext.Resolve<ICustomerHistoriesService>();
            var items = service.GetPaged(id, fromDate ,toDate, type, status, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<CustomerHistoriesInfo>(items, totals);

            return result;
        }

        [Url("admin/customers/edit/{id}")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý khách hàng"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin khách hàng"), Url = "#" });

            var service = WorkContext.Resolve<ICustomerService>();
            var model = new CustomerModel();
            if (id > 0)
            {
                model = service.GetById(id);
            }
            else
            {
                model.CutomerCode = service.GetLatestCustomerCode();
            }

            var result = new ControlFormResult<CustomerModel>(model)
            {
                Title = T("Thông tin khách hàng"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                ShowCancelButton = false,
                ShowBoxHeader = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };
            result.RegisterFileUploadOptions("ImageIcon.FileName", new ControlFileUploadOptions
            {
                AllowedExtensions = "jpg,jpeg,png,gif"
            });

            result.MakeReadOnlyProperty(x => x.CutomerCode);
            result.MakeReadOnlyProperty(x => x.StartDate);
            result.MakeReadOnlyProperty(x => x.EndDate);
            result.MakeReadOnlyProperty(x => x.TotalDay);
            result.MakeReadOnlyProperty(x => x.TotalMoney);
            if (id > 0)
            {
                result.MakeReadOnlyProperty(x => x.UserName);
                result.MakeReadOnlyProperty(x => x.Password); 
            }

            result.RegisterExternalDataSource(x => x.Sex, y => BindSex());
            result.RegisterExternalDataSource(x => x.CityId, y => BindCities());
            result.RegisterExternalDataSource(x => x.FilmTypeIds, y => BindFilmTypes());
            result.RegisterExternalDataSource(x => x.CountryIds, y => BindCountries());
            result.RegisterExternalDataSource(x => x.Status, y => BindStatus());

            result.AddAction().HasText(T("Lịch sử"))
               .HasUrl(Url.Action("History", new {@id = id}))
               .HasButtonStyle(ButtonStyle.Warning);

            result.AddAction().HasText(T("Trở về"))
               .HasUrl(Url.Action("Index"))
               .HasButtonStyle(ButtonStyle.Danger);

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/customers/update")]
        public ActionResult Update(CustomerModel model)
        {
            var service = WorkContext.Resolve<ICustomerService>();
            CustomerInfo item = model.Id == 0 ? new CustomerInfo() : service.GetById(model.Id);

            item.CustomerCode = model.CutomerCode;
            if (model.Id == 0)
            {
                item.CustomerCode = service.GetLatestCustomerCode();
            }
            
            item.FullName = model.FullName;
            item.Email = model.Email;
            item.Address = model.Address;
            item.PhoneNumber = model.PhoneNumber;
            item.CityId = model.CityId;
            item.Birthday = model.Birthday;
            item.Sex = model.Sex;
            item.ImageIcon = model.ImageIcon;
            item.FilmTypeIds = Utilities.ParseString(model.FilmTypeIds);
            item.CountryIds = Utilities.ParseString(model.CountryIds);
            item.MemberDate = DateTime.Now.Date;
            item.Skype = model.Skype;
            item.ZingMe = model.ZingMe;
            item.Facebook = model.Facebook;
            item.Google = model.Google;
            item.Yahoo = model.Yahoo;
            item.VipXu = model.VipXu;
            item.TotalMoney = model.TotalMoney;
            item.Status = model.Status;
            item.IsBlock = model.IsBlock;
            item.Description = model.Description;
            service.Save(item);

            return new AjaxResult()
                .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"));
        }

        [Url("admin/customers/export-excel")]
        public ActionResult ExportExcel()
        {
            var ef = new ExcelFile();
            string fileName = Server.MapPath("/Media/Default/ExcelTemplate/DuLieuKhachHang.xls");
            ef.LoadXls(fileName, XlsOptions.PreserveAll);
            byte[] fileContents;
            ExcelWorksheet ws = ef.Worksheets[0];
            var data = WorkContext.Resolve<ICustomerService>().ExportExcel();
            if (data != null && data.Count > 0)
            {
                int index = 1;
                foreach (var item in data)
                {
                    ws.Cells[index, 0].Value = index;
                    ws.Cells[index, 1].Value = item.CustomerCode;
                    ws.Cells[index, 2].Value = item.FullName;
                    ws.Cells[index, 3].Value = item.MemberDate.ToString(Extensions.Constants.DateTimeFomatFull);
                    ws.Cells[index, 4].Value = item.Email;
                    ws.Cells[index, 5].Value = item.PhoneNumber;
                    ws.Cells[index, 6].Value = (int)item.VipXu;
                    ws.Cells[index, 7].Value = item.TotalDay;
                    ws.Cells[index, 8].Value = item.TextStartDate;
                    ws.Cells[index, 9].Value = item.TextEndDate;
                    index++;
                    ws.Rows[index].InsertCopy(1, ws.Rows[1]);
                }

                ws.Rows[index].Delete();
            }

            using (var stream = new MemoryStream())
            {
                ef.SaveXls(stream);

                fileContents = stream.ToArray();
            }

            return File(fileContents, "application/vnd.ms-excel");
        }
    }
}
<file_sep>﻿using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using CMSSolutions.Caching;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface ICategoryService : ICacheService<CategoryInfo, int>, IGenericService<CategoryInfo, int>, IDependency
    {
        bool CheckAlias(int id, string alias);

        string LanguageCode { get; set; }

        int SiteId { get; set; }

        CategoryInfo GetByIdCache(int id);

        CategoryInfo GetHomePage();

        string GetCategoryName(int id);

        IList<CategoryInfo> GetPaged(bool isDeleted, int pageIndex, int pageSize, out int totals);

        IList<CategoryInfo> ResetCache();

        CategoryInfo GetByAlias(string alias);

        List<CategoryInfo> GetChildenByParentId(int parentId);

        List<CategoryInfo> GetAllParent();

        IList<CategoryInfo> GetAllCache();

        List<CategoryInfo> GetTree();
    }

    public class CategoryService : GenericService<CategoryInfo, int>, ICategoryService
    {
        private readonly ICacheInfo cacheManager;

        public string LanguageCode { get; set; }

        public int SiteId { get; set; }

        public CategoryService(
            IRepository<CategoryInfo, int> repository, 
            IEventBus eventBus,
            ICacheInfo cacheManager)
            : base(repository, eventBus)
        {
            this.cacheManager = cacheManager;
        }

        public override void Insert(CategoryInfo record)
        {
            Repository.Insert(record);
            ResetCache();
        }

        public override void Update(CategoryInfo record)
        {
            Repository.Update(record);
            ResetCache();
        }

        public override void Delete(CategoryInfo record)
        {
            Repository.Delete(record);
            ResetCache();
        }

        public override void Save(CategoryInfo record)
        {
            if (record.IsTransient())
            {
                Insert(record);
            }
            else
            {
                Update(record);
            }

            ResetCache();
        }

        public CategoryInfo GetHomePage()
        {
            var list = GetAllCache();
            if (list != null && list.Count > 0)
            {
                return list.FirstOrDefault(x => x.IsHome && x.IsActived);
            }

            return null;
        }

        public string GetCategoryName(int id)
        {
            var list = GetAllCache();
            if (list != null && list.Count > 0)
            {
                return list.Where(x => x.Id == id && !x.IsActived).Select(x => x.Name).FirstOrDefault();
            }

            return string.Empty;
        }

        public bool CheckAlias(int id, string alias)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Alias", alias),
                AddInputParameter("@Id", id)
            };

            var result = (int)ExecuteReaderResult("sp_Categories_CheckAlias", list.ToArray());
            return result > 0;
        }

        public CategoryInfo GetByAlias(string alias)
        {
            var list = GetAllCache();
            if (list != null && list.Count > 0)
            {
                return list.FirstOrDefault(x => x.Alias.ToLower() == alias.ToLower() && x.IsActived);
            }

            return null;
        }

        public List<CategoryInfo> GetTree()
        {
            var listParent = GetAllParent();
            var list = new List<CategoryInfo>();
            if (listParent != null)
            {
                foreach (var parent in listParent)
                {
                    parent.ChildenName = parent.ShortName;
                    parent.HasChilden = true;
                    list.Add(parent);
                    list.AddRange(GetChildenByParentId(parent.Id));
                }
            }

            return list;
        }
       
        public List<CategoryInfo> GetChildenByParentId(int parentId)
        {
            var list = GetAllCache();
            var results = new List<CategoryInfo>();
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    if (parentId > 0 && item.ParentId == parentId && item.IsActived)
                    {
                        item.HasChilden = false;
                        item.ChildenName = "--- " + item.ShortName;
                        results.Add(item);
                        results.AddRange(GetChildenByParentId2(item.Id));
                    }
                }

                return results;
            }

            return null;
        }

        public List<CategoryInfo> GetChildenByParentId2(int parentId)
        {
            var list = GetAllCache();
            var results = new List<CategoryInfo>();
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    if (parentId > 0 && item.ParentId == parentId && item.IsActived)
                    {
                        item.HasChilden = false;
                        item.ChildenName = "--- --- " + item.ShortName;
                        results.Add(item);
                    }
                }

                results.Sort((foo1, foo2) => foo1.OrderBy.CompareTo(foo2.OrderBy));

                return results;
            }

            return null;
        }

        public List<CategoryInfo> GetAllParent()
        {
            var list = GetAllCache();
            if (list != null && list.Count > 0)
            {
                return list.Where(x => x.ParentId == 0 && x.IsActived).ToList();
            }

            return null;
        }

        public CategoryInfo GetByIdCache(int id)
        {
            var list = GetAllCache();
            if (list != null && list.Count > 0)
            {
                return list.FirstOrDefault(x => x.Id == id && x.IsActived);
            }

            return null;
        }

        public IList<CategoryInfo> GetAllCache()
        {
            var results = cacheManager.Get(string.Format(Extensions.Constants.CacheKeys.CATEGORY_ALL_TABLE, LanguageCode, SiteId));
            if (results == null)
            {
                results = ResetCache();
            }

            var list = (List<CategoryInfo>) results;
            if (results != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    foreach (var check in list)
                    {
                        if (check.Id == item.ParentId)
                        {
                            item.ParentName = check.ShortName;
                            break;
                        }
                    }
                }

                return list;
            }

            return new List<CategoryInfo>();
        }

        public IList<CategoryInfo> GetPaged(bool isDeleted, int pageIndex, int pageSize, out int totals)
        {
            var results = GetAllCache();
            if (results != null)
            {
                var list = results.Where(y => y.IsDeleted == isDeleted);
                totals = list.Count();
                var users = (from x in list select x).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

                return users;
            }

            totals = 0;
            return new List<CategoryInfo>();
        }

        public IList<CategoryInfo> ResetCache()
        {
            cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.CATEGORY_ALL_TABLE, LanguageCode, SiteId));
            var table = Repository.Table.Where(x => x.LanguageCode == LanguageCode && x.SiteId == SiteId).ToList();
            cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.CATEGORY_ALL_TABLE, LanguageCode, SiteId), table);

            return table;
        }
    }
}
<file_sep>﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CMSSolutions.Configuration;
using CMSSolutions.ContentManagement.Widgets.Services;
using CMSSolutions.DisplayManagement;
using CMSSolutions.Security.Cryptography;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Themes;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = false)]
    public class HomeCustomerController : BaseHomeController
    {
        private readonly dynamic shapeFactory;
        public HomeCustomerController(IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory) 
            : base(workContextAccessor)
        {
            this.shapeFactory = shapeFactory;
        }

        private void BuildModules()
        {
            var widget = WorkContext.Resolve<IWidgetService>();
            var viewRenderer = new ViewRenderer { Context = ControllerContext };

            #region Customer
            var customerService = WorkContext.Resolve<ICustomerService>();
            var customer = customerService.GetById(UserId);
            var viewCustomer = viewRenderer.RenderPartialView(Extensions.Constants.CustomerViewFilePath, customer);
            WorkContext.Layout.AdBannerRightFirst.Add(new MvcHtmlString(viewCustomer));
            #endregion

            #region SocialNetwork
            var socialNetwork = widget.GetWidget(HomeWidgets.DisplaySocialNetwork.ToString());
            if (socialNetwork != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = socialNetwork;
                WorkContext.Layout.DisplaySocialNetwork(widgetShape);
            }
            #endregion
        }

        [Url("nguoi-dung/thong-bao")]
        public ActionResult UserMessages()
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;

            SiteId = (int)Site.Home;
            var category = serviceCategory.GetById((int)FixCategories.NapVIP);
            ViewData[Extensions.Constants.HeaderTitle] = category.Name;
            ViewData[Extensions.Constants.HeaderDescription] = category.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = category.Tags;

            BuildModules();

            return View("UserMessages");
        }

        [Url("nguoi-dung/phim-ua-thich")]
        public ActionResult UserHistories1()
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;

            SiteId = (int)Site.Home;
            var category = serviceCategory.GetById((int)FixCategories.NapVIP);
            ViewData[Extensions.Constants.HeaderTitle] = category.Name;
            ViewData[Extensions.Constants.HeaderDescription] = category.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = category.Tags;

            BuildModules();

            return View("UserHistories1");
        }

        [Url("nguoi-dung/phim-da-xem")]
        public ActionResult UserHistories2()
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;

            SiteId = (int)Site.Home;
            var category = serviceCategory.GetById((int)FixCategories.NapVIP);
            ViewData[Extensions.Constants.HeaderTitle] = category.Name;
            ViewData[Extensions.Constants.HeaderDescription] = category.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = category.Tags;

            BuildModules();

            return View("UserHistories2");
        }

        [Url("nguoi-dung/phim-dang-xem")]
        public ActionResult UserHistories3()
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;

            SiteId = (int)Site.Home;
            var category = serviceCategory.GetById((int)FixCategories.NapVIP);
            ViewData[Extensions.Constants.HeaderTitle] = category.Name;
            ViewData[Extensions.Constants.HeaderDescription] = category.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = category.Tags;

            BuildModules();

            return View("UserHistories3");
        }

        [Url("nguoi-dung/sua-thong-tin")]
        public ActionResult UserProfile()
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;

            SiteId = (int)Site.Home;
            var category = serviceCategory.GetById((int)FixCategories.NapVIP);
            ViewData[Extensions.Constants.HeaderTitle] = category.Name;
            ViewData[Extensions.Constants.HeaderDescription] = category.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = category.Tags;

            BuildModules();

            var customerService = WorkContext.Resolve<ICustomerService>();
            var cityService = WorkContext.Resolve<ICityService>();
            var countryService = WorkContext.Resolve<ICountryService>();
            var filmTypesService = WorkContext.Resolve<IFilmTypesService>();

            var customer = customerService.GetById(UserId);
            var model = new DataViewerModel
            {
                Customer = customer,
                ListCities = cityService.GetRecords(x => x.Status == (int) Status.Approved).ToList(),
                ListCountries = countryService.GetRecords().ToList()
            };
            model.ListFilmTypes = filmTypesService.GetByType(WorkContext.CurrentCulture,SiteId, 1).ToList();
            model.ListDay = Utilities.GetListDay();
            model.ListMonth = Utilities.GetListMonth();
            model.ListYear = Utilities.GetListYear();

            return View("CustomerProfile", model);
        }

        [HttpPost]
        [Url("nguoi-dung/cap-nhat")]
        public ActionResult UserUpdate()
        {
            var redirect = new DataViewerModel();

            var fullName = Request.Form["txtFullName"];
            var email = Request.Form["txtEmail"];
            var address = Request.Form["txtAddress"];
            var city = Request.Form["ddlCity"];
            var phoneNumber = Request.Form["txtPhoneNumber"];
            var day = Request.Form["ddlDay"];
            var month = Request.Form["ddlMonth"];
            var year = Request.Form["ddlYear"];
            var gender = Request.Form["radGender"];
            var password = Request.Form["txtPassword"];
            var captcha = Request.Form["txtCaptcha"];
            var selectFilmTypes = Request.Form["selectFilmTypes[]"];
            var selectCountries = Request.Form["selectCountries[]"];
            var imgImageIcon = Request.Form["imgImageIcon"];

            if (string.IsNullOrEmpty(email))
            {
                redirect.Data = "E-mail không để trống.";
                redirect.Status = false;
                return Json(redirect);
            }

            if (string.IsNullOrEmpty(city) || city == "0")
            {
                redirect.Data = "Vui lòng chọn Tỉnh/Thành.";
                redirect.Status = false;
                return Json(redirect);
            }

            if (string.IsNullOrEmpty(day) || day == "0")
            {
                redirect.Data = "Vui lòng chọn Ngày sinh của bạn.";
                redirect.Status = false;
                return Json(redirect);
            }

            if (string.IsNullOrEmpty(month) || month == "0")
            {
                redirect.Data = "Vui lòng chọn Tháng sinh của bạn.";
                redirect.Status = false;
                return Json(redirect);
            }

            if (string.IsNullOrEmpty(year) || year == "0")
            {
                redirect.Data = "Vui lòng chọn Năm sinh của bạn.";
                redirect.Status = false;
                return Json(redirect);
            }

            if (string.IsNullOrEmpty(selectFilmTypes))
            {
                redirect.Data = "Bạn phải chọn thể loại phim.";
                redirect.Status = false;
                return Json(redirect);
            }

            if (string.IsNullOrEmpty(selectCountries))
            {
                redirect.Data = "Bạn phải chọn quốc gia.";
                redirect.Status = false;
                return Json(redirect);
            }

            HttpPostedFileBase uploadfile = Request.Files[0];
            if (uploadfile == null && string.IsNullOrEmpty(imgImageIcon))
            {
                redirect.Status = false;
                redirect.Data = "Bạn chưa chọn ảnh đại diện.";
                return Json(redirect);
            }

            if (string.IsNullOrEmpty(captcha) || captcha.ToUpper() != GlobalCapcha.ToUpper())
            {
                redirect.Status = false;
                redirect.Data = "Mã xác thực không đúng.";
                return Json(redirect);
            }

            var customerService = WorkContext.Resolve<ICustomerService>();
            var customer = customerService.GetById(UserId);
            if (customer.Password != EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, Utilities.RemoveInjection(password)))
            {
                redirect.Status = false;
                redirect.Data = "Mật khẩu không đúng bạn không thể cập nhật thông tin cá nhân cho tài khoản này.";
                return Json(redirect);
            }

            var imageUrl = customer.ImageIcon;
            if (string.IsNullOrEmpty(customer.ImageIcon) || uploadfile == null || string.IsNullOrEmpty(uploadfile.FileName))
            {
                imageUrl = "/Images/avatars/avatar-no-image.png";
            }
            else
            {
                imageUrl = "/Media/Default/Customers/" + DateTime.Now.ToString("dd-MM-yyyy") + uploadfile.FileName;
            }
            var ngaySinh = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day));
            var fullUrl = Server.MapPath("~/Media/Default/Customers/" + DateTime.Now.ToString("dd-MM-yyyy") + uploadfile.FileName);
            uploadfile.SaveAs(fullUrl);

            customer.FullName = fullName;
            customer.Email = email;
            customer.Address = address;
            customer.Birthday = ngaySinh;
            customer.CityId = city;
            customer.PhoneNumber = phoneNumber;
            customer.Sex = int.Parse(gender);
            customer.FilmTypeIds = selectFilmTypes;
            customer.CountryIds = selectCountries;
            customer.ImageIcon = imageUrl;
            customerService.Update(customer);
            redirect.Data = "Đã cập nhật thông tin tài khoản thành công.";
            redirect.Status = true;
            redirect.Url = Url.Action("UserProfile", "HomeCustomer");

            return Json(redirect);
        }

        [HttpPost, ValidateInput(false)]
        [Url("nguoi-dung/quen-mat-khau")]
        public ActionResult UserForgotPassword()
        {
            var redirect = new DataViewerModel();
            return Json(redirect);
        }

        [Url("nguoi-dung/doi-mat-khau")]
        public ActionResult UserChangePassword()
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;

            SiteId = (int)Site.Home;
            var category = serviceCategory.GetById((int)FixCategories.NapVIP);
            ViewData[Extensions.Constants.HeaderTitle] = category.Name;
            ViewData[Extensions.Constants.HeaderDescription] = category.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = category.Tags;

            BuildModules();

            return View("UserChangePassword");
        }

        [HttpPost, ValidateInput(false)]
        [Url("nguoi-dung/doi-mat-khau/cap-nhat")]
        public ActionResult UpdateChangePassword()
        {
            var redirect = new DataViewerModel();
            if (!IsLogin)
            {
                redirect.Data = "Bạn chưa đăng nhập.";
                redirect.Status = false;
                return Json(redirect);
            }

            var passwordOld = Request.Form["txtPasswordOld"];
            var passwordNew = Request.Form["txtPasswordNew"];
            var passwordConfirm = Request.Form["<PASSWORD>"];
            var captcha = Request.Form["txtCaptcha"];
            if (string.IsNullOrEmpty(captcha) || captcha.ToUpper() != GlobalCapcha.ToUpper())
            {
                redirect.Status = false;
                redirect.Data = "Mã xác thực không đúng.";
                return Json(redirect);
            }

            if (string.IsNullOrEmpty(passwordOld))
            {
                redirect.Status = false;
                redirect.Data = "Mật khẩu cũ không để trống.";
                return Json(redirect);
            }

            if (string.IsNullOrEmpty(passwordNew))
            {
                redirect.Status = false;
                redirect.Data = "Mật khẩu mới không để trống.";
                return Json(redirect);
            }

            if (passwordNew.Length <= 5)
            {
                redirect.Status = false;
                redirect.Data = "Mật khẩu mới độ dài tối đa 6 ký tự.";
                return Json(redirect);
            }

            if (passwordNew != passwordConfirm)
            {
                redirect.Status = false;
                redirect.Data = "Mật khẩu xác nhận không đúng.";
                return Json(redirect);
            }

            var service = WorkContext.Resolve<ICustomerService>();
            var status = service.ChangePassword(Utilities.RemoveInjection(UserName),
                EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, Utilities.RemoveInjection(passwordOld)), 
                EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, Utilities.RemoveInjection(passwordNew)));
            if (status != 0)
            {
                redirect.Status = true;
                redirect.Data = "Mật khẩu của bạn đã được đổi thành công.";
                var customerService = WorkContext.Resolve<ICustomerService>();
                var customer = customerService.GetById(UserId);
                SetCustomerState(customer);
            }
            else
            {
                redirect.Status = false;
                redirect.Data = "Mật khẩu cũ của bạn không đúng.";
            }

            return Json(redirect);
        }

        [Url("nguoi-dung/upload-videos")]
        public ActionResult UploadVideos()
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;

            SiteId = (int)Site.Home;
            var category = serviceCategory.GetById((int)FixCategories.NapVIP);
            ViewData[Extensions.Constants.HeaderTitle] = category.Name;
            ViewData[Extensions.Constants.HeaderDescription] = category.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = category.Tags;

            BuildModules();
            return View("CustomerUploadVideos");
        }

        [HttpPost, ValidateInput(false)]
        [Url("nguoi-dung/luu-tru-videos")]
        public ActionResult UserSaveVideos()
        {
            var redirect = new DataViewerModel();
            redirect.Data = "Thực hiện thất bại. Chưa hỗ trợ upload videos cho khách hàng.";
            redirect.Status = false;

            return Json(redirect);
        }
    }
}
<file_sep>﻿using System;
using System.Globalization;
using System.Web.Mvc;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminCategoryController : BaseAdminController
    {
        public AdminCategoryController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
            TableName = "tblCategories";
        }

        [Url("admin/category")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý chuyên mục"), Url = "#" });

            var result = new ControlGridFormResult<CategoryInfo>
            {
                Title = T("Quản lý chuyên mục"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetCategories,
                DefaultPageSize = WorkContext.DefaultPageSize,
                EnablePaginate = true,
                UpdateActionName = "Update",
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml,
                ClientId = TableName,
                ActionsColumnWidth = 100
            };

            result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true); 
            result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true);

            result.AddColumn(x => x.Id, T("Mã"))
                .AlignCenter()
                .HasWidth(60);
            result.AddColumn(x => x.ParentName, T("Chuyên mục cha")).HasWidth(150);
            result.AddColumn(x => x.ShortName, T("Chuyên mục")).HasWidth(150);
            result.AddColumn(x => x.Name, "Tên hỗ trợ SEO");
            result.AddColumn(x => x.OrderBy, "Vị trí")
                .AlignCenter()
                .HasWidth(60);
            result.AddColumn(x => x.IsActived)
                .HasHeaderText(T("Hiển thị"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage();

            result.AddAction().HasText(T("Thêm mới"))
                .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
                .HasButtonStyle(ButtonStyle.Primary)
                .HasBoxButton(false)
                .HasRow(false)
                .HasCssClass(Constants.RowLeft)
                .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildSites(false, string.Empty))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
                .HasText(T("Sửa"))
                .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                .HasButtonStyle(ButtonStyle.Default)
                .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddRowAction(true)
                .HasText(T("Xóa"))
                .HasName("Delete")
                .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString()))
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");

            return result;
        }

        private ControlGridAjaxData<CategoryInfo> GetCategories(ControlGridFormRequest options)
        {
            var service = WorkContext.Resolve<ICategoryService>();
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }
            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            bool status = false;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId]))
            {
                var statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]);
                switch ((Status)statusId)
                {
                    case Status.Approved:
                        status = false;
                        break;
                    case Status.Deleted:
                        status = true;
                        break;
                }
            }

            int totals;
            service.LanguageCode = languageCode;
            service.SiteId = siteId;
            var list = service.GetPaged(status, options.PageIndex, options.PageSize, out totals);

            return new ControlGridAjaxData<CategoryInfo>(list, totals);
        }

        [Url("admin/category/edit")]
        public ActionResult Edit(int id)
        {
            var model = new CategoryModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<ICategoryService>();
                model = service.GetById(id); 
            }
            
            var result = new ControlFormResult<CategoryModel>(model)
            {
                Title = T("Thông tin chuyên mục"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                ShowCancelButton = false,
                ShowBoxHeader = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages());
            result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage"));
            result.RegisterCascadingDropDownDataSource(x => x.ParentId, Url.Action("GetCategoriesBySite"));

            result.AddAction().HasText(T("Làm mới"))
                .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
                .HasCssClass("btn btn-success");

            result.AddAction().HasText(T("Trở về"))
               .HasUrl(Url.Action("Index"))
               .HasCssClass("btn btn-danger");

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/category/update")]
        public ActionResult Update(CategoryModel model)
        {
            if (!ModelState.IsValid)
            {
                return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            CategoryInfo categoryInfo;
            var service = WorkContext.Resolve<ICategoryService>();
            service.SiteId = model.SiteId;
            service.LanguageCode = model.LanguageCode;

            var alias = Utilities.GetAlias(model.Name);
            if (!string.IsNullOrEmpty(alias))
            {
                if (service.CheckAlias(model.Id, alias))
                {
                    alias += DateTime.Now.ToString("ddMMyyyyhhmm");
                }
            }

            var url = model.Url;
            if (string.IsNullOrEmpty(url))
            {
                url = alias;
            }

            categoryInfo = model.Id == 0 ? new CategoryInfo() : service.GetById(model.Id);

            categoryInfo.SiteId = model.SiteId;
            categoryInfo.ParentId = model.ParentId;
            categoryInfo.ShortName = model.ShortName;
            categoryInfo.Name = model.Name;
            categoryInfo.Alias = alias;
            categoryInfo.LanguageCode = model.LanguageCode;
            categoryInfo.IsActived = model.IsActived;
            categoryInfo.OrderBy = model.OrderBy;
            categoryInfo.Description = model.Description;
            categoryInfo.SiteId = model.SiteId;
            categoryInfo.CreateDate = DateTime.Now.Date;
            categoryInfo.IsDeleted = model.IsDeleted;
            categoryInfo.Url = url;
            categoryInfo.IsHome = model.IsHome;
            categoryInfo.HasChilden = model.HasChilden;
            categoryInfo.Tags = model.Tags;

            service.Save(categoryInfo);

            try
            {
                #region Add Search
                var service2 = WorkContext.Resolve<ISearchService>();
                var searchObject = service2.GetBySearchId(categoryInfo.Id.ToString(), (int)SearchType.Category);
                long id = 0;
                if (searchObject != null)
                {
                    id = searchObject.Id;
                }

                var search = new SearchInfo
                {
                    Id = id,
                    Title = categoryInfo.ShortName,
                    Alias = categoryInfo.Alias,
                    CategoryIds = categoryInfo.Id.ToString(),
                    CreateDate = categoryInfo.CreateDate,
                    IsBlock = categoryInfo.IsDeleted,
                    LanguageCode = categoryInfo.LanguageCode,
                    SearchId = categoryInfo.Id.ToString(),
                    SiteId = categoryInfo.SiteId,
                    Sumary = categoryInfo.Name,
                    Tags = categoryInfo.Tags,
                    Type = (int)SearchType.Category,
                    TitleEnglish = string.Empty,
                    Images = string.Empty,
                    ViewCount = "0",
                    Processed = 0
                };

                service2.Save(search);

                var cacheSearch = new LuceneService();
                cacheSearch.UpdateLuceneIndex(search);
                #endregion
            }
            catch (Exception)
            {
                return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE")
                    .Alert(T("Không thể thêm dữ liệu tìm kiếm."));
            }

            return new AjaxResult()
                .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"));
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<ICategoryService>();
            var obj = service.GetById(id);
            service.LanguageCode = obj.LanguageCode;
            service.SiteId = obj.SiteId;
            obj.IsDeleted = true;
            service.Update(obj);

            return new AjaxResult().NotifyMessage("DELETE_ENTITY_COMPLETE");
        }
    }
}
<file_sep>﻿using System;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using CMSSolutions.ContentManagement.Widgets.Services;
using CMSSolutions.DisplayManagement;
using CMSSolutions.Extensions;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Themes;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Payments;
using CMSSolutions.Websites.Services;
using CMSSolutions.Websites.VipHDBankCardServices;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = false)]
    public class HomeVipXuController : BaseHomeController
    {
        private readonly dynamic shapeFactory;
        public HomeVipXuController(IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory) 
            : base(workContextAccessor)
        {
            this.shapeFactory = shapeFactory;
        }

        [Url("tai-tro.html")]
        public ActionResult Index()
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            var model = new PaymentModel();
            model.PageName = 1;
            if (!IsLogin)
            {
                return Redirect(Url.Action("Index", "Home"));
            }

            var customerService = WorkContext.Resolve<ICustomerService>();
            CustomerInfo customer = customerService.GetCustomerByCacheId(UserId);
            SetCustomerState(customer);

            #region Payments
            var transid = Request.QueryString["?transid"];
            var responCode = Request.QueryString["responCode"];
            var mac = Request.QueryString["mac"];
            var amount = Request.QueryString["amount"];
            var bankCode = Request.QueryString["bankCode"];

            var encrypter = new DesSecurity();
            var apiBank = new APIBankCardService();
            var transactionBankService = WorkContext.Resolve<ITransactionBankService>();
            var serviceLog = new APISmsService();
            if (mac != encrypter.DESMAC(transid + responCode, apiBank.ReceiverKey) && !String.IsNullOrEmpty(transid))
            {
                model.Messages = "Giao dịch nạp VIPXU qua thẻ ngân hàng thất bại.";
                model.Status = false;
                model.Url = "";
                var transaction = new TransactionBankInfo
                {
                    CustomerCode = CustomerCode,
                    TransactionCode = TransactionCode,
                    CreateDate = DateTime.Now,
                    BankCode = bankCode,
                    Amount = amount,
                    ResponCode = responCode,
                    Mac = mac,
                    TransId = transid,
                    Type = (int)TransferType.Rereceive,
                    Description = "Giao dịch nạp VIPXU qua thẻ ngân hàng thất bại.",
                    Status = (int)PaymentStatus.Close
                };

                transactionBankService.BankProcessing(transaction, 0);
                serviceLog.InsertLog(new LogInfo
                {
                    CreateDate = DateTime.Now,
                    Messages = "Giao dịch nạp VIPXU qua thẻ ngân hàng thất bại.",
                    Keyword = bankCode,
                    Contents = "Mã GD: " + TransactionCode + " - Mã KH: " + CustomerCode + " - Số tiền nạp: " + amount,
                    Type = (int)LogType.BankCard,
                    Status = (int)LogStatus.Error
                });
                TransactionCode = null;
            }

            if (!string.IsNullOrEmpty(transid) && !string.IsNullOrEmpty(responCode) && Convert.ToInt32(responCode) != (int)BankErrorMessages.Success)
            {
                model.Messages = "Giao dịch nạp VIPXU qua thẻ ngân hàng thất bại.";
                model.Status = false;
                model.Url = "";
                var transaction = new TransactionBankInfo
                {
                    CustomerCode = CustomerCode,
                    TransactionCode = TransactionCode,
                    CreateDate = DateTime.Now,
                    BankCode = bankCode,
                    Amount = amount,
                    ResponCode = responCode,
                    Mac = mac,
                    TransId = transid,
                    Type = (int)TransferType.Rereceive,
                    Description = "Giao dịch thất bại",
                    Status = (int)PaymentStatus.Close
                };

                transactionBankService.BankProcessing(transaction, 0);
                serviceLog.InsertLog(new LogInfo
                {
                    CreateDate = DateTime.Now,
                    Messages = "Giao dịch nạp VIPXU qua thẻ ngân hàng thất bại.",
                    Keyword = bankCode,
                    Contents = TransactionCode + " " + CustomerCode + " " + amount,
                    Type = (int)LogType.BankCard,
                    Status = (int)LogStatus.Error
                });

                TransactionCode = null;
            }

            if (!string.IsNullOrEmpty(TransactionCode) && !string.IsNullOrEmpty(transid) && Convert.ToInt32(responCode) == (int)BankErrorMessages.Success)
            {
                var vipXu = TotalVipXu(int.Parse(amount));
                model.Messages = string.Format("Bạn đã nạp {0} VIPXU vào tài khoản {1} thành công.", vipXu, CustomerCode);
                model.Status = true;
                model.Amount = amount;
                model.Url = string.Format("http://{0}", Extensions.Constants.HomeDomainName);

                var transaction = new TransactionBankInfo
                {
                    CustomerCode = CustomerCode,
                    TransactionCode = TransactionCode,
                    CreateDate = DateTime.Now,
                    BankCode = bankCode,
                    Amount = amount,
                    ResponCode = responCode,
                    Mac = mac,
                    TransId = transid,
                    Type = (int)TransferType.Rereceive,
                    Description = string.Format("Đã nạp {0} VIPXU vào tài khoản {1} thành công.", vipXu, CustomerCode),
                    Status = (int)PaymentStatus.Close
                };

                transactionBankService.BankProcessing(transaction, vipXu);
                serviceLog.InsertLog(new LogInfo
                {
                    CreateDate = DateTime.Now,
                    Messages = "Giao dịch nạp VIPXU qua thẻ ngân hàng thành công.",
                    Keyword = bankCode,
                    Contents = TransactionCode + " " + CustomerCode + " " + amount,
                    Type = (int)LogType.BankCard,
                    Status = (int)LogStatus.Success
                });

                TransactionCode = null;
                customerService.ResetCacheCustomers();
                customer = customerService.GetCustomerByCacheId(UserId);
                SetCustomerState(customer);
            }

            #endregion

            #region Init
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;

            SiteId = (int)Site.Home;
            serviceCategory.SiteId = SiteId;
            var cate = serviceCategory.GetByIdCache((int)FixCategories.NapVIP);
            ViewData[Extensions.Constants.HeaderTitle] = cate.Name;
            ViewData[Extensions.Constants.HeaderDescription] = cate.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = cate.Tags;

            BindVipModules();

            var serviceBankCard = WorkContext.Resolve<IBankCardService>();
            model.ListBankCards = serviceBankCard.GetRecords(x => x.Status == (int)Status.Approved).ToList();
            var serviceCard = WorkContext.Resolve<ICardTypeService>();
            model.ListCardTypes = serviceCard.GetRecords(x => x.Status == (int)Status.Approved).ToList();
            model.CustomerCode = CustomerCode;
            #endregion

            return View(model);
        }

        [Url("tai-tro/0/thong-tin.html")]
        public ActionResult VipXuInfo()
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            var model = new PaymentModel();
            model.PageName = 0;
            model.CustomerName = FullName;
            model.VipXu = VipXu.ToString();
            if (!IsLogin)
            {
                model.Messages = "Bạn chưa đăng nhập.";
                model.Status = false;
                return Redirect(Url.Action("Index", "Home"));
            }

            #region Init
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;

            SiteId = (int)Site.Home;
            serviceCategory.SiteId = SiteId;
            var cate = serviceCategory.GetByIdCache((int)FixCategories.NapVIP);
            ViewData[Extensions.Constants.HeaderTitle] = cate.Name;
            ViewData[Extensions.Constants.HeaderDescription] = cate.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = cate.Tags;

            BindVipModules();

            model.CustomerCode = CustomerCode;
            #endregion

            return View(model);
        }

        [Url("tai-tro/2/log-doi-xu.html")]
        public ActionResult LogDoiXu()
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            var model = new PaymentModel();
            model.PageName = 2;
            if (!IsLogin)
            {
                model.Messages = "Bạn chưa đăng nhập.";
                model.Status = false;
                return Redirect(Url.Action("Index", "Home"));
            }

            #region Init
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;

            SiteId = (int)Site.Home;
            serviceCategory.SiteId = SiteId;
            var cate = serviceCategory.GetByIdCache((int)FixCategories.NapVIP);
            ViewData[Extensions.Constants.HeaderTitle] = cate.Name;
            ViewData[Extensions.Constants.HeaderDescription] = cate.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = cate.Tags;

            BindVipModules();

            model.CustomerCode = CustomerCode;
            var historyService = WorkContext.Resolve<ICustomerHistoriesService>();
            model.CustomerDoiXuHistories = historyService.GetDoiXuByCustomer(CustomerCode);
            #endregion

            return View("LogDoiXu", model);
        }

        [Url("tai-tro/3/log-nap-vip.html")]
        public ActionResult LogNapVip()
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            var model = new PaymentModel();
            model.PageName = 3;
            #region Init
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;

            SiteId = (int)Site.Home;
            serviceCategory.SiteId = SiteId;
            var cate = serviceCategory.GetByIdCache((int)FixCategories.NapVIP);
            ViewData[Extensions.Constants.HeaderTitle] = cate.Name;
            ViewData[Extensions.Constants.HeaderDescription] = cate.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = cate.Tags;

            BindVipModules();

            model.CustomerCode = CustomerCode;
            var historyService = WorkContext.Resolve<ICustomerHistoriesService>();
            model.CustomerNapVipHistories = historyService.GetNapVipByCustomer(UserId);
            #endregion

            return View("LogNapVip", model);
        }

        private void BindVipModules()
        {
            var widget = WorkContext.Resolve<IWidgetService>();
            var viewRenderer = new ViewRenderer { Context = ControllerContext };

            #region Customer
            var customerService = WorkContext.Resolve<ICustomerService>();
            var customer = customerService.GetById(UserId);
            if (customer == null)
            {
                customer = new CustomerInfo();
            }
            var viewCustomer = viewRenderer.RenderPartialView(Extensions.Constants.CustomerViewFilePath, customer);
            WorkContext.Layout.AdBannerRightFirst.Add(new MvcHtmlString(viewCustomer));
            #endregion

            #region SocialNetwork
            var socialNetwork = widget.GetWidget(HomeWidgets.DisplaySocialNetwork.ToString());
            if (socialNetwork != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = socialNetwork;
                WorkContext.Layout.DisplaySocialNetwork(widgetShape);
            }
            #endregion
        }

        [HttpPost, ValidateInput(false)]
        [Url("thanh-toan/the-atm")]
        public ActionResult BankPayment()
        {
            var redirect = new DataViewerModel();
            if (!IsLogin)
            {
                redirect.Data = "Bạn chưa đăng nhập.";
                redirect.Status = false;
                return Json(redirect);
            }

            var amount = Request.Form["Amount"];
            var bankCode = Request.Form["BankCode"];
            var captcha = Request.Form["txtCaptcha"];
            if (string.IsNullOrEmpty(captcha) || captcha.ToUpper() != GlobalCapcha.ToUpper())
            {
                redirect.Status = false;
                redirect.Data = "Mã xác thực không đúng.";
                return Json(redirect);
            }

            if (string.IsNullOrEmpty(amount.Trim()))
            {
                redirect.Status = false;
                redirect.Data = "Số tiền không để trống.";
                return Json(redirect);
            }
            
            if (double.Parse(amount) < 50000)
            {
                redirect.Status = false;
                redirect.Data = "Số tiền phải lớn hơn hoặc bằng 50.000VNĐ.";
                return Json(redirect);
            }

            var apiBank = new APIBankCardService();
            apiBank.ReponseUrl = "http://viphd.vn" + Url.Action("Index") + "?amount=" + amount + "&bankCode=" + bankCode + "&";
            //apiBank.ReponseUrl = "http://localhost:1500" + Url.Action("Index") + "?amount=" + amount + "&bankCode=" + bankCode + "&";
            var encrypter = new DesSecurity();

            string stan = "720527";
            string termtxndatetime = DateTime.Now.ToString("yyyyMMddHHmmss");
            string fee = "0";
            string userName = "DuManhTan";
            string IssuerID = "EPAY";
            string tranID = DateTime.Now.ToString("yyyyMMddHHmmss");

            string mac = apiBank.MerchantId + stan + termtxndatetime + amount + fee + userName + IssuerID + tranID + bankCode + apiBank.ReponseUrl;
            mac = encrypter.DESMAC(mac, apiBank.SenderKey);
            var service = new Service();
            var result = service.Deposit(apiBank.MerchantId, stan, termtxndatetime, amount, fee, userName,
                                               IssuerID, tranID,
                                               bankCode, mac,
                                               apiBank.ReponseUrl);
            
            TransactionCode = Utilities.GenerateUniqueNumber();
            var transaction = new TransactionBankInfo
            {
                CustomerCode = CustomerCode,
                TransactionCode = TransactionCode,
                CreateDate = DateTime.Now,
                BankCode = bankCode,
                Amount = amount,
                ResponCode = "",
                Mac = "",
                TransId = "",
                Type = (int) TransferType.Send,
                Description = "",
                Status = (int) PaymentStatus.Open
            };

            var transactionBankService = WorkContext.Resolve<ITransactionBankService>();
            transactionBankService.Insert(transaction);

            var serviceLog = new APISmsService();
            serviceLog.InsertLog(new LogInfo
            {
                CreateDate = DateTime.Now,
                Messages = "Gửi giao dịch nạp thẻ ngân hàng.",
                Keyword = bankCode,
                Contents = TransactionCode + " " + CustomerCode + " " + amount,
                Type = (int)LogType.BankCard,
                Status = (int)LogStatus.Information
            });

            redirect = new DataViewerModel
            {
                Status = true,
                Url = !string.IsNullOrEmpty(result.url) ? result.url : string.Empty
            };

            return Json(redirect);
        }

        [HttpPost, ValidateInput(false)]
        [Url("thanh-toan/the-nap")]
        public ActionResult CardPayment()
        {
            if (string.IsNullOrEmpty(TransactionCode))
            {
                TransactionCode = Utilities.GenerateUniqueNumber();
            }

            var redirect = new DataViewerModel();
            if (!IsLogin)
            {
                redirect.Data = "Bạn chưa đăng nhập.";
                redirect.Status = false;
                return Json(redirect);
            }

            var captcha = Request.Form["Captcha"];
            if (string.IsNullOrEmpty(captcha) || captcha.ToUpper() != GlobalCapcha.ToUpper())
            {
                redirect.Status = false;
                redirect.Data = "Mã xác thực không đúng.";
                return Json(redirect);
            }

            var service = new APICardCharging();
            string sessionId;
            string messages = service.Login(out sessionId);
            if (string.IsNullOrEmpty(sessionId) || messages != Utilities.GetMessages((int)ErrorMessages.Success))
            {
                redirect.Status = false;
                redirect.Data = messages;
                return Json(redirect);
            }

            var serviceCardTypes = WorkContext.Resolve<ICardTypeService>();
            var cardTypes = Request.Form["CardTypes"];
            if (string.IsNullOrEmpty(cardTypes))
            {
                redirect.Status = false;
                redirect.Data = "Bạn chưa chọn mạng cho thẻ nạp";
                return Json(redirect);
            }

            var seriNumber = Request.Form["SeriNumber"];
            if (cardTypes != "MGC" && string.IsNullOrEmpty(seriNumber))
            {
                redirect.Status = false;
                redirect.Data = "Bạn chưa nhập số seri của thẻ.";
                return Json(redirect);
            }

            var pinCode = Request.Form["PinCode"];
            if (string.IsNullOrEmpty(pinCode))
            {
                redirect.Status = false;
                redirect.Data = "Bạn chưa nhập mã thẻ cào.";
                return Json(redirect);
            }
            
            var cardType = serviceCardTypes.GetByCode(cardTypes, -1);
            if (cardType.HasSerial)
            {
                service.CardData = seriNumber + ":" + pinCode + "::" + cardTypes;
            }
            else if (!cardType.HasSerial)
            {
                service.CardData = pinCode + ":" + cardTypes;
            }

            string txttarget = "account";
            string amount;
            var status = service.CardCharging(sessionId, service.CardData, txttarget, out amount);
            if (status == ErrorMessages.Success)
            {
                var vipXu = TotalVipXu(int.Parse(amount));
                redirect.Status = true;
                redirect.Data = string.Format("Bạn đã nạp {0} VIPXU vào tài khoản {1} thành công.", vipXu, CustomerCode);
                redirect.Url = string.Format("http://{0}", Extensions.Constants.HomeDomainName);

                var transaction = new TransactionCardInfo
                {
                    CustomerCode = CustomerCode,
                    TransactionCode = TransactionCode,
                    CreateDate = DateTime.Now,
                    Amount = amount,
                    CardCode = cardTypes,
                    SeriNumber = seriNumber,
                    PinCode = pinCode,
                    Description = "Nạp thẻ thành công",
                    Status = (int)CardStatus.Success
                };

                var transactionCardService = WorkContext.Resolve<ITransactionCardService>();
                transactionCardService.CardProcessing(transaction, vipXu);
                var serviceLog = new APISmsService();
                serviceLog.InsertLog(new LogInfo
                {
                    CreateDate = DateTime.Now,
                    Messages = "Nạp tiền theo nhà mạng thành công",
                    Keyword = cardTypes,
                    Contents = "Mã GD: " + TransactionCode + " - Mã KH: " + CustomerCode + " - Số tiền nạp: " + amount + " - VIPXU: " + vipXu,
                    Type = (int)LogType.ScratchCard,
                    Status = (int)LogStatus.Success
                });

                TransactionCode = null;
                var customerService = WorkContext.Resolve<ICustomerService>();
                customerService.ResetCacheCustomers();
                var customer = customerService.GetCustomerByCacheId(UserId);
                SetCustomerState(customer);
            }
            else
            {
                 redirect.Status = true;
                 redirect.Data = Utilities.GetMessages((int)status);
                 var transaction = new TransactionCardInfo
                 {
                     CustomerCode = CustomerCode,
                     TransactionCode = TransactionCode,
                     CreateDate = DateTime.Now,
                     Amount = amount,
                     CardCode = cardTypes,
                     SeriNumber = seriNumber,
                     PinCode = pinCode,
                     Description = "Nạp tiền theo nhà mạng thất bại",
                     Status = (int)CardStatus.Error
                 };

                 var transactionCardService = WorkContext.Resolve<ITransactionCardService>();
                 transactionCardService.CardProcessing(transaction, 0);

                 var serviceLog = new APISmsService();
                 serviceLog.InsertLog(new LogInfo
                 {
                     CreateDate = DateTime.Now,
                     Messages = "Nạp tiền theo nhà mạng",
                     Keyword = cardTypes,
                     Contents = "Mã GD: " + TransactionCode + " - Mã KH: " + CustomerCode + " - Số tiền nạp: " + amount,
                     Type = (int)LogType.ScratchCard,
                     Status = (int)LogStatus.Error
                 });
            }
           
            return Json(redirect);
        }

        [HttpPost, ValidateInput(false)]
        [Url("thanh-toan/doi-ngay")]
        public ActionResult ExchangeDay()
        {
            var redirect = new DataViewerModel();
            if (!IsLogin)
            {
                redirect.Data = "Bạn chưa đăng nhập.";
                redirect.Status = false;
                return Json(redirect);
            }

            var day = Request.Form["txtExchangeDay"];
            if (string.IsNullOrEmpty(day))
            {
                redirect.Data = "Số ngày bạn chọn không đúng.";
                redirect.Status = false;
                return Json(redirect);
            }
            
            var vipXu = 0;
            var package = (ExchangeDay) int.Parse(day);
            switch (package)
            {
                case Extensions.ExchangeDay.Package15:
                    vipXu = 200;
                    break;
                case Extensions.ExchangeDay.Package50:
                    vipXu = 500;
                    break;
                case Extensions.ExchangeDay.Package100:
                    vipXu = 1000;
                    break;
                case Extensions.ExchangeDay.Package300:
                    vipXu = 3000;
                    break;
            }
           
            TransactionCode = Utilities.GenerateUniqueNumber();
            var customerService = WorkContext.Resolve<ICustomerService>();
            var status = customerService.ExchangeDay(UserId, int.Parse(day), vipXu, TransactionCode, EnumExtensions.GetDisplayName(package));
            var serviceLog = new APISmsService();
            if (status == 0)
            {
                serviceLog.InsertLog(new LogInfo
                {
                    CreateDate = DateTime.Now,
                    Messages = "Đổi VIPXU thành công",
                    Keyword = day,
                    Contents = "Mã GD: " + TransactionCode + " - Mã KH: " + CustomerCode + " - VIPXU: " + vipXu + " - Số ngày:" + day,
                    Type = (int)LogType.Other,
                    Status = (int)LogStatus.Success
                });

                TransactionCode = null;
                customerService.ResetCacheCustomers();
                var customer = customerService.GetCustomerByCacheId(UserId);
                SetCustomerState(customer);
                redirect.Data = string.Format("Bạn đã đổi {0} VIPXU lấy {1} ngày sử dụng thành công. Sử dụng từ ngày {2} đến hết ngày {3}", vipXu, day,
                    customer.StartDate != null ? customer.StartDate.Value.ToString(Extensions.Constants.DateTimeFomat) : StartDate.ToString(Extensions.Constants.DateTimeFomat),
                    customer.EndDate != null ? customer.EndDate.Value.ToString(Extensions.Constants.DateTimeFomat) : EndDate.ToString(Extensions.Constants.DateTimeFomat));
                redirect.Status = true;
            }
            else
            {
                serviceLog.InsertLog(new LogInfo
                {
                    CreateDate = DateTime.Now,
                    Messages = "Đổi VIPXU thất bại",
                    Keyword = day,
                    Contents = "Mã GD: " + TransactionCode + " - Mã KH: " + CustomerCode + " - VIPXU: " + vipXu + " - Số ngày:" + day,
                    Type = (int)LogType.Other,
                    Status = (int)LogStatus.Success
                });

                TransactionCode = null;
                redirect.Data = "Tài khoản của bạn không đủ VIPXU để thực hiện giao dịch. Vui lòng quay lại bước 1.";
                redirect.Status = false;
            }

            return Json(redirect);
        }

        private int ExchangeVipXu(int money)
        {
            var vipXu = 0;
            foreach (ExchangeMoney item in Enum.GetValues(typeof(ExchangeMoney)))
            {
                var name = EnumExtensions.GetDisplayName(item);
                var value = int.Parse(name.Replace(".", ""));
                if (value == money)
                {
                    vipXu = (int) item;
                    break;
                }
            }

            return vipXu;
        }

        private int TotalVipXu(int money)
        {
            var vipXu = ExchangeVipXu(money);
            if (vipXu == 0)
            {
                foreach (ExchangeMoney item in Enum.GetValues(typeof(ExchangeMoney)))
                {
                    var name = EnumExtensions.GetDisplayName(item);
                    var value = int.Parse(name.Replace(".", ""));
                    if (money > value)
                    {
                        var newMoney = money - value;
                        vipXu += ExchangeVipXu(value);
                        vipXu += ExchangeVipXu(newMoney);
                        break;
                    }
                }
            }

            return vipXu;
        }

        [HttpPost, ValidateInput(false)]
        [Url("thanh-toan/kich-hoat-khuyenmai")]
        public ActionResult ActiveCode()
        {
            var redirect = new DataViewerModel();
            if (!IsLogin)
            {
                redirect.Data = "Bạn chưa đăng nhập.";
                redirect.Status = false;
                return Json(redirect);
            }

            var freeCode = Request.Form["txtFreeCode"];
            if (string.IsNullOrEmpty(freeCode))
            {
                redirect.Data = "Mã khuyến mãi không tồn tại.";
                redirect.Status = false;
                return Json(redirect);
            }

            var servicePromotionCustomers = WorkContext.Resolve<IPromotionCustomersService>();
            var promotionCustomers = servicePromotionCustomers.GetCodeCustomer(UserId, freeCode);
            if (promotionCustomers == null)
            {
                redirect.Data = "Mã khuyến mãi không tồn tại.";
                redirect.Status = false;
                return Json(redirect);
            }

            var status = servicePromotionCustomers.ActiveCode(UserId, freeCode);
            var serviceLog = new APISmsService();
            if (status == 0)
            {
                serviceLog.InsertLog(new LogInfo
                {
                    CreateDate = DateTime.Now,
                    Messages = "Kích hoạt mã khuyến mãi thành công.",
                    Keyword = freeCode,
                    Contents = string.Format("Kích hoạt mã khuyến mãi {0} thành công. Đã nhận được {1} VIPXU từ mã khuyến mãi.", freeCode, promotionCustomers.Value),
                    Type = (int)LogType.Other,
                    Status = (int)LogStatus.Success
                });

                var customerService = WorkContext.Resolve<ICustomerService>();
                customerService.ResetCacheCustomers();
                var customer = customerService.GetCustomerByCacheId(UserId);
                SetCustomerState(customer);
                redirect.Data = string.Format("Bạn đã kích hoạt thành công mã khuyến mãi {0}. Bạn nhận được {1} VIPXU.", freeCode, promotionCustomers.Value);
                redirect.Status = true;
                redirect.Url = string.Format("http://{0}", Extensions.Constants.HomeDomainName);
            }
            else
            {
                serviceLog.InsertLog(new LogInfo
                {
                    CreateDate = DateTime.Now,
                    Messages = "Kích hoạt mã khuyến mãi thất bại.",
                    Keyword = freeCode,
                    Contents = string.Format("Mã khuyến mãi {0} có thể đã được sử dụng hoặc đã quá hạn sử dụng.", freeCode),
                    Type = (int)LogType.Other,
                    Status = (int)LogStatus.Error
                });

                redirect.Data = string.Format("Mã khuyến mãi {0} có thể đã được sử dụng hoặc đã quá hạn sử dụng.", freeCode);
                redirect.Status = false;
            }
           
            return Json(redirect);
        }

        [HttpPost, ValidateInput(false)]
        [Url("vip-xu/cap-nhat")]
        public ActionResult LoadVipXu()
        {
            var redirect = new DataViewerModel();
            var customerService = WorkContext.Resolve<ICustomerService>();
            customerService.ResetCacheCustomers();
            var customer = customerService.GetCustomerByCacheId(UserId);
            SetCustomerState(customer);
            redirect.Url = Url.Action("Index");
            redirect.Status = true;

            return Json(redirect);
        }

        [HttpPost, ValidateInput(false)]
        [Url("thanh-toan/kich-hoat/sms")]
        public ActionResult ActiveSmsCode()
        {
            var redirect = new DataViewerModel();
            if (!IsLogin)
            {
                redirect.Data = "Bạn chưa đăng nhập.";
                redirect.Status = false;
                return Json(redirect);
            }

            var transactionCode = Request.Form["TransactionCode"];
            if (string.IsNullOrEmpty(transactionCode))
            {
                redirect.Data = "Mã giao dịch không tồn tại.";
                redirect.Status = false;
                return Json(redirect);
            }

            var service = WorkContext.Resolve<ITransactionSmsService>();
            var transaction = service.GetByMOCode(transactionCode);
            if (transaction == null)
            {
                redirect.Data = "Mã giao dịch không tồn tại.";
                redirect.Status = false;
                return Json(redirect);
            }

            var status = service.ActiveSms(transactionCode, CustomerCode);
            var serviceLog = new APISmsService();
            if (status == 0)
            {
                var mo = service.GetByMOCode(transactionCode);
                mo.Id = 0;
                mo.Status = (int) RequestStatus.Messages200;
                mo.Type = (int) SMSType.MT;
                mo.StartDate = transaction.StartDate;
                mo.EndDate = transaction.EndDate;
                service.Insert(mo);

                serviceLog.InsertLog(new LogInfo
                {
                    CreateDate = DateTime.Now,
                    Messages = "Kích hoạt mã giao dịch SMS thành công.",
                    Keyword = transactionCode,
                    Contents = string.Format("Kích hoạt mã giao dịch SMS {0} thành công. Đã nhận được {1} ngày từ mã giao dịch. Bắt đầu từ ngày {2} đến hết ngày {3}", 
                        transactionCode, transaction.TotalDay, transaction.StartDate != null ? transaction.StartDate.Value.ToString(Extensions.Constants.DateTimeFomat) : "", 
                        transaction.EndDate != null ? transaction.EndDate.Value.ToString(Extensions.Constants.DateTimeFomat): ""),
                    Type = (int)LogType.SMS,
                    Status = (int)LogStatus.Success
                });

                var customerService = WorkContext.Resolve<ICustomerService>();
                customerService.ResetCacheCustomers();
                var customer = customerService.GetCustomerByCacheId(UserId);
                SetCustomerState(customer);
                redirect.Data = string.Format("Kích hoạt mã giao dịch SMS {0} thành công. Đã nhận được {1} ngày từ mã giao dịch. Bắt đầu từ ngày {2} đến hết ngày {3}",
                        transactionCode, transaction.TotalDay, transaction.StartDate != null ? transaction.StartDate.Value.ToString(Extensions.Constants.DateTimeFomat) : "",
                        transaction.EndDate != null ? transaction.EndDate.Value.ToString(Extensions.Constants.DateTimeFomat) : "");
                redirect.Status = true;
                redirect.Url = string.Format("http://{0}", Extensions.Constants.HomeDomainName);
            }
            else
            {
                serviceLog.InsertLog(new LogInfo
                {
                    CreateDate = DateTime.Now,
                    Messages = "Kích hoạt mã giao dịch thất bại.",
                    Keyword = transactionCode,
                    Contents = string.Format("Mã giao dịch {0} có thể đã được sử dụng hoặc đã bị khóa. Vui lòng liên hệ với quản trị để được trợ giúp.", transactionCode),
                    Type = (int)LogType.SMS,
                    Status = (int)LogStatus.Error
                });

                redirect.Data = string.Format("Mã giao dịch {0} có thể đã được sử dụng hoặc đã bị khóa. Vui lòng liên hệ với quản trị để được trợ giúp.", transactionCode);
                redirect.Status = false;
            }

            return Json(redirect);
        }
    }
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IVastService : IGenericService<VastInfo, int>, IDependency
    {
        List<VastInfo> SearchPaged(
                    string languageCode,
                    int siteId,
                    int adId,
                    int pageIndex,
                    int pageSize,
                    out int totalRecord);
    }
    
    public class VastService : GenericService<VastInfo, int>, IVastService
    {
        public VastService(IRepository<VastInfo, int> repository, IEventBus eventBus) : base(repository, eventBus)
        {

        }

        public List<VastInfo> SearchPaged(string languageCode, int siteId, int adId, 
            int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@LanguageCode", languageCode),
                AddInputParameter("@SiteId", siteId),
                AddInputParameter("@AdId", adId),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<VastInfo>("sp_Vast_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }
    }
}
<file_sep>﻿using System;
using System.Globalization;
using System.Web.Mvc;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminArticlesController : BaseAdminController
    {
        public AdminArticlesController(
            IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
            TableName = "tblArticles";
        }

        [Url("admin/articles")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý bài viết"), Url = "#" });

            var result = new ControlGridFormResult<ArticlesInfo>
            {
                Title = T("Quản lý bài viết"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetArticles,
                DefaultPageSize = WorkContext.DefaultPageSize,
                UpdateActionName = "Update",
                EnablePaginate = true,
                ClientId =TableName,
                ActionsColumnWidth = 150,
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml
            };

            result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.UserId, "$('#" + Extensions.Constants.UserId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.CategoryId, "$('#" + Extensions.Constants.CategoryId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.FromDate, "$('#" + Extensions.Constants.FromDate + "').val();", true);
            result.AddCustomVar(Extensions.Constants.ToDate, "$('#" + Extensions.Constants.ToDate + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true);
            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true);

            result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(100);
            result.AddColumn(x => x.Icon, T("Ảnh đại diện"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsImage(y => y.Icon, Extensions.Constants.CssThumbsSize);
            result.AddColumn(x => x.Title, T("Tiêu đề"));
            result.AddColumn(x => x.Alias, T("Tiêu đề không dấu"));
            result.AddColumn(x => x.CategoryName, "Chuyên mục");
            result.AddColumn(x => x.IsPublished)
                .HasHeaderText(T("Đã đăng"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage(false);

            result.AddColumn(x => x.IsHome)
                .HasHeaderText(T("Trang chủ"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage(false);

            result.AddColumn(x => x.IsVideo)
                .HasHeaderText(T("Có Videos"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage(false);

            result.AddAction().HasText(T("Thêm mới"))
                .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
                .HasButtonStyle(ButtonStyle.Primary)
                .HasBoxButton(false)
                .HasRow(false)
                .HasCssClass(Constants.RowLeft)
                .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildSites(true, Extensions.Constants.CategoryId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildCategories)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildUsers).HasParentClass(Constants.ContainerCssClassCol3));
            result.AddAction(new ControlFormHtmlAction(() => BuildFromDate())).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildToDate())).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
                .HasText(T("Sửa"))
                .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new {id = x.Id})))
                .HasButtonStyle(ButtonStyle.Default)
                .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddRowAction(true)
                .HasText(T("Xóa"))
                .HasName("Delete")
                .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString()))
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");

            return result;
        }

        protected ControlGridAjaxData<ArticlesInfo> GetArticles(ControlGridFormRequest options)
        {
            var searchText = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText]))
            {
                searchText = Request.Form[Extensions.Constants.SearchText];
            }

            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId] ))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var categoryId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.CategoryId]))
            {
                categoryId = Convert.ToInt32(Request.Form[Extensions.Constants.CategoryId]);
            }

            var fromDate = DateTime.Now.Date;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FromDate]))
            {
                fromDate = DateTime.ParseExact(Request.Form[Extensions.Constants.FromDate], Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture);
            }

            var toDate = DateTime.Now.Date;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ToDate]))
            {
                toDate = DateTime.ParseExact(Request.Form[Extensions.Constants.ToDate], Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture);
            }

            var status = -1;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId]))
            {
                var statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]);
                switch ((Status)statusId)
                {
                        case Status.Approved:
                        status = 0;
                        break;
                        case Status.Deleted:
                        status = 1;
                        break;
                }
            }

            var userId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.UserId]))
            {
                userId = int.Parse(Request.Form[Extensions.Constants.UserId]);
            }

            int totals;
            var service = WorkContext.Resolve<IArticlesService>();
            service.LanguageCode = languageCode;
            service.CategoryId = categoryId;
            var records = service.SearchPaged(
                searchText,
                siteId,
                userId,
                fromDate,
                toDate,
                status,
                options.PageIndex,
                options.PageSize,
                out totals);

            return new ControlGridAjaxData<ArticlesInfo>(records, totals);
        }

        [Url("admin/articles/edit")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý bài viết"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin bài viết"), Url = "#" });

            if (!ModelState.IsValid)
            {
                return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var model = new ArticlesModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<IArticlesService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<ArticlesModel>(model)
            {
                Title = T("Thông tin bài viết"),
                UpdateActionName = "Update",
                FormMethod = FormMethod.Post,
                SubmitButtonText = T("Lưu lại"),
                ShowBoxHeader = false,
                ShowCancelButton = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.RegisterFileUploadOptions("Icon.FileName", new ControlFileUploadOptions
            {
                AllowedExtensions = "jpg,jpeg,png,gif"
            });

            result.AddAction().HasText(T("Làm mới"))
                .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
                .HasCssClass("btn btn-success");

            result.AddAction().HasText(T("Trở về"))
               .HasUrl(Url.Action("Index"))
               .HasCssClass("btn btn-danger");

            result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages());
            result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage"));
            result.RegisterCascadingDropDownDataSource(x => x.CategoryId, Url.Action("GetCategoriesBySite"));

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/articles/update")]
        public ActionResult Update(ArticlesModel model)
        {
            var service = WorkContext.Resolve<IArticlesService>();
            service.CategoryId = model.CategoryId;
            service.LanguageCode = model.LanguageCode;

            var alias = model.Alias;
            if (string.IsNullOrEmpty(alias))
            {
                alias = Utilities.GetAlias(model.Title);
                if (service.CheckAlias(alias))
                {
                    alias += "-1";
                }
            }

            ArticlesInfo articlesInfo = model.Id == 0 ? new ArticlesInfo() : service.GetById(model.Id);

            articlesInfo.ParentId = model.ParentId;
            articlesInfo.SiteId = model.SiteId;
            articlesInfo.CategoryId = model.CategoryId;
            articlesInfo.Title = model.Title;
            articlesInfo.LanguageCode = model.LanguageCode;
            articlesInfo.Icon = model.Icon;
            articlesInfo.Alias = alias;
            articlesInfo.Summary = model.Summary;
            articlesInfo.Contents = model.Contents;
            articlesInfo.CreateDate = DateTime.Now.Date;
            articlesInfo.CreateByUser = WorkContext.CurrentUser.Id;
            articlesInfo.IsPublished = model.IsPublished;
            articlesInfo.PublishedDate = DateTime.Now.Date;
            articlesInfo.IsHome = model.IsHome;
            articlesInfo.IsVideo = model.IsVideo;
            articlesInfo.Description = model.Description;
            articlesInfo.IsDeleted = model.IsDeleted;
            articlesInfo.Tags = model.Tags;
            articlesInfo.VideosUrl = model.VideosUrl;

            service.Save(articlesInfo);

            try
            {
                #region Add Search
                var service2 = WorkContext.Resolve<ISearchService>();
                var searchObject = service2.GetBySearchId(articlesInfo.Id.ToString(), (int)SearchType.Articles);
                long id = 0;
                if (searchObject != null)
                {
                    id = searchObject.Id;
                }

                var search = new SearchInfo
                {
                    Id = id,
                    Title = articlesInfo.Title,
                    Alias = articlesInfo.Alias,
                    CategoryIds = articlesInfo.CategoryId.ToString(),
                    CreateDate = articlesInfo.CreateDate,
                    IsBlock = articlesInfo.IsDeleted,
                    LanguageCode = articlesInfo.LanguageCode,
                    SearchId = articlesInfo.Id.ToString(),
                    SiteId = articlesInfo.SiteId,
                    Sumary = articlesInfo.Summary,
                    Tags = articlesInfo.Tags,
                    Type = (int)SearchType.Articles,
                    TitleEnglish = string.Empty,
                    Images = articlesInfo.Icon,
                    ViewCount = articlesInfo.ViewCount.ToString(),
                    Processed = 0
                };

                service2.Save(search);

                var cacheSearch = new LuceneService();
                cacheSearch.UpdateLuceneIndex(search);
                #endregion
            }
            catch (Exception)
            {
                return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE")
                    .Alert(T("Không thể thêm dữ liệu tìm kiếm."));
            }

            return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"));
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<IArticlesService>();
            var obj = service.GetById(id);
            service.CategoryId = obj.CategoryId;
            obj.IsDeleted = true;
            service.Update(obj);

            return new AjaxResult()
                .NotifyMessage("DELETE_ENTITY_COMPLETE")
                .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!"));
        }
    }
}
<file_sep>﻿using System;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;

namespace CMSSolutions.Websites.Models
{
    public class AdvertisementGroupModel
    {
        public AdvertisementGroupModel()
        {
            Code = Guid.NewGuid().ToString().Replace("-", string.Empty);
            IsActived = true;
        }

        [ControlHidden]
        public int Id { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.CategoryId + "').empty();")]
        public string LanguageCode { get; set; }

        [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public int SiteId { get; set; }

        [ControlCascadingDropDown(LabelText = "Chuyên mục hiển thị", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public int CategoryId { get; set; }

        [ControlCascadingDropDown(AllowMultiple = true, EnableChosen = true, LabelText = "Quảng cáo", ParentControl = "SiteId", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)]
        public int[] AdvertisementIds { get; set; }

        [ControlText(Type = ControlText.TextBox, ReadOnly = true, LabelText = "Mã quảng cáo", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)]
        public string Code { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Tên nhóm", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol8, ContainerRowIndex = 2)]
        public string GroupName { get; set; }

        [ControlText(LabelText = "<NAME>", Type = ControlText.MultiText, Rows = 2, MaxLength = 2000, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)]
        public string Description { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Đã tạo Xml", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)]
        public bool IsGenerate { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Đang sử dụng", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)]
        public bool IsActived { get; set; }

        [ControlDatePicker(LabelText = "Ngày hết hạn", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)]
        public string FinishDate { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Giờ hết hạn", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)]
        public string FinishTime { get; set; }

        public static implicit operator AdvertisementGroupModel(AdvertisementGroupInfo entity)
        {
            return new AdvertisementGroupModel
            {
                LanguageCode = entity.LanguageCode,
                SiteId = entity.SiteId,
                CategoryId = entity.CategoryId,
                Id = entity.Id,
                Code = entity.Code,
                GroupName = entity.GroupName,
                Description = entity.Description,
                AdvertisementIds = Utilities.ParseListInt(entity.AdvertisementIds),
                IsGenerate = entity.IsGenerate,
                IsActived = entity.IsActived,
                FinishDate = entity.FinishDate.ToString(Extensions.Constants.DateTimeFomat),
                FinishTime = entity.FinishTime
            };
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface ITransactionSmsService : IGenericService<TransactionSmsInfo, long>, IDependency
    {
        int ActiveSms(string transactionCode, string customerCode);

        TransactionSmsInfo GetByMOCode(string transactionCode);

        IList<TransactionSmsInfo> GetPaged(string keyword, int type, int status, int isClosed,
            DateTime fromDate, DateTime toDate, int pageIndex, int pageSize, out int totals);

        IList<TransactionSmsInfo> ExportExcelSms(DateTime fromDate, DateTime toDate, int type);

        int SmsClosed(DateTime toDate);
    }

    public class TransactionSmsService : GenericService<TransactionSmsInfo, long>, ITransactionSmsService
    {
        public TransactionSmsService(IRepository<TransactionSmsInfo, long> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public int ActiveSms(string transactionCode, string customerCode)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@TransactionCode", transactionCode),
                AddInputParameter("@CustomerCode", customerCode)
            };

            return (int)ExecuteReaderResult("sp_TransactionSms_Active", list.ToArray());
        }

        public TransactionSmsInfo GetByMOCode(string transactionCode)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@TransactionCode", transactionCode)
            };

            return ExecuteReaderRecord<TransactionSmsInfo>("sp_TransactionSms_GetMOCode", list.ToArray());
        }

        public IList<TransactionSmsInfo> GetPaged(string keyword, int type,
            int status, int isClosed, DateTime fromDate, DateTime toDate, 
            int pageIndex, int pageSize, out int totals)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SearchText", keyword),
                AddInputParameter("@Type", type),
                AddInputParameter("@Status", status),
                AddInputParameter("@IsClosed", isClosed),
                AddInputParameter("@FromDate", fromDate),
                AddInputParameter("@ToDate", toDate),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<TransactionSmsInfo>("sp_TransactionSms_Search_Paged", "@TotalRecord", out totals, list.ToArray());
        }

        public IList<TransactionSmsInfo> ExportExcelSms(DateTime fromDate, DateTime toDate, int type)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Type", type),
                AddInputParameter("@FromDate", fromDate),
                AddInputParameter("@ToDate", toDate)
            };

            return ExecuteReader<TransactionSmsInfo>("sp_TransactionSms_ReportSms", list.ToArray());
        }

        public int SmsClosed(DateTime toDate)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@ToDate", toDate)
            };

            return ExecuteNonQuery("sp_TransactionSms_Closed", list.ToArray());
        }
    }
}<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class ArticlesModel
    {
        public ArticlesModel()
        {
            CategoryId = 59;
            IsPublished = true;
        }

        [ControlHidden]
        public int Id { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.CategoryId + "').empty();")]
        public string LanguageCode { get; set; }

        [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public int SiteId { get; set; }

        [ControlCascadingDropDown(LabelText = "Chuyên mục hiển thị", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public int CategoryId { get; set; }

        [ControlText(LabelText = "Bài viết liên quan", Type = ControlText.TextBox, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public int ParentId { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Đăng tin", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public bool IsPublished { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Hiện trên trang chủ", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public bool IsHome { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Không sử dụng", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public bool IsDeleted { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Tin có videos", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public bool IsVideo { get; set; }

        [ControlText(Type = ControlText.TextBox, PlaceHolder = "Vui lòng nhập tiêu đề bài viết. Tối đa 200 ký tự.", LabelText = "Tiêu đề", Required = true, MaxLength = 200, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)]
        public string Title { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Tiêu đề hỗ trợ SEO", PlaceHolder = "Mặc định để trống, tự sinh.", MaxLength = 200, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 2)]
        public string Alias { get; set; } 

        [ControlFileUpload(EnableFineUploader = true, LabelText = "Ảnh đại diện", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 3, Required = true, ShowThumbnail = true)]
        public string Icon { get; set; }

        [ControlText(Type = ControlText.MultiText, PlaceHolder = "Nhập nhiều đường dẫn videos ở đây chú ý tách nhau bởi dấu ';'", LabelText = "Đường dẫn vieos", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 4)]
        public string VideosUrl { get; set; }

        [ControlText(LabelText = "Tóm tắt nội dung", PlaceHolder = "Vui lòng tóm tắt nội dung bài viết. Tối đa 400 ký tự.", Type = ControlText.MultiText, Rows = 2, Required = true, MaxLength = 400, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 5)]
        public string Summary { get; set; }

        [ControlText(LabelText = "Nội dung bài viết", Required = true, Type = ControlText.RichText, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 6)]
        public string Contents { get; set; }

        [ControlText(LabelText = "Từ khóa SEO", Required = true, PlaceHolder = "Vui lòng nhập từ khóa SEO cho bài viết. Tối đa 400 ký tự.", Type = ControlText.MultiText, Rows = 2, MaxLength = 400, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 7)]
        public string Description { get; set; }

        [ControlText(LabelText = "Tags SEO", Required = true, PlaceHolder = "Nhập từ khóa SEO cách nhau bởi dấu, Tối đa 500 ký tự.", Type = ControlText.MultiText, Rows = 2, MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 8)]
        public string Tags { get; set; }

        public static implicit operator ArticlesModel(ArticlesInfo other)
        {
            if (other == null)
            {
                return null;
            }

            return new ArticlesModel
            {
                Id = other.Id,
                LanguageCode = other.LanguageCode,
                Alias = other.Alias,
                ParentId = other.ParentId,
                CategoryId = other.CategoryId,
                Title = other.Title,
                Icon =  other.Icon,
                IsPublished = other.IsPublished,
                IsHome = other.IsHome,
                IsVideo = other.IsVideo,
                Summary = other.Summary,
                Contents = other.Contents,
                Description = other.Description,
                IsDeleted = other.IsDeleted,
                VideosUrl = other.VideosUrl,
                Tags = other.Tags,
                SiteId = other.SiteId
            };
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using CMSSolutions.Extensions;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminPromotionController : BaseAdminController
    {
        public AdminPromotionController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
            TableName = "tblPromotions";
        }

        [Url("admin/promotions")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý đợt khuyến mãi"), Url = "#" });

            var result = new ControlGridFormResult<PromotionInfo>
            {
                Title = T("Quản lý đợt khuyến mãi"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetPromotions,
                DefaultPageSize = WorkContext.DefaultPageSize,
                EnablePaginate = true,
                UpdateActionName = "Update",
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml,
                ClientId = TableName,
                ActionsColumnWidth = 250
            };

            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true);

            result.AddColumn(x => x.Id, T("ID")).HasWidth(60).AlignCenter();
            result.AddColumn(x => x.Title, T("Thông tin khuyến mãi"));
            result.AddColumn(x => x.TextFromDate, T("Ngày bắt đầu"));
            result.AddColumn(x => x.TextToDate, T("Ngày kết thúc"));
            result.AddColumn(x => EnumExtensions.GetDisplayName((PromotionStatus)x.Status), T("Trạng thái"));

            result.AddAction().HasText(T("Thêm mới"))
                .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
                .HasButtonStyle(ButtonStyle.Primary)
                .HasBoxButton(false)
                .HasCssClass(Constants.RowLeft)
                .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(BuildPromotionStatus)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction().HasText(T("Áp dụng KM"))
               .HasUrl(x => Url.Action("Index","AdminPromotionCustomers", RouteData.Values.Merge(new { @promotionId = x.Id })))
               .HasButtonStyle(ButtonStyle.Info)
               .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddRowAction()
                .HasText(T("Sửa"))
                .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                .HasButtonStyle(ButtonStyle.Default)
                .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddRowAction(true)
                .HasText(T("Đã kết thúc"))
                .HasName("Delete")
                .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString()))
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");
            return result;
        }

        private string BuildPromotionStatus()
        {
            var list = EnumExtensions.GetListItems<PromotionStatus>();
            var sb = new StringBuilder();
            sb.AppendFormat(T("Trạng thái") + " <select id=\"" + Extensions.Constants.StatusId + "\" name=\"" + Extensions.Constants.StatusId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var status in list)
            {
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        private ControlGridAjaxData<PromotionInfo> GetPromotions(ControlGridFormRequest options)
        {
            var statusId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId]))
            {
                statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]);
            }
            int totals;
            var items = WorkContext.Resolve<IPromotionService>().SearchPaged(statusId, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<PromotionInfo>(items, totals);

            return result;
        }

        [Url("admin/promotions/edit/{id}")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý đợt khuyến mãi"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin đợt khuyến mãi"), Url = "#" });

            var model = new PromotionModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<IPromotionService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<PromotionModel>(model)
            {
                Title = T("Thông tin đợt khuyến mãi"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                CancelButtonText = T("Trở về"),
                ShowBoxHeader = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.RegisterExternalDataSource(x => x.Status, y => EnumExtensions.GetListItems<PromotionStatus>());
            if (id > 0)
            {
                result.AddAction().HasText(T("Áp dụng KM"))
                .HasUrl(Url.Action("Index","AdminPromotionCustomers", new { @promotionId = id }))
                .HasButtonStyle(ButtonStyle.Info);
            }

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/promotions/update")]
        public ActionResult Update(PromotionModel model)
        {
            PromotionInfo item;
            var service = WorkContext.Resolve<IPromotionService>();
            if (model.Id == 0)
            {
                item = new PromotionInfo();
            }
            else
            {
                item = service.GetById(model.Id);
            }

            item.Title = model.Title;
            item.Contents = model.Contents;
            item.FromDate = model.FromDate;
            item.ToDate = model.ToDate;
            item.Status = model.Status;
            service.Save(item);

            return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE").Alert(T("Cập nhật thành công!"));
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<IPromotionService>();
            var model = service.GetById(id);
            model.Status = (int)PromotionStatus.Finish;
            service.Update(model);

            return new AjaxResult().NotifyMessage("DELETE_ENTITY_COMPLETE");
        }
    }
}
<file_sep>using System.ComponentModel;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class CardTypeInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("Code")]
        public string Code { get; set; }
        
        [DataMember]
        [DisplayName("Name")]
        public string Name { get; set; }
        
        [DataMember]
        [DisplayName("HasSerial")]
        public bool HasSerial { get; set; }
        
        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }
    }

    public class CardTypeMap : EntityTypeConfiguration<CardTypeInfo>, IEntityTypeConfiguration
    {

        public CardTypeMap()
        {
            ToTable("Modules_CardTypes");
            HasKey(m => m.Id);
            Property(m => m.Code).HasMaxLength(50);
            Property(m => m.Name).HasMaxLength(250);
        }
    }
}
<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class CountryModel
    {
        [ControlHidden]
        public int Id { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 50, LabelText = "Mã nước", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 0)]
        public string Code { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 50, LabelText = "Tên nước", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)]
        public string Name { get; set; }
        
        public static implicit operator CountryModel(CountryInfo entity)
        {
            return new CountryModel
            {
                Id = entity.Id,
                Code = entity.Code,
                Name = entity.Name
            };
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface ITransactionBankService : IGenericService<TransactionBankInfo, long>, IDependency
    {
        int BankProcessing(TransactionBankInfo entity, int vipXu);

        IList<TransactionBankInfo> GetPaged(string keyword, string bankCode, int type, int status, int isLock,
            DateTime fromDate, DateTime toDate, int pageIndex, int pageSize, out int totals);

        int ATMClosed(DateTime toDate);

        IList<TransactionBankInfo> ExportExcelAtm(DateTime fromDate, DateTime toDate, int type);
    }

    public class TransactionBankService : GenericService<TransactionBankInfo, long>, ITransactionBankService
    {
        public TransactionBankService(IRepository<TransactionBankInfo, long> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public int BankProcessing(TransactionBankInfo entity, int vipXu)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@CustomerCode", entity.CustomerCode),
                AddInputParameter("@TransactionCode", entity.TransactionCode),
                AddInputParameter("@CreateDate", entity.CreateDate),
                AddInputParameter("@BankCode", entity.BankCode),
                AddInputParameter("@Amount", entity.Amount),
                AddInputParameter("@ResponCode", entity.ResponCode),
                AddInputParameter("@Mac", entity.Mac),
                AddInputParameter("@TransId", entity.TransId),
                AddInputParameter("@Type", entity.Type),
                AddInputParameter("@Description", entity.Description),
                AddInputParameter("@Status", entity.Status),
                AddInputParameter("@VipXu", vipXu)
            };

            return ExecuteNonQuery("sp_TransactionBank_BankProcessing", list.ToArray());
        }

        public IList<TransactionBankInfo> ExportExcelAtm(DateTime fromDate, DateTime toDate, int type)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Type", type),
                AddInputParameter("@FromDate", fromDate),
                AddInputParameter("@ToDate", toDate)
            };

            return ExecuteReader<TransactionBankInfo>("sp_TransactionBank_ReportATM", list.ToArray());
        }

        public IList<TransactionBankInfo> GetPaged(string keyword, string bankCode, int type, int status, int isLock, 
            DateTime fromDate, DateTime toDate, int pageIndex, int pageSize, out int totals)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SearchText", keyword),
                AddInputParameter("@BankCode", bankCode),
                AddInputParameter("@Type", type),
                AddInputParameter("@Status", status),
                AddInputParameter("@IsLock", isLock),
                AddInputParameter("@FromDate", fromDate),
                AddInputParameter("@ToDate", toDate),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<TransactionBankInfo>("sp_TransactionBank_Search_Paged", "@TotalRecord", out totals, list.ToArray());
        }

        public int ATMClosed(DateTime toDate)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@ToDate", toDate)
            };

            return ExecuteNonQuery("sp_TransactionAtm_Closed", list.ToArray());
        }
    }
}<file_sep>﻿using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface ISupportService : IGenericService<SupportInfo, int>, IDependency
    {
        string LanguageCode { get; set; }

        int SiteId { get; set; }

        IList<SupportInfo> GetAllParents(int status);

        IList<SupportInfo> GetPaged(string keyword, int parentId, int status, int pageIndex, int pageSize, out int totals);

        IList<SupportInfo> GetByParent(int parentId);

        IList<SupportInfo> GetAllChildren(int status);
    }

    public class SupportService : GenericService<SupportInfo, int>, ISupportService
    {
        public SupportService(IRepository<SupportInfo, int> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public string LanguageCode { get; set; }
        public int SiteId { get; set; }

        public IList<SupportInfo> GetAllParents(int status)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@Status", status),
            };

            return ExecuteReader<SupportInfo>("sp_Supports_GetAllParents", list.ToArray());
        }

        public IList<SupportInfo> GetPaged(string keyword, int parentId, int status, int pageIndex, int pageSize, out int totals)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Keyword", keyword),
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@ParentId", parentId),
                AddInputParameter("@Status", status),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<SupportInfo>("sp_Supports_Search_Paged", "@TotalRecord", out totals, list.ToArray());
        }

        public IList<SupportInfo> GetByParent(int parentId)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@ParentId", parentId)
            };

            return ExecuteReader<SupportInfo>("sp_Supports_GetByParent", list.ToArray());
        }

        public IList<SupportInfo> GetAllChildren(int status)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@Status", status),
            };

            return ExecuteReader<SupportInfo>("sp_Supports_GetAllChildren", list.ToArray());
        }
    }
}<file_sep>﻿using System;
using System.Web.Mvc;
using CMSSolutions.Extensions;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminFilmTypesController : BaseAdminController
    {
        public AdminFilmTypesController(IWorkContextAccessor workContextAccessor) : 
                base(workContextAccessor)
        {
            TableName = "tblFilmTypes";
        }
        
        [Url("admin/film-types")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý thể loại phim"), Url = "#" });

            var result = new ControlGridFormResult<FilmTypesInfo>
            {
                Title = T("Quản lý thể loại phim"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetFilmTypes,
                UpdateActionName = "Update",
                ActionsColumnWidth = 100,
                ClientId = TableName,
                DefaultPageSize = WorkContext.DefaultPageSize,
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml
            };

            result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true);

            result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(60);
            result.AddColumn(x => x.Name, T("Tên thể loại phim"));
            result.AddColumn(x => EnumExtensions.GetDisplayName((Status)x.Status), T("Trạng thái"));

            result.AddAction().HasText(T("Thêm mới"))
               .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
               .HasButtonStyle(ButtonStyle.Primary)
               .HasBoxButton(false)
               .HasCssClass(Constants.RowLeft)
               .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildSites(false, string.Empty))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
                 .HasText(T("Sửa"))
                 .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                 .HasButtonStyle(ButtonStyle.Default)
                 .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddRowAction(true)
                .HasText(T("Xóa"))
                .HasName("Delete")
                .HasValue(x => x.Id)
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");
            return result;
        }

        private ControlGridAjaxData<FilmTypesInfo> GetFilmTypes(ControlGridFormRequest options)
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var statusId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId]))
            {
                statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]);
            }

            int totals;
            var items = WorkContext.Resolve<IFilmTypesService>().GetPaged(languageCode,siteId, statusId, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<FilmTypesInfo>(items, totals);

            return result;
        }
        
        [Url("admin/film-types/edit/{id}")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý thể loại phim"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin thể loại phim"), Url = "#" });

            var model = new FilmTypesModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<IFilmTypesService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<FilmTypesModel>(model)
            {
                Title = T("Thông tin thể loại phim"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                CancelButtonText = T("Trở về"),
                ShowBoxHeader = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages());
            result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage"));
            result.RegisterExternalDataSource(x => x.Status, y => BindStatus());

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/film-types/update")]
        public ActionResult Update(FilmTypesModel model)
        {
            if (!ModelState.IsValid)
            {
				return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var service = WorkContext.Resolve<IFilmTypesService>();
            FilmTypesInfo item = model.Id == 0 ? new FilmTypesInfo() : service.GetById(model.Id);

            item.LanguageCode = model.LanguageCode;
            item.SiteId = model.SiteId;
            item.Name = model.Name;
            item.Description = model.Description;
            item.Status = model.Status;
            item.IsFilm = model.IsFilm;
            item.IsShow = model.IsShow;
            item.IsClip = model.IsClip;
            item.IsJJFilm = model.IsJJFilm;
            service.Save(item);

            return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"));
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<IFilmTypesService>();
            var item = service.GetById(id);
            item.Status = (int)Status.Deleted;
            service.Update(item);

            return new AjaxResult()
                .NotifyMessage("DELETE_ENTITY_COMPLETE")
                .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!"));
        }
    }
}
<file_sep>﻿using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class SliderInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("SiteId")]
        public int SiteId { get; set; }

        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }

        [DataMember]
        [DisplayName("CategoryId")]
        public int CategoryId { get; set; }

        [NotMapped]
        [DisplayName("CategoryName")]
        public string CategoryName { get; set; }

        [DataMember]
        [DisplayName("PageId")]
        public int PageId { get; set; }

        [DataMember]
        [DisplayName("FilmId")]
        public long FilmId { get; set; }

        [NotMapped]
        [DisplayName("FilmName")]
        public string FilmName { get; set; }

        [DataMember]
        [DisplayName("Images")]
        public string Images { get; set; }

        [DataMember]
        [DisplayName("OrderBy")]
        public int OrderBy { get; set; }
    }

    public class SliderMap : EntityTypeConfiguration<SliderInfo>, IEntityTypeConfiguration
    {
        public SliderMap()
        {
            ToTable("Modules_Slider");
            HasKey(x => x.Id);
            Property(x => x.LanguageCode).HasMaxLength(50).IsRequired();
            Property(x => x.SiteId).IsRequired();
            Property(x => x.CategoryId).IsRequired();
            Property(x => x.PageId).IsRequired();
            Property(x => x.FilmId).IsRequired();
            Property(x => x.Images).IsRequired().HasMaxLength(500);
            Property(x => x.OrderBy).IsRequired();
        }
    }
}<file_sep>﻿using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Caching;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface ISliderService : ICacheService<SliderInfo, int>, IGenericService<SliderInfo, int>, IDependency
    {
        string LanguageCode { get; set; }

        int SiteId { get; set; }

        IList<SliderInfo> GetPaged(int pageId, int pageIndex, int pageSize, out int totals);

        IList<SliderInfo> GetByPageId(int pageId);

        void RefreshByPage(int pageId);

        IList<SliderInfo> GetCacheByPageId(int pageId);
    }

    public class SliderService : GenericService<SliderInfo, int>, ISliderService
    {
        private readonly ICacheInfo cacheManager;
        private readonly ICategoryService categoryService;
        public SliderService(IRepository<SliderInfo, int> repository,
            IEventBus eventBus, ICacheInfo cacheManager,
            ICategoryService categoryService)
            : base(repository, eventBus)
        {
            this.cacheManager = cacheManager;
            this.categoryService = categoryService;
        }

        public string LanguageCode { get; set; }

        public int SiteId { get; set; }

        public IList<SliderInfo> GetPaged(int pageId, int pageIndex, int pageSize, out int totals)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@PageId", pageId),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<SliderInfo>("sp_Slider_Search_Paged", "@TotalRecord", out totals, list.ToArray());
        }

        public IList<SliderInfo> GetByPageId(int pageId)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@PageId", pageId)
            };

            return ExecuteReader<SliderInfo>("sp_Slider_GetByPageId", list.ToArray());
        }

        public IList<SliderInfo> GetCacheByPageId(int pageId)
        {
            var list = cacheManager.Get(string.Format(Extensions.Constants.CacheKeys.HOME_SLIDER_PAGE, pageId));
            if (list == null)
            {
                list = GetByPageId(pageId);
                cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_SLIDER_PAGE, pageId));
                cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_SLIDER_PAGE, pageId), list);
            }

            return (IList<SliderInfo>)list;
        }

        public void RefreshByPage(int pageId)
        {
            cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_SLIDER_PAGE, pageId));
            cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_SLIDER_PAGE, pageId), GetByPageId(pageId));
        }

        public SliderInfo GetByIdCache(int id)
        {
            throw new System.NotImplementedException();
        }

        public IList<SliderInfo> GetAllCache()
        {
            throw new System.NotImplementedException();
        }

        public IList<SliderInfo> ResetCache()
        {
            throw new System.NotImplementedException();
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using CMSSolutions.Configuration;
using CMSSolutions.Extensions;
using CMSSolutions.Localization.Domain;
using CMSSolutions.Localization.Services;
using CMSSolutions.Security.Cryptography;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Security;
using CMSSolutions.Web.Security.Services;
using CMSSolutions.Web.Themes;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Authorize]
    [Themed(IsDashboard = true)]
    public class BaseAdminController : BaseController
    {
        public BaseAdminController(
            IWorkContextAccessor workContextAccessor)
            : base(workContextAccessor)
        {
            
        }

        public virtual FTPClient GetConnectionFtp(int serverId, out string rootFolder, out string languageCode, out int siteId)
        {
            var service = WorkContext.Resolve<IFilmServersService>();
            var server = service.GetById(serverId);
            if (server != null)
            {
                string password = EncryptionExtensions.Decrypt(KeyConfiguration.PublishKey, server.Password);
                if (string.IsNullOrEmpty(password))
                {
                    throw new ArgumentException(T(SecurityConstants.ErrorConfigKey).Text);
                }

                string userName = EncryptionExtensions.Decrypt(KeyConfiguration.PublishKey, server.UserName);
                if (string.IsNullOrEmpty(userName))
                {
                    throw new ArgumentException(T(SecurityConstants.ErrorConfigKey).Text);
                }

                rootFolder = server.FolderRoot;
                languageCode = server.LanguageCode;
                siteId = server.SiteId;
                return new FTPClient(server.ServerIP, userName, password);
            }

            rootFolder = string.Empty;
            languageCode = string.Empty;
            siteId = 0;
            return null;
        }

        public virtual string BuildFromDate(bool showDefaultDate = true)
        {
            var sb = new StringBuilder();
            var date = "";
            if (showDefaultDate)
            {
                date = DateTime.Now.AddDays(-7).ToString("dd/MM/yyyy");
            }

            var fromDateSelected = GetQueryString(9);
            if (!string.IsNullOrEmpty(fromDateSelected))
            {
                date = fromDateSelected;
            }

            sb.AppendFormat(T("Từ ngày") + " <input id=\"" + Extensions.Constants.FromDate + "\" name=\"" + Extensions.Constants.FromDate + "\" value=\"" + date + "\" class=\"form-control datepicker\"></input>");
            sb.Append("<script>$(document).ready(function () { " +
                      "$('.datepicker').datepicker({ " +
                      "dateFormat: 'dd/mm/yy', " +
                      "changeMonth: true, " +
                      "changeYear: true, " +
                      "onSelect: function (dateText) { " +
                      "$('#" + TableName + "').jqGrid().trigger('reloadGrid'); " +
                      "}}); });</script>");

            return sb.ToString();
        }

        public virtual string BuildToDate(bool showDefaultDate = true)
        {
            var sb = new StringBuilder();
            var date = "";
            if (showDefaultDate)
            {
                date = DateTime.Now.ToString("dd/MM/yyyy");
            }

            var toDateSelected = GetQueryString(10);
            if (!string.IsNullOrEmpty(toDateSelected))
            {
                date = toDateSelected;
            }

            sb.AppendFormat(T("Đến ngày") + " <input id=\"" + Extensions.Constants.ToDate + "\" name=\"" + Extensions.Constants.ToDate + "\" value=\"" + date + "\" class=\"form-control datepicker\"></input>");
            sb.Append("<script>$(document).ready(function () { " +
                      "$('.datepicker').datepicker({ " +
                      "dateFormat: 'dd/mm/yy', " +
                      "changeMonth: true, " +
                      "changeYear: true, " +
                      "onSelect: function (dateText) { " +
                      "$('#" + TableName + "').jqGrid().trigger('reloadGrid'); " +
                      "}}); });</script>");

            return sb.ToString();
        }

        public virtual string BuildSearchText()
        {
            var sb = new StringBuilder();

            var keyword = GetQueryString(11);
            sb.AppendFormat(T("Từ khóa") + " <input value=\"" + keyword + "\" placeholder=\"" + T("Nhập từ khóa cần tìm.") + "\" id=\"" + Extensions.Constants.SearchText + "\" name=\"" + Extensions.Constants.SearchText + "\" class=\"form-control\" onkeypress = \"return InputEnterEvent(event, '" + TableName + "');\" onblur=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\"></input>");

            return sb.ToString();
        }

        public virtual string BuildStatus()
        {
            var list = EnumExtensions.GetListItems<Status>();
            var statusSelected = GetQueryString(8);
            var sb = new StringBuilder();
            sb.AppendFormat(T("Trạng thái") + " <select id=\"" + Extensions.Constants.StatusId + "\" name=\"" + Extensions.Constants.StatusId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var status in list)
            {
                if (!string.IsNullOrEmpty(statusSelected) && status.Value == statusSelected)
                {
                    sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", status.Text, status.Value);
                    continue;
                }

                sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        public virtual string BuildServers()
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var service = WorkContext.Resolve<IFilmServersService>();
            var list = service.GetRecords(x => x.LanguageCode == languageCode && x.SiteId == siteId);
            var sb = new StringBuilder();
            sb.AppendFormat(T("Máy chủ") + " <select id=\"" + Extensions.Constants.ServerId + "\" name=\"" + Extensions.Constants.ServerId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var server in list)
            {
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", server.ServerName, server.Id);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        public virtual IEnumerable<SelectListItem> BindServers()
        {
            var service = WorkContext.Resolve<IFilmServersService>();
            var items = service.GetRecords();
            var result = new List<SelectListItem>();
            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = string.Format("[{0}] {1} {2}", item.ServerIP, item.ServerName, item.IsVip ? T(" - VIP") : T(" - Thường")),
                Value = item.Id.ToString(),
                Selected = item.IsDefault
            }));

            result.Insert(0, new SelectListItem { Text = "--- Chọn máy chủ ---", Value = "0" });

            return result;
        }

        public virtual string BuildUsers()
        {
            var service = WorkContext.Resolve<IMembershipService>();
            var list = service.GetRecords(x => !x.IsLockedOut);
            var sb = new StringBuilder();
            var userSelected = GetQueryString(3);
            sb.AppendFormat(T("Người quản trị") + " <select id=\"" + Extensions.Constants.UserId + "\" name=\"" + Extensions.Constants.UserId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var user in list)
            {
                if (string.IsNullOrEmpty(userSelected))
                {
                    if (user.Id == WorkContext.CurrentUser.Id)
                    {
                        sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", user.FullName, user.Id);
                        continue;
                    }
                }

                if (!string.IsNullOrEmpty(userSelected) && user.Id == int.Parse(userSelected))
                {
                    sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", user.FullName, user.Id);
                    continue;
                }
                
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", user.FullName, user.Id);
            }

            sb.Append("</select>");

            return sb.ToString();
        }

        public virtual string BuildCountries()
        {
            var service = WorkContext.Resolve<ICountryService>();
            var items = service.GetRecords();
            var result = new List<SelectListItem>();
            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.Name,
                Value = item.Id.ToString()
            }));
            result.Insert(0, new SelectListItem {Text = T("--- Chọn nước sản xuât ---"), Value = "0"});

            var sb = new StringBuilder();
            sb.AppendFormat(T("Nước sản xuất") + " <select id=\"" + Extensions.Constants.CountryId + "\" name=\"" + Extensions.Constants.CountryId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var item in result)
            {
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", item.Text, item.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        public string GetQueryString(int index)
        {
            var returnUrl = Request.QueryString[Extensions.Constants.ReturnUrl];
            if (!string.IsNullOrEmpty(returnUrl))
            {
                var data = Encoding.UTF8.GetString(Convert.FromBase64String(returnUrl));
                if (!string.IsNullOrEmpty(data))
                {
                    var list = data.Split(',');
                    if (list.Length > index)
                    {
                        var result = list[index];
                        if (result != "null")
                        {
                            return result;
                        }
                    }
                }
            }

            return string.Empty;
        }

        public virtual string BuildLanguages(bool hasEvent, string controlName)
        {
            var service = WorkContext.Resolve<ILanguageService>();
            var items = service.GetActiveLanguages();
            var list = new List<Language>();
            list.AddRange(items.Where(x => x.Theme == Constants.ThemeDefault));
            var sb = new StringBuilder();

            if (hasEvent)
            {
                var url = Url.Action("GetSitesByLanguage");
                sb.AppendFormat(T("Ngôn ngữ") + " <select id=\"" + Extensions.Constants.LanguageCode + "\" name=\"" + Extensions.Constants.LanguageCode + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"" +
                " var data = $('#" + TableName + "_Container').find('select').serialize();" +
                    @"$.ajax({{
	                url: '" + url + @"',
	                data: data,
	                type: 'POST',
	                dataType: 'json',
	                success: function (result) {{
                        $('#" + controlName + @"').empty();
                        if (result != null){{
		                    $.each(result, function(idx, item) {{                  
                                $('#" + controlName + @"').append($('<option>', {{
                                    value: item.Value,
                                    text: item.Text
                                }}));
                            }});   
                        }}
	                }}
                }});
                $('#" + TableName + "').jqGrid().trigger('reloadGrid');" +
                "\">");
            }
            else
            {
                sb.AppendFormat(T("Ngôn ngữ") + " <select id=\"" + Extensions.Constants.LanguageCode + "\" name=\"" + Extensions.Constants.LanguageCode + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            }

            var languageSelected = GetQueryString(0);
            foreach (var language in list)
            {
                if (string.IsNullOrEmpty(languageSelected))
                {
                    if (language.CultureCode == WorkContext.CurrentCulture)
                    {
                        sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", language.Name, language.CultureCode);
                        continue;
                    }
                }

                if (!string.IsNullOrEmpty(languageSelected) && language.CultureCode == languageSelected)
                {
                    sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", language.Name, language.CultureCode);
                    continue;
                }

                sb.AppendFormat("<option value=\"{1}\">{0}</option>", language.Name, language.CultureCode);
            }

            sb.Append("</select>");

            return sb.ToString();
        }

        public virtual IEnumerable<SelectListItem> BindFilmTypes()
        {
            var service = WorkContext.Resolve<IFilmTypesService>();
            var items = service.GetRecords(x => x.Status == (int)Status.Approved);
            var result = new List<SelectListItem>();
            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.Name,
                Value = item.Id.ToString()
            }));

            return result;
        }

        public virtual IEnumerable<SelectListItem> BindCountries()
        {
            var service = WorkContext.Resolve<ICountryService>();
            var items = service.GetRecords();
            var result = new List<SelectListItem>();
            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.Name,
                Value = item.Id.ToString()
            }));

            return result;
        }

        public virtual string BuildSites(bool hasEvent, string controlName)
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }
            var service = WorkContext.Resolve<ISiteService>();
            var list = service.GetRecords(x => x.LanguageCode == languageCode);
            var result = new List<SelectListItem>();
            result.AddRange(list.Select(item => new SelectListItem
            {
                Text = item.Name,
                Value = item.Id.ToString(),
                Selected = item.IsActived
            }));
            result.Insert(0, new SelectListItem { Text = "--- Chọn trang web ---", Value = "0" });

            var url = Url.Action("GetCategoriesBySite");
            var sb = new StringBuilder();
            if (hasEvent)
            {
                sb.AppendFormat(T("Trang web") + " <select id=\"" + Extensions.Constants.SiteId + "\" name=\"" + Extensions.Constants.SiteId +
                "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"" +
                " var data = $('#" + TableName + "_Container').find('select').serialize();" +
                @"$.ajax({{
	                url: '" + url + @"',
	                data: data,
	                type: 'POST',
	                dataType: 'json',
	                success: function (result) {{
                        $('#" + controlName + @"').empty();
                        if (result != null){{
		                    $.each(result, function(idx, item) {{
                                $('#" + controlName + @"').append($('<option>', {{
                                    value: item.Value,
                                    text: item.Text
                                }}));
                            }});   
                        }} 
	                }}
                }});
                $('#" + TableName + "').jqGrid().trigger('reloadGrid');" +
                "\">");
            }
            else
            {
                sb.AppendFormat(T("Trang web") + " <select id=\"" + Extensions.Constants.SiteId + "\" name=\"" + Extensions.Constants.SiteId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            }

            var siteSelected = GetQueryString(1);
            foreach (var site in result)
            {
                if (!string.IsNullOrEmpty(siteSelected) && site.Value == siteSelected)
                {
                    sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", site.Text, site.Value);
                    continue;
                }

                sb.AppendFormat("<option value=\"{1}\">{0}</option>", site.Text, site.Value);
            }
            sb.Append("</select>");

            var categorySelected = GetQueryString(2);
            if (!string.IsNullOrEmpty(siteSelected) && !string.IsNullOrEmpty(categorySelected))
            {
                sb.AppendFormat("<script type=\"text/javascript\">$(document).ready(function() {{" +
                "var data = $('#" + TableName + "_Container').find('select').serialize();" +
                @"$.ajax({{
	                url: '" + url + @"',
	                data: data,
	                type: 'POST',
	                dataType: 'json',
	                success: function (result) {{
                        $('#" + controlName + @"').empty();
                        if (result != null){{
		                    $.each(result, function(idx, item) {{
                                if(item.Value == '"+categorySelected+@"'){{
                                    $('#" + controlName + @"').append('<option selected value=' + item.Value + '>'+ item.Text +'</option>');
                                }} else{{
                                    $('#" + controlName + @"').append('<option value=' + item.Value + '>'+ item.Text +'</option>');
                                }}                               
                            }}); 
                        }} 
	                }}
                }});}});</script>");
            }

            return sb.ToString();
        }

        public virtual string BuildSiteServers(bool hasEvent, string controlName)
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }
            var service = WorkContext.Resolve<ISiteService>();
            var list = service.GetRecords(x => x.LanguageCode == languageCode);
            var result = new List<SelectListItem>();
            result.AddRange(list.Select(item => new SelectListItem
            {
                Text = item.Name,
                Value = item.Id.ToString(),
                Selected = item.IsActived
            }));
            result.Insert(0, new SelectListItem { Text = "--- Chọn trang web ---", Value = "0" });

            var sb = new StringBuilder();
            if (hasEvent)
            {
                var url = Url.Action("GetServersBySite");
                sb.AppendFormat(T("Trang web") + " <select id=\"" + Extensions.Constants.SiteId + "\" name=\"" + Extensions.Constants.SiteId +
                "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"" +
                " var data = $('#" + TableName + "_Container').find('select').serialize();" +
                @"$.ajax({{
	                url: '" + url + @"',
	                data: data,
	                type: 'POST',
	                dataType: 'json',
	                success: function (result) {{
                        $('#" + controlName + @"').empty();
                        if (result != null){{
		                    $.each(result, function(idx, item) {{
                                $('#" + controlName + @"').append($('<option>', {{
                                    value: item.Value,
                                    text: item.Text
                                }}));
                            }});   
                        }} 
	                }}
                }});
                $('#" + TableName + "').jqGrid().trigger('reloadGrid');" +
                "\">");
            }
            else
            {
                sb.AppendFormat(T("Trang web") + " <select id=\"" + Extensions.Constants.SiteId + "\" name=\"" + Extensions.Constants.SiteId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            }

            foreach (var site in result)
            {
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", site.Text, site.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        [Url("admin/vast/get-ads-by-site")]
        public ActionResult GetAdBySite()
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var service = WorkContext.Resolve<IAdvertisementService>();
            var items = service.GetAdBySite(languageCode, siteId);
            var result = new List<SelectListItem>();

            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.Title,
                Value = item.Id.ToString()
            }));

            return Json(result);
        }

        public virtual string BuildSiteAds(bool hasEvent, string controlName)
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }
            var service = WorkContext.Resolve<ISiteService>();
            var list = service.GetRecords(x => x.LanguageCode == languageCode);
            var result = new List<SelectListItem>();
            result.AddRange(list.Select(item => new SelectListItem
            {
                Text = item.Name,
                Value = item.Id.ToString(),
                Selected = item.IsActived
            }));
            result.Insert(0, new SelectListItem { Text = "--- Chọn trang web ---", Value = "0" });

            var sb = new StringBuilder();
            if (hasEvent)
            {
                var url = Url.Action("GetAdsBySite");
                sb.AppendFormat(T("Trang web") + " <select id=\"" + Extensions.Constants.SiteId + "\" name=\"" + Extensions.Constants.SiteId +
                "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"" +
                " var data = $('#" + TableName + "_Container').find('select').serialize();" +
                @"$.ajax({{
	                url: '" + url + @"',
	                data: data,
	                type: 'POST',
	                dataType: 'json',
	                success: function (result) {{
                        $('#" + controlName + @"').empty();
                        if (result != null){{
		                    $.each(result, function(idx, item) {{
                                $('#" + controlName + @"').append($('<option>', {{
                                    value: item.Value,
                                    text: item.Text
                                }}));
                            }});   
                        }} 
	                }}
                }});
                $('#" + TableName + "').jqGrid().trigger('reloadGrid');" +
                "\">");
            }
            else
            {
                sb.AppendFormat(T("Trang web") + " <select id=\"" + Extensions.Constants.SiteId + "\" name=\"" + Extensions.Constants.SiteId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            }

            foreach (var site in result)
            {
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", site.Text, site.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        public virtual string BuildCategories()
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }
            var service = WorkContext.Resolve<ICategoryService>();
            service.LanguageCode = languageCode;
            service.SiteId = siteId;
            var sb = new StringBuilder();

            var categorySelected = GetQueryString(2);
            sb.AppendFormat(T("Chuyên mục") + " <select id=\"" + Extensions.Constants.CategoryId + "\" name=\"" + Extensions.Constants.CategoryId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#"+TableName+"').jqGrid().trigger('reloadGrid');\">");
            var list = service.GetTree();
            foreach (var cate in list)
            {
                if (!string.IsNullOrEmpty(categorySelected) && cate.Id == int.Parse(categorySelected))
                {
                    sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", cate.ChildenName, cate.Id);
                    continue;
                }

                sb.AppendFormat("<option value=\"{1}\">{0}</option>", cate.ChildenName, cate.Id);
            }

            sb.Append("</select>");

            return sb.ToString();
        }

        public virtual IEnumerable<SelectListItem> BindLanguages()
        {
            var service = WorkContext.Resolve<ILanguageService>();
            var items = service.GetActiveLanguages();
            var result = new List<SelectListItem>();
            result.AddRange(items.Where(x => x.Theme == Constants.ThemeDefault).Select(item => new SelectListItem
            {
                Text = item.Name,
                Value = item.CultureCode.ToString(),
                Selected = item.CultureCode == WorkContext.CurrentCulture
            }));

            return result;
        }

        public virtual IEnumerable<SelectListItem> BindSites()
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var service = WorkContext.Resolve<ISiteService>();
            var items = service.GetRecords(x => x.LanguageCode == languageCode);
            var result = new List<SelectListItem>();

            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.Name,
                Value = item.Id.ToString(),
                Selected = item.IsActived
            }));
            result.Insert(0, new SelectListItem { Text = "--- Chọn trang web ---", Value = "0" });

            return result;
        }

        public virtual string BuildDirectors()
        {
            var service = WorkContext.Resolve<IDirectorService>();
            var items = service.GetRecords(x => x.Status == (int)Status.Approved);
            var result = new List<SelectListItem>();
            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.FullName,
                Value = item.Id.ToString()
            }));
            result.Insert(0, new SelectListItem { Text = "--- Đạo diễn phim ---", Value = "0" });

            var directorSelected = GetQueryString(4);
            var sb = new StringBuilder();
            sb.AppendFormat(T("Đạo diễn") + " <select id=\"" + Extensions.Constants.DirectorId + "\" name=\"" + Extensions.Constants.DirectorId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var director in result)
            {
                if (!string.IsNullOrEmpty(directorSelected) && director.Value == directorSelected)
                {
                    sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", director.Text, director.Value);
                    continue;
                }
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", director.Text, director.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        public virtual string BuildActors()
        {
            var service = WorkContext.Resolve<IActorService>();
            var items = service.GetRecords(x => x.Status == (int)Status.Approved);
            var result = new List<SelectListItem>();
            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.FullName,
                Value = item.Id.ToString()
            }));
            result.Insert(0, new SelectListItem { Text = "--- Diễn viên ---", Value = "0" });

            var actorSelected = GetQueryString(5);
            var sb = new StringBuilder();
            sb.AppendFormat(T("Diễn viên") + " <select id=\"" + Extensions.Constants.ActorId + "\" name=\"" + Extensions.Constants.ActorId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var actor in result)
            {
                if (!string.IsNullOrEmpty(actorSelected) && actor.Value == actorSelected)
                {
                    sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", actor.Text, actor.Value);
                    continue;
                }

                sb.AppendFormat("<option value=\"{1}\">{0}</option>", actor.Text, actor.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        public virtual string BuildFilmTypes()
        {
            var service = WorkContext.Resolve<IFilmTypesService>();
            var items = service.GetRecords(x => x.Status == (int)Status.Approved);
            var result = new List<SelectListItem>();
            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.Name,
                Value = item.Id.ToString()
            }));
            result.Insert(0, new SelectListItem { Text = "--- Thể loại phim ---", Value = "0" });

            var filmTypesSelected = GetQueryString(6);
            var sb = new StringBuilder();
            sb.AppendFormat(T("Thể loại phim") + " <select id=\"" + Extensions.Constants.FilmTypesId + "\" name=\"" + Extensions.Constants.FilmTypesId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var item in result)
            {
                if (!string.IsNullOrEmpty(filmTypesSelected) && item.Value == filmTypesSelected)
                {
                    sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", item.Text, item.Value);
                    continue;
                }

                sb.AppendFormat("<option value=\"{1}\">{0}</option>", item.Text, item.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        public virtual string BuildFilmGroups()
        {
            var items = EnumExtensions.GetListItems<FilmGroup>();
            items.Insert(0, new SelectListItem { Text = "--- Nhóm phim ---", Value = "0" });

            var filmGroupSelected = GetQueryString(7);
            var sb = new StringBuilder();
            sb.AppendFormat(T("Nhóm phim") + " <select id=\"" + Extensions.Constants.FilmGroup + "\" name=\"" + Extensions.Constants.FilmGroup + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var group in items)
            {
                if (!string.IsNullOrEmpty(filmGroupSelected) && group.Value == filmGroupSelected)
                {
                    sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", group.Text, group.Value);
                    continue;
                }
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", group.Text, group.Value);
            }
            sb.Append("</select>");
            return sb.ToString();
        }

        public virtual IEnumerable<SelectListItem> BindStatus()
        {
            var items = EnumExtensions.GetListItems<Status>();
            items[0].Selected = true;
            return items;
        }

        public virtual IEnumerable<SelectListItem> BindSex()
        {
            var items = EnumExtensions.GetListItems<Sex>();
            items[0].Selected = true;
            return items;
        }

        public virtual IEnumerable<SelectListItem> BindCities()
        {
            var cityService = WorkContext.Resolve<ICityService>();
            var items = cityService.GetRecords(x => x.Status == (int)Status.Approved).ToList();
            var result = new List<SelectListItem>();
            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.Name,
                Value = item.Id.ToString()
            }));
            result.Insert(0, new SelectListItem { Text = "--- Chọn Quận huyện/Thành phố ---", Value = "0" });
            return result;
        }

        [Url("admin/video-files/get-root-folders")]
        public virtual ActionResult GetRootFolders()
        {
            var serverId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ServerId]))
            {
                serverId = Convert.ToInt32(Request.Form[Extensions.Constants.ServerId]);
            }

            var service = WorkContext.Resolve<IFilmServersService>();
            var items = service.GetRecords(x => x.Id == serverId);
            var result = new List<SelectListItem>();
            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.FolderRoot,
                Value = item.FolderRoot
            }));
            result.Insert(0, new SelectListItem { Text = "--- Tất cả ---", Value = Extensions.Constants.ValueAll });

            return Json(result);
        }

        [Url("admin/get-sites-by-language")]
        public ActionResult GetSitesByLanguage()
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var service = WorkContext.Resolve<ISiteService>();
            var items = service.GetRecords(x => x.LanguageCode == languageCode);
            var result = new List<SelectListItem>();
            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.Name,
                Value = item.Id.ToString()
            }));
            result.Insert(0, new SelectListItem { Text = "--- Chọn trang web ---", Value = "0" });
           
            return Json(result);
        }

        [Url("admin/category/get-servers-by-site")]
        public ActionResult GetServersBySite()
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var service = WorkContext.Resolve<IFilmServersService>();
            var items = service.GetRecords(x => x.LanguageCode == languageCode && x.SiteId == siteId);
            var result = new List<SelectListItem>();

            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.ServerName,
                Value = item.Id.ToString()
            }));
            result.Insert(0, new SelectListItem { Text = T("--- Chọn máy chủ ---"), Value = "0" });

            return Json(result);
        }

        [Url("admin/vast/get-ads-by-site")]
        public ActionResult GetAdsBySite()
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var service = WorkContext.Resolve<IAdvertisementService>();
            var items = service.GetRecords(x => x.LanguageCode == languageCode && x.SiteId == siteId);
            var result = new List<SelectListItem>();

            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.Title,
                Value = item.Id.ToString()
            }));
            result.Insert(0, new SelectListItem { Text = T("--- Chọn quảng cáo ---"), Value = "0" });

            return Json(result);
        }

        [Url("admin/category/get-categories-by-site")]
        public ActionResult GetCategoriesBySite()
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }
            
            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var service = WorkContext.Resolve<ICategoryService>();
            service.LanguageCode = languageCode;
            service.SiteId = siteId;
            var items = service.GetTree();
            var result = new List<SelectListItem>();

            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.ChildenName,
                Value = item.Id.ToString()
            }));
            result.Insert(0, new SelectListItem { Text = T("--- Không chọn ---"), Value = "0" });

            return Json(result);
        }

        [Url("admin/reset-cache")]
        public ActionResult ResetCache()
        {
            var serviceLanguage = WorkContext.Resolve<ILanguageService>();
            var items = serviceLanguage.GetRecords(x => x.Theme == Constants.ThemeDefault);
            if (items != null && items.Count > 0)
            {
                var categoryService = WorkContext.Resolve<ICategoryService>();
                foreach (var language in items)
                {
                    try
                    {
                        categoryService.LanguageCode = language.CultureCode;
                        categoryService.SiteId = 1;
                        categoryService.ResetCache();
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }

                foreach (var language in items)
                {
                    try
                    {
                        categoryService.LanguageCode = language.CultureCode;
                        categoryService.SiteId = 2;
                        categoryService.ResetCache();
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }

            #region Film

            try
            {
                var serviceFilms = WorkContext.Resolve<IFilmService>();
                serviceFilms.LanguageCode = WorkContext.CurrentCulture;
                serviceFilms.SiteId = (int)Site.Home;
                serviceFilms.ResetCache();
                serviceFilms.RefreshFilmJJChannelIntroduce(0);
                serviceFilms.RefreshTVShows(0);
                serviceFilms.RefreshClips(5);
                serviceFilms.RefreshStatistical1(30, 1);
                serviceFilms.RefreshStatistical1(30, 2);
                serviceFilms.RefreshStatistical1(30, 3);

                serviceFilms.RefreshStatistical2(30, 1);
                serviceFilms.RefreshStatistical2(30, 2);
                serviceFilms.RefreshStatistical2(30, 3);

                serviceFilms.RefreshStatistical3(30, 1);
                serviceFilms.RefreshStatistical3(30, 2);
                serviceFilms.RefreshStatistical3(30, 3);

                serviceFilms.RefreshStatistical4(30, 1);
                serviceFilms.RefreshStatistical4(30, 2);
                serviceFilms.RefreshStatistical4(30, 3);

                serviceFilms.RefreshStatistical5(30, 1);
            }
            catch (Exception)
            {

            }
            #endregion

            #region Articles

            try
            {
                var serviceArticles = WorkContext.Resolve<IArticlesService>();
                serviceArticles.LanguageCode = WorkContext.CurrentCulture;
                serviceArticles.SiteId = 1;
                serviceArticles.CategoryId = 0;
                serviceArticles.ResetCache();
                serviceArticles.CategoryId = 60;
                serviceArticles.ResetCache();
                serviceArticles.CategoryId = 61;
                serviceArticles.ResetCache();
                serviceArticles.CategoryId = 62;
                serviceArticles.ResetCache();
            }
            catch (Exception)
            {

            }
            #endregion

            #region Search
            try
            {
                var service = WorkContext.Resolve<ISearchService>();
                service.SearchRestore(1);
                service.SiteId = (int)Site.Home;
                service.ResetCache();
            }
            catch (Exception)
            {

            }
            #endregion

            #region Slider
            var sliderService = WorkContext.Resolve<ISliderService>();
            sliderService.LanguageCode = WorkContext.CurrentCulture;
            sliderService.SiteId = (int) Site.Home;
            var list = EnumExtensions.GetListItems<SliderPages>();
            foreach (var page in list)
            {
                try
                {
                    sliderService.RefreshByPage(int.Parse(page.Value));
                }
                catch (Exception)
                {

                }
            }
            #endregion

            #region Customers
            var customerService = WorkContext.Resolve<ICustomerService>();
            customerService.ResetCacheCustomers();
            #endregion

            return Redirect(Url.Action("Index", "Admin"));
        }
    }
}<file_sep>﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class DownloadCustomerInfo : BaseEntity<long>
    {
        [DataMember]
        [DisplayName("DownloadId")]
        public int DownloadId { get; set; }

        [DataMember]
        [DisplayName("CustomerId")]
        public int CustomerId { get; set; }

        [DataMember]
        [DisplayName("StartDate")]
        public DateTime? StartDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextStartDate
        {
            get
            {
                if (StartDate == null)
                {
                    return "";
                }

                return StartDate.Value.ToString(Extensions.Constants.DateTimeFomatFull);
            }
        }

        [DataMember]
        [DisplayName("EndDate")]
        public DateTime? EndDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextEndDate
        {
            get
            {
                if (EndDate == null)
                {
                    return "";
                }

                return EndDate.Value.ToString(Extensions.Constants.DateTimeFomatFull);
            }
        }

        [DataMember]
        [DisplayName("VipXu")]
        public int VipXu { get; set; }

        [DataMember]
        [DisplayName("Day")]
        public int Day { get; set; }
    }
}<file_sep>﻿using System.ComponentModel;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class SiteInfo : BaseEntity<int>
    {
         [DataMember]
         [DisplayName("Name")]
         public string Name { get; set; }

         [DataMember]
         [DisplayName("LanguageCode")]
         public string LanguageCode { get; set; }

         [DataMember]
         [DisplayName("Url")]
         public string Url { get; set; }

         [DataMember]
         [DisplayName("Domain")]
         public string Domain { get; set; }

         [DataMember]
         [DisplayName("IsActived")]
         public bool IsActived { get; set; }

         [DataMember]
         [DisplayName("Description")]
         public string Description { get; set; }
    }

    public class SiteMap : EntityTypeConfiguration<SiteInfo>, IEntityTypeConfiguration
    {
        public SiteMap()
        {
            ToTable("Modules_Sites");
            HasKey(x => x.Id);
            Property(x => x.LanguageCode).HasMaxLength(50).IsRequired();
            Property(x => x.Name).IsRequired().HasMaxLength(250);
            Property(x => x.Url).HasMaxLength(250);
            Property(x => x.Domain).HasMaxLength(50);
            Property(x => x.IsActived).IsRequired();
            Property(x => x.Description).HasMaxLength(2000);
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using CMSSolutions.ContentManagement.Widgets.Services;
using CMSSolutions.DisplayManagement;
using CMSSolutions.Extensions;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Themes;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = false)]
    public class HomeCategoryController : BaseHomeController
    {
        private readonly dynamic shapeFactory;
        public HomeCategoryController(
            IWorkContextAccessor workContextAccessor, 
            IShapeFactory shapeFactory) 
            : base(workContextAccessor)
        {
            this.shapeFactory = shapeFactory;
            PageIndex = 1;
        }

        [HttpGet]
        [Url("{alias}/c{id}.html")]
        public ActionResult Index(string alias, int id)
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            SiteId = (int)Site.Home;
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;
            serviceCategory.SiteId = SiteId;
            var category = serviceCategory.GetByIdCache(id);
            ViewData[Extensions.Constants.HeaderTitle] = category.Name;
            ViewData[Extensions.Constants.HeaderDescription] = category.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = category.Tags;

            if (Request.QueryString["trang"] != null)
            {
                PageIndex = int.Parse(Request.QueryString["trang"]);
            }
            PageSize = 40;

            BuildModulesCategory(category);

            return View();
        }

        [HttpGet]
        [Url("su-kien/phim-dang-hot.html")]
        public ActionResult FilmHot()
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            SiteId = (int)Site.Home;
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;
            serviceCategory.SiteId = (int)Site.Home;
            var category = serviceCategory.GetByIdCache((int)FixCategories.FilmHot);
            ViewData[Extensions.Constants.HeaderTitle] = category.Name;
            ViewData[Extensions.Constants.HeaderDescription] = category.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = category.Tags;

            if (Request.QueryString["trang"] != null)
            {
                PageIndex = int.Parse(Request.QueryString["trang"]);
            }
            PageSize = 16;

            BuildModules();

            return View("FilmHot");
        }

        private string BuildBreadcrumb(CategoryInfo category)
        {
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;
            serviceCategory.SiteId = (int)Site.Home;

            var html = new StringBuilder();
            html.Append("<div class=\"mh-breadcrumb-dv\">");
            html.Append("<div>");
            html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span><img width=\"22\" src=\"/Images/themes/ico-home_trans.png\"></span></a>", "Dành cho víp", "/");
            html.Append("</div>/ ");
            if (category.ParentId > 0)
            {
                var parent = serviceCategory.GetByIdCache(category.ParentId);
                html.Append("<div>");
                html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span>{0}</span></a>", parent.ShortName, Url.Action("Index", "HomeCategory", new { @alias = parent.Alias, @id = parent.Id }));
                html.Append("</div>/ ");
            }
            html.Append("<div>");
            html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span>{0}</span></a>", category.ShortName, "#");
            html.Append("</div>");

            html.Append("</div>");
            return html.ToString();
        }
        
        private void BuildModulesCategory(CategoryInfo category)
        {
            var widget = WorkContext.Resolve<IWidgetService>();
            var viewRenderer = new ViewRenderer { Context = ControllerContext };
            if (!IsVip)
            {
                #region BannerPageLeft
                var bannerPageLeft = widget.GetWidget(HomeWidgets.BannerPageLeft.ToString());
                if (bannerPageLeft != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageLeft;
                    WorkContext.Layout.AdBannerPageLeft(widgetShape);
                }
                #endregion

                #region BannerPageCenter
                var bannerPageCenter = widget.GetWidget(HomeWidgets.BannerPageCenter.ToString());
                if (bannerPageCenter != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageCenter;
                    WorkContext.Layout.AdBannerPageCenter(widgetShape);
                }
                #endregion

                #region BannerPageRight
                var bannerPageRight = widget.GetWidget(HomeWidgets.BannerPageRight.ToString());
                if (bannerPageRight != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageRight;
                    WorkContext.Layout.AdBannerPageRight(widgetShape);
                }
                #endregion

                #region BannerContentLeftSeventh
                var bannerContentLeftSeventh = widget.GetWidget(HomeWidgets.BannerContentLeftSeventh.ToString());
                if (bannerContentLeftSeventh != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerContentLeftSeventh;
                    WorkContext.Layout.AdBannerContentLeftSeventh(widgetShape);
                }
                #endregion

                #region BannerRightFirst
                var bannerRightFirst = widget.GetWidget(HomeWidgets.BannerRightFirst.ToString());
                if (bannerRightFirst != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerRightFirst;
                    WorkContext.Layout.AdBannerRightFirst(widgetShape);
                }
                #endregion

                #region BannerRightSecond
                var bannerRightSecond = widget.GetWidget(HomeWidgets.BannerRightSecond.ToString());
                if (bannerRightSecond != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerRightSecond;
                    WorkContext.Layout.AdBannerRightSecond(widgetShape);
                }
                #endregion

                #region BannerRightThird
                var bannerRightThird = widget.GetWidget(HomeWidgets.BannerRightThird.ToString());
                if (bannerRightThird != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerRightThird;
                    WorkContext.Layout.AdBannerRightThird(widgetShape);
                }
                #endregion

                #region BannerRightFourth
                var bannerRightFourth = widget.GetWidget(HomeWidgets.BannerRightFourth.ToString());
                if (bannerRightFourth != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerRightFourth;
                    WorkContext.Layout.AdBannerRightFourth(widgetShape);
                }
                #endregion
            }
            else
            {
                #region BannerPageLeftVip
                var bannerPageLeftVip = widget.GetWidget(HomeWidgets.BannerPageLeftVip.ToString());
                if (bannerPageLeftVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageLeftVip;
                    WorkContext.Layout.AdBannerPageLeftVip(widgetShape);
                }
                #endregion

                #region BannerPageCenterVip
                var bannerPageCenterVip = widget.GetWidget(HomeWidgets.BannerPageCenterVip.ToString());
                if (bannerPageCenterVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageCenterVip;
                    WorkContext.Layout.AdBannerPageCenterVip(widgetShape);
                }
                #endregion

                #region BannerPageRightVip
                var bannerPageRightVip = widget.GetWidget(HomeWidgets.BannerPageRightVip.ToString());
                if (bannerPageRightVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageRightVip;
                    WorkContext.Layout.AdBannerPageRightVip(widgetShape);
                }
                #endregion
            }

            #region HomeSliderBanner

            if (category.Id == 2 || category.ParentId == 2)
            {
                var modelSlider = new DataViewerModel { Data = BuildSlider(SiteId, (int)SliderPages.CatetegoryPhimLe) };
                var viewSlider = viewRenderer.RenderPartialView(Extensions.Constants.SliderBannerFilePath, modelSlider);
                WorkContext.Layout.SliderBanner.Add(new MvcHtmlString(viewSlider));
            }

            if (category.Id == 3 || category.ParentId == 3)
            {
                var modelSlider = new DataViewerModel { Data = BuildSlider(SiteId, (int)SliderPages.CatetegoryPhimBo) };
                var viewSlider = viewRenderer.RenderPartialView(Extensions.Constants.SliderBannerFilePath, modelSlider);
                WorkContext.Layout.SliderBanner.Add(new MvcHtmlString(viewSlider));
            }

            var viewRegisterResource = viewRenderer.RenderPartialView(Extensions.Constants.RegisterResourceFilePath, null);
            WorkContext.Layout.RegisterResource.Add(new MvcHtmlString(viewRegisterResource));
            
            #endregion

            #region HomeFooterLogoInformation
            var homeFooterLogoInformation = widget.GetWidget(HomeWidgets.HomeFooterLogoInformation.ToString());
            if (homeFooterLogoInformation != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = homeFooterLogoInformation;
                WorkContext.Layout.FooterLogoInformation(widgetShape);
            }
            #endregion
            var type = 0;
            if (category.Id == (int)FixCategories.FilmLe || category.ParentId == (int)FixCategories.FilmLe)
            {
                type = 1;
                #region DisplayStatistic1
                var modelStatistic1 = new DataViewCategoryModel
                {
                    Type = (int)HomeDisplayFilmType.StatisticalFilmRetail,
                    Title = "PHIM LẺ XEM NHIỀU NHẤT"
                };
                var viewStatistic1 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic1FilePath, modelStatistic1);
                WorkContext.Layout.DisplayStatistic1.Add(new MvcHtmlString(viewStatistic1));
                #endregion
            }

            if (category.Id == (int)FixCategories.FilmBo || category.ParentId == (int)FixCategories.FilmBo)
            {
                type = 2;
                #region DisplayStatistic2
                var modelStatistic2 = new DataViewCategoryModel
                {
                    Type = (int)HomeDisplayFilmType.StatisticalLengthEpisodes,
                    Title = "PHIM BỘ XEM NHIỀU NHẤT"
                };
                var viewStatistic2 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic2FilePath, modelStatistic2);
                WorkContext.Layout.DisplayStatistic2.Add(new MvcHtmlString(viewStatistic2));
                #endregion
            }

            #region SocialNetwork
            var socialNetwork = widget.GetWidget(HomeWidgets.DisplaySocialNetwork.ToString());
            if (socialNetwork != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = socialNetwork;
                WorkContext.Layout.DisplaySocialNetwork(widgetShape);
            }
            #endregion

            #region Tags
            var serviceTags = WorkContext.Resolve<ITagService>();
            var modelTags = new TagViewModel { ListTags = serviceTags.GetDisplayTags() };
            var viewTags = viewRenderer.RenderPartialView(Extensions.Constants.TagViewFilePath, modelTags);
            WorkContext.Layout.DisplayTags.Add(new MvcHtmlString(viewTags));
            #endregion

            #region CategoryContentFirst
            var modelFirst = new DataViewCategoryModel();
            var countryService = WorkContext.Resolve<ICountryService>();
            var filmTypesService = WorkContext.Resolve<IFilmTypesService>();
            modelFirst.Breadcrumb = BuildBreadcrumb(category);
            modelFirst.ListCountries = countryService.GetRecords().ToList();
            modelFirst.ListFilmTypes = filmTypesService.GetByType(WorkContext.CurrentCulture, SiteId, 1).ToList();
            modelFirst.SearchOrderBy = EnumExtensions.GetListItems<SearchOrderBy>();

            modelFirst.SelectedFilmTypes = 0;
            if (Request.QueryString["theloaiphim"] != null)
            {
                modelFirst.SelectedFilmTypes = int.Parse(Request.QueryString["theloaiphim"]);
            }

            modelFirst.SelectedCountry = 0;
            if (Request.QueryString["quocgia"] != null)
            {
                modelFirst.SelectedCountry = int.Parse(Request.QueryString["quocgia"]);
            }

            modelFirst.SelectedOrderBy = "0";
            if (Request.QueryString["sortOrder"] != null)
            {
                modelFirst.SelectedOrderBy = Request.QueryString["sortOrder"];
            }

            modelFirst.SelectedSortBy = (int) SearchSortBy.DESC;
            if (Request.QueryString["sortBy"] != null)
            {
                modelFirst.SelectedSortBy = int.Parse(Request.QueryString["sortBy"]);
            }
            modelFirst.SliderName = "DataListView";
            modelFirst.CurrentCategory = category;
            modelFirst.PageIndex = PageIndex;
            modelFirst.PageSize = PageSize;

            var service = WorkContext.Resolve<IFilmService>();
            service.SiteId = SiteId;
            service.LanguageCode = WorkContext.CurrentCulture;
            var totalRow = 0;
            var listFilmCategory = service.GetByCategoryId(
                             SiteId, WorkContext.CurrentCulture,
                             category.ParentId > 0 ? category.Id : 0,
                             category.ParentId == 0 ? category.Id : 0,
                             modelFirst.SelectedFilmTypes,
                             modelFirst.SelectedCountry,
                             type,
                             int.Parse(modelFirst.SelectedOrderBy), modelFirst.SelectedSortBy,
                             modelFirst.PageIndex, modelFirst.PageSize, out totalRow);
            modelFirst.TotalRow = totalRow;
            modelFirst.ListFilms = listFilmCategory;
            modelFirst.Type = type;
            var viewFilmFirst = viewRenderer.RenderPartialView(Extensions.Constants.CategoryListViewViewFilePath, modelFirst);
            WorkContext.Layout.CategoryContentLeftFirst.Add(new MvcHtmlString(viewFilmFirst));
            #endregion
        }

        public override void BuildModules()
        {
            var widget = WorkContext.Resolve<IWidgetService>();
            var viewRenderer = new ViewRenderer { Context = ControllerContext };
            if (!IsVip)
            {

            }
            else
            {
                #region BannerPageLeftVip
                var bannerPageLeftVip = widget.GetWidget(HomeWidgets.BannerPageLeftVip.ToString());
                if (bannerPageLeftVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageLeftVip;
                    WorkContext.Layout.AdBannerPageLeftVip(widgetShape);
                }
                #endregion

                #region BannerPageCenterVip
                var bannerPageCenterVip = widget.GetWidget(HomeWidgets.BannerPageCenterVip.ToString());
                if (bannerPageCenterVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageCenterVip;
                    WorkContext.Layout.AdBannerPageCenterVip(widgetShape);
                }
                #endregion

                #region BannerPageRightVip
                var bannerPageRightVip = widget.GetWidget(HomeWidgets.BannerPageRightVip.ToString());
                if (bannerPageRightVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageRightVip;
                    WorkContext.Layout.AdBannerPageRightVip(widgetShape);
                }
                #endregion
            }

            #region HomeSliderBanner
            var modelSlider = new DataViewerModel { Data = BuildSlider(SiteId, (int)SliderPages.FilmHot) };
            var viewSlider = viewRenderer.RenderPartialView(Extensions.Constants.SliderBannerFilePath, modelSlider);
            WorkContext.Layout.SliderBanner.Add(new MvcHtmlString(viewSlider));

            var viewRegisterResource = viewRenderer.RenderPartialView(Extensions.Constants.RegisterResourceFilePath, null);
            WorkContext.Layout.RegisterResource.Add(new MvcHtmlString(viewRegisterResource));
            #endregion

            #region HomeFooterLogoInformation
            var homeFooterLogoInformation = widget.GetWidget(HomeWidgets.HomeFooterLogoInformation.ToString());
            if (homeFooterLogoInformation != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = homeFooterLogoInformation;
                WorkContext.Layout.FooterLogoInformation(widgetShape);
            }
            #endregion

            #region CategoryContentFirst
            var modelFirst = new DataViewCategoryModel
            {
                HtmlData = "",
                Title = "Phim Đang HOT",
                UrlNext = "javascript: void(0);",
                SliderName = "FilmHot",
                PageIndex = PageIndex,
                PageSize = PageSize
            };
           var data = BuilHtml(modelFirst);
            var viewFilmFirst = viewRenderer.RenderPartialView(Extensions.Constants.HomeFilmHotViewFilePath, modelFirst);
            WorkContext.Layout.CategoryContentLeftFirst.Add(new MvcHtmlString(viewFilmFirst));
            #endregion

            #region HomeFacebookFanpage
            var modelSliderOne = new DataViewCategoryModel();
            modelSliderOne.Data = data == null ? "[]" : Utilities.ConvertObjectToJson(data.Select(x => x.Id).ToList());
            var viewSliderOne = viewRenderer.RenderPartialView(Extensions.Constants.SliderOneViewFilePath, modelSliderOne);
            WorkContext.Layout.AdFacebookFanpage.Add(new MvcHtmlString(viewSliderOne));
            #endregion

            #region SocialNetwork
            var socialNetwork = widget.GetWidget(HomeWidgets.DisplaySocialNetwork.ToString());
            if (socialNetwork != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = socialNetwork;
                WorkContext.Layout.DisplaySocialNetwork(widgetShape);
            }
            #endregion
        }

        private IEnumerable<FilmInfo> BuilHtml(DataViewCategoryModel model)
        {
            var service = WorkContext.Resolve<IFilmService>();
            service.SiteId = SiteId;
            service.LanguageCode = WorkContext.CurrentCulture;
            var totalRow = 0;
            var listFilmHot = service.GetFilmHot(model.PageIndex, model.PageSize, out totalRow);
            model.TotalRow = totalRow;
            var html = new StringBuilder();
            if (listFilmHot != null && listFilmHot.Count > 0)
            {
                html.Append("<div>");
                html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">");
                html.Append("<li>");
                for (int i = 0; i < listFilmHot.Count; i++)
                {
                    html.Append(BuildItem(listFilmHot[i], i, true));
                }
                html.Append("</li>");
                html.Append("</ul>");
                html.Append("</div>");
            }

            model.HtmlData = html.ToString();

            return listFilmHot != null ? listFilmHot.ToList(): null;
        }
    }
}
<file_sep>using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IFilmTypesService : IGenericService<FilmTypesInfo, int>, IDependency
    {
        IList<FilmTypesInfo> GetPaged(string languageCode, int siteId, int status, int pageIndex, int pageSize, out int totals);

        IList<FilmTypesInfo> GetByType(string languageCode, int siteId, int type);
    }
    
    public class FilmTypesService : GenericService<FilmTypesInfo, int>, IFilmTypesService
    {
        public FilmTypesService(IRepository<FilmTypesInfo, int> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public IList<FilmTypesInfo> GetPaged(string languageCode, int siteId, int status, int pageIndex, int pageSize, out int totals)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", siteId),
                AddInputParameter("@LanguageCode", languageCode),
                AddInputParameter("@Status", status),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmTypesInfo>("sp_FilmTypes_Search_Paged", "@TotalRecord", out totals, list.ToArray());
        }

        public IList<FilmTypesInfo> GetByType(string languageCode, int siteId, int type)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", siteId),
                AddInputParameter("@LanguageCode", languageCode),
                AddInputParameter("@Type", type)
            };

            return ExecuteReader<FilmTypesInfo>("sp_FilmTypes_GetByType", list.ToArray());
        }
    }
}
<file_sep>﻿using System.Web.Mvc;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminCountryController : BaseAdminController
    {
        public AdminCountryController(IWorkContextAccessor workContextAccessor) : 
                base(workContextAccessor)
        {
            TableName = "tblCountries";
        }

        [Url("admin/country")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý nước sản xuất phim"), Url = "#" });

            var result = new ControlGridFormResult<CountryInfo>
            {
                Title = T("Quản lý nước sản xuất phim"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetCountries,
                DefaultPageSize = WorkContext.DefaultPageSize,
                EnablePaginate = true,
                UpdateActionName = "Update",
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml,
                ClientId = TableName,
                ActionsColumnWidth = 100
            };

            result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true);

            result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(60);
            result.AddColumn(x => x.Code, T("Mã nước"));
            result.AddColumn(x => x.Name, T("Tên nước"));

            result.AddAction().HasText(T("Thêm mới"))
              .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
              .HasButtonStyle(ButtonStyle.Primary)
              .HasBoxButton(false)
              .HasCssClass(Constants.RowLeft)
              .HasRow(true)
              .ShowModalDialog();

            result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
                 .HasText(T("Sửa"))
                 .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                 .HasButtonStyle(ButtonStyle.Default)
                 .HasButtonSize(ButtonSize.ExtraSmall)
                 .ShowModalDialog();

            //result.AddRowAction(true)
            //    .HasText(T("Xóa"))
            //    .HasName("Delete")
            //    .HasValue(x => x.Id)
            //    .HasButtonStyle(ButtonStyle.Danger)
            //    .HasButtonSize(ButtonSize.ExtraSmall)
            //    .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            //result.AddReloadEvent("DELETE_ENTITY_COMPLETE");
            return result;
        }

        private ControlGridAjaxData<CountryInfo> GetCountries(ControlGridFormRequest options)
        {
            var searchText = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText]))
            {
                searchText = Request.Form[Extensions.Constants.SearchText];
            }

            int totals;
            var items = WorkContext.Resolve<ICountryService>().SearchPaged(searchText, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<CountryInfo>(items, totals);

            return result;
        }

        [Themed(false)]
        [Url("admin/country/edit/{id}")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý nước sản xuất phim"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin nước sản xuất phim"), Url = "#" });

            var service = WorkContext.Resolve<ICountryService>();
            var model = new CountryModel();
            if (id > 0)
            {
                model = service.GetById(id);
            }

            var result = new ControlFormResult<CountryModel>(model)
            {
                Title = T("Thông tin nước sản xuất phim"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                ShowCancelButton = true,
                ShowBoxHeader = false,
                CancelButtonText = T("Đóng"),
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/country/update")]
        public ActionResult Update(CountryModel model)
        {
            if (!ModelState.IsValid)
            {
                return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var service = WorkContext.Resolve<ICountryService>();
            CountryInfo item = model.Id == 0 ? new CountryInfo() : service.GetById(model.Id);
            if (service.CheckExist(model.Id, model.Code))
            {
                return new AjaxResult()
                    .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                    .Alert(T("Mã nước sản xuất đã tồn tại!"));
            }

            if (service.CheckExist(model.Id, model.Name))
            {
                return new AjaxResult()
                    .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                    .Alert(T("Tên nước sản xuất đã tồn tại!"));
            }

            item.Code = model.Code;
            item.Name = model.Name;
            service.Save(item);

            return new AjaxResult()
                .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"))
                .CloseModalDialog();
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<ICountryService>();
            var item = service.GetById(id);
            service.Delete(item);

			return new AjaxResult().NotifyMessage("DELETE_ENTITY_COMPLETE");
        }
    }
}
<file_sep>using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface ISearchService : IGenericService<SearchInfo, long>, IDependency
    {
        int SiteId { get; set; }

        SearchInfo GetBySearchId(string searchId, int type);

        IList<SearchInfo> Search(List<SearchCondition> conditions, int pageIndex, int pageSize, ref int total);

        IList<SearchInfo> ResetCache();

        void SearchRestore(int type);
    }

    public class SearchService : GenericService<SearchInfo, long>, ISearchService
    {
        public SearchService(IRepository<SearchInfo, long> repository, 
            IEventBus eventBus) 
            : base(repository, eventBus)
        {
            
        }

        public IList<SearchInfo> Search(List<SearchCondition> conditions, int pageIndex, int pageSize, ref int total)
        {
            var service = new LuceneService();
            return service.Search(conditions, true, pageIndex, pageSize, ref total);
        }

        public int SiteId { get; set; }

        public SearchInfo GetBySearchId(string searchId, int type)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SearchId", searchId),
                AddInputParameter("@Type", type)
            };

            return ExecuteReaderRecord<SearchInfo>("sp_Search_GetDetails", list.ToArray());
        }

        public void SearchRestore(int type)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Type", type)
            };

            ExecuteNonQuery("sp_AutoSearh", list.ToArray());
        }

        public IList<SearchInfo> ResetCache()
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId)
            };

            var data = ExecuteReader("sp_Search_BuildJson", list.ToArray());
            var service = new LuceneService {SiteId = SiteId};
            service.AddUpdateLuceneIndex(data.Tables[0]);
            return null;
        }
    }
}
<file_sep>﻿using System;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class VastModel
    {
        public VastModel()
        {
            KeyCode = Guid.NewGuid().ToString().Replace("-", string.Empty);
            AdSystemVersion = "3.0";
            Skipoffset = "00:00:05";
            Duration = "00:00:30.03";
            MediaFileBitrate = 660;
            MediaFileDelivery = "progressive";
            MediaFileHeight = 480;
            MediaFileWidth = 854;
            MediaFileMaintainAspectRatio = true;
            MediaFileScalable = true;
            MediaFileType = "video/mp4";
        }

        [ControlHidden]
        public int Id { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.AdId + "').empty();")]
        public string LanguageCode { get; set; }

        [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public int SiteId { get; set; }

        [ControlCascadingDropDown(LabelText = "Quảng cáo", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public int AdId { get; set; }

        [ControlText(Type = ControlText.TextBox, ReadOnly = true, LabelText = "Mã Vast", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public string KeyCode { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Version", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public string AdSystemVersion { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Thời gian bỏ qua", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public string Skipoffset { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Thời gian chạy", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public string Duration { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Tiêu đề", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 2)]
        public string AdSystemValue { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Mô tả", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 2)]
        public string AdTitle { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn lỗi", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)]
        public string LinkError { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn impression", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 4)]
        public string LinkImpression { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn đơn vị quảng cáo", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 5)]
        public string LinkClickThrough { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn tracking 1", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 6)]
        public string TrackingValue1 { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn tracking 2", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 7)]
        public string TrackingValue2 { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn tracking 3", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 8)]
        public string TrackingValue3 { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn tracking 4", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 9)]
        public string TrackingValue4 { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn tracking 5", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 10)]
        public string TrackingValue5 { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn tracking 6", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 11)]
        public string TrackingValue6 { get; set; }

        [ControlNumeric(LabelText = "Bitrate", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 12)]
        public int MediaFileBitrate { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Delivery", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 12)]
        public string MediaFileDelivery { get; set; }

        [ControlNumeric(LabelText = "Chiều cao", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 12)]
        public int MediaFileHeight { get; set; }

        [ControlNumeric(LabelText = "Chiều rộng", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 12)]
        public int MediaFileWidth { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Duy trì tỷ lệ", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 13)]
        public bool MediaFileMaintainAspectRatio { get; set; }
        
        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Scalable", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 13)]
        public bool MediaFileScalable { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn video quảng cáo", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol10, ContainerRowIndex = 14)]
        public string MediaFileValue { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Loại file", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 14)]
        public string MediaFileType { get; set; }

        public static implicit operator VastModel(VastInfo entity)
        {
            return new VastModel
            {
                Id = entity.Id,
                LanguageCode =  entity.LanguageCode,
                SiteId = entity.SiteId,
                KeyCode = entity.KeyCode,
                AdId = entity.AdId,
                AdSystemVersion = entity.AdSystemVersion,
                AdSystemValue = entity.AdSystemValue,
                AdTitle = entity.AdTitle,
                LinkError = entity.LinkError,
                LinkImpression = entity.LinkImpression,
                Skipoffset = entity.Skipoffset,
                Duration = entity.Duration,
                LinkClickThrough = entity.LinkClickThrough,
                TrackingValue1 = entity.TrackingValue1,
                TrackingValue2 = entity.TrackingValue2,
                TrackingValue3 = entity.TrackingValue3,
                TrackingValue4 = entity.TrackingValue4,
                TrackingValue5 = entity.TrackingValue5,
                TrackingValue6 = entity.TrackingValue6,
                MediaFileBitrate = entity.MediaFileBitrate,
                MediaFileDelivery = entity.MediaFileDelivery,
                MediaFileHeight = entity.MediaFileHeight,
                MediaFileWidth = entity.MediaFileWidth,
                MediaFileMaintainAspectRatio = entity.MediaFileMaintainAspectRatio,
                MediaFileScalable = entity.MediaFileScalable,
                MediaFileType = entity.MediaFileType,
                MediaFileValue = entity.MediaFileValue
            };
        }

    }
}
<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class TagModel
    {
        public TagModel()
        {
            IsDisplay = true;
        }

        [ControlHidden]
        public int Id { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Tiêu đề", PlaceHolder = "Tối đa 250 ký tự", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public string Name { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, LabelText = "Tên không dấu", PlaceHolder = "Hệ thống tự động sinh.", MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)]
        public string Alias { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Được hiển thị", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 3)]
        public bool IsDisplay { get; set; }

        public static implicit operator TagModel(TagInfo other)
        {
            if (other == null)
            {
                return null;
            }

            return new TagModel
            {
                Id = other.Id,
                Name = other.Name,
                Alias = other.Alias,
                IsDisplay = other.IsDisplay
            };
        }
    }
}<file_sep>using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IEpisodesService : IGenericService<EpisodeInfo, int>, IDependency
    {
        bool CheckExist(int id, string keyword);

        IList<EpisodeInfo> GetPaged(string languageCode, int siteId, string keyword, int status, int pageIndex, int pageSize, out int totals);

        IList<EpisodeInfo> GetAll(string languageCode, int siteId, int status);
    }
    
    public class EpisodeService : GenericService<EpisodeInfo, int>, IEpisodesService
    {
        public EpisodeService(IRepository<EpisodeInfo, int> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public bool CheckExist(int id, string keyword)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Id", id),
                AddInputParameter("@Keyword", keyword)
            };
            var result = (int)ExecuteReaderResult("sp_Episodes_CheckName", list.ToArray());

            return result > 0;
        }

        public IList<EpisodeInfo> GetPaged(string languageCode, int siteId, string keyword, int status, int pageIndex, int pageSize, out int totals)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", siteId),
                AddInputParameter("@LanguageCode", languageCode),
                AddInputParameter("@Keyword", keyword),
                AddInputParameter("@Status", status),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<EpisodeInfo>("sp_Episodes_Search_Paged", "@TotalRecord", out totals, list.ToArray());
        }

        public IList<EpisodeInfo> GetAll(string languageCode, int siteId, int status)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", siteId),
                AddInputParameter("@LanguageCode", languageCode),
                AddInputParameter("@Status", status)
            };

            return ExecuteReader<EpisodeInfo>("sp_Episodes_GetAll", list.ToArray());
        }
    }
}
<file_sep>﻿using System.Xml.Serialization;

namespace CMSSolutions.Websites.Models
{
    #region ads
    [XmlRoot("VAST")]
    public class Vast
    {
        [XmlElement("Ad")]
        public Ads ItemAds { get; set; }
    }

    [XmlRoot("Ad")]
    public class Ads
    {
        [XmlAttributeAttribute("id")]
        public int Id { get; set; }

        [XmlElement("InLine")]
        public InLine ObjectInLine { get; set; }
    }

    [XmlRoot("InLine")]
    public class InLine
    {
        [XmlElement("AdSystem")]
        public AdSystem ObjectAdSystem { get; set; }

        [XmlElement("AdTitle")]
        public string AdTitle { get; set; }

        [XmlElement("Error")]
        public string Error { get; set; }

        [XmlElement("Impression")]
        public string Impression { get; set; }

        [XmlElement("Creatives")]
        public Creatives Creatives { get; set; }
    }

    [XmlRoot("AdSystem")]
    public class AdSystem
    {
        [XmlAttributeAttribute("version")]
        public string Version { get; set; }

        [XmlText]
        public string Value { get; set; }
    }

    [XmlRoot("Creatives")]
    public class Creatives
    {
        [XmlElement("Creative")]
        public Creative[] ListCreatives { get; set; }
    }

    [XmlRoot("Creative")]
    public class Creative
    {
        [XmlElement("Linear")]
        public Linear ObjectLinear { get; set; }
    }

    [XmlRoot("Linear")]
    public class Linear
    {
        [XmlAttributeAttribute("skipoffset")]
        public string Skipoffset { get; set; }

        [XmlElement("Duration")]
        public string Duration { get; set; }

        [XmlElement("VideoClicks")]
        public VideoClicks VideoClicks { get; set; }

        [XmlElement("TrackingEvents")]
        public TrackingEvents TrackingEvents { get; set; }

        [XmlElement("MediaFiles")]
        public MediaFiles MediaFiles { get; set; }
    }

    [XmlRoot("VideoClicks")]
    public class VideoClicks
    {
        [XmlElement("ClickThrough")]
        public string ClickThrough { get; set; }
    }

    public class TrackingEvents
    {
        [XmlElement("Tracking")]
        public Tracking[] LisTrackings { get; set; }
    }

    [XmlRoot("Tracking")]
    public class Tracking
    {
        [XmlAttributeAttribute("event")]
        public string Event { get; set; }

        [XmlText]
        public string Value { get; set; }
    }

    [XmlRoot("MediaFiles")]
    public class MediaFiles
    {
        [XmlElement("MediaFile")]
        public MediaFile[] ListMediaFiles { get; set; }
    }

    [XmlRoot("MediaFile")]
    public class MediaFile
    {
        [XmlAttributeAttribute("bitrate")]
        public int Bitrate { get; set; }

        [XmlAttributeAttribute("delivery")]
        public string Delivery { get; set; }

        [XmlAttributeAttribute("height")]
        public int Height { get; set; }

        [XmlAttributeAttribute("width")]
        public int Width { get; set; }

        [XmlAttributeAttribute("maintainAspectRatio")]
        public bool MaintainAspectRatio { get; set; }

        [XmlAttributeAttribute("scalable")]
        public bool Scalable { get; set; }

        [XmlAttributeAttribute("type")]
        public string Type { get; set; }

        [XmlText]
        public string Value { get; set; }
    }
    #endregion

    #region vplugin xml
    [XmlRoot("Ad")]
    public class Ad
    {
        [XmlElement("link")]
        public string Link { get; set; }

        [XmlElement("type")]
        public string Type { get; set; }

        [XmlElement("id")]
        public string Id { get; set; }

        [XmlElement("click")]
        public string Click { get; set; }

        [XmlElement("duration")]
        public int Duration { get; set; }

        [XmlElement("position")]
        public int Position { get; set; }

        [XmlElement("skip")]
        public int Skip { get; set; }
    }

    [XmlRoot("vplugin")]
    public class Vplugin
    {
        [XmlElement("Ad")]
        public Ad[] ListAds { get; set; }
    }
    #endregion
}<file_sep>﻿using System.Collections.Generic;
using System.Xml;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Extensions
{
    public class PicasaService
    {
        public List<PicasaInfo> ParseRssFile(string albumLink,string currentLink)
        {
            var rssXmlDoc = new XmlDocument();
            rssXmlDoc.Load(albumLink);
            XmlNodeList rssNodes = rssXmlDoc.SelectNodes("rss/channel/item");
            var list = new List<PicasaInfo>();
            foreach (XmlNode rssNode in rssNodes)
            {
                XmlNode rssSubNode = rssNode.SelectSingleNode("link");
                if (rssSubNode == null)
                {
                    continue;
                }

                string link = rssSubNode.InnerText;
                if (link != currentLink)
                {
                    continue;
                }

                rssSubNode = rssNode.LastChild;
                XmlNodeList listUrl = rssSubNode.ChildNodes;
                foreach (XmlNode item in listUrl)
                {
                    if (item == null || item.Attributes == null || item.Attributes.Count <= 0)
                    {
                        continue;
                    }

                    if (item.Attributes["medium"] == null)
                    {
                        continue;
                    }

                    string medium = item.Attributes["medium"].Value;
                    if (!string.IsNullOrEmpty(medium) && medium == "video")
                    {
                        var info = new PicasaInfo();
                        info.Medium = medium;
                        string url = item.Attributes["url"].Value;
                        info.Url = url.Replace("&amp;", "&");
                        string width = item.Attributes["width"].Value;
                        info.Width = int.Parse(width);
                        string height = item.Attributes["height"].Value;
                        info.Height = int.Parse(height);
                        string type = item.Attributes["type"].Value;
                        info.Type = type;

                        list.Add(info);
                    }
                }
            }

            return list;
        }
    }
}<file_sep>﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using CMSSolutions.ContentManagement.Widgets.Services;
using CMSSolutions.DisplayManagement;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Themes;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = false)]
    public class HomeSearchController : BaseHomeController
    {
        private readonly dynamic shapeFactory;
        public HomeSearchController(IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory) 
            : base(workContextAccessor)
        {
            this.shapeFactory = shapeFactory;
            PageIndex = 1;
        }

        [HttpGet]
        [Url("tim-kiem")]
        public ActionResult Index()
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            string keyword = Request.QueryString["keyword"];
            BuildModulesSearch(keyword);

            return View();
        }

        private void BuildModulesSearch(string keyword)
        {
            var widget = WorkContext.Resolve<IWidgetService>();
            var viewRenderer = new ViewRenderer { Context = ControllerContext };
            if (!IsVip)
            {
                
            }

            #region HomeFooterLogoInformation
            var homeFooterLogoInformation = widget.GetWidget(HomeWidgets.HomeFooterLogoInformation.ToString());
            if (homeFooterLogoInformation != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = homeFooterLogoInformation;
                WorkContext.Layout.FooterLogoInformation(widgetShape);
            }
            #endregion

            #region SocialNetwork
            var socialNetwork = widget.GetWidget(HomeWidgets.DisplaySocialNetwork.ToString());
            if (socialNetwork != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = socialNetwork;
                WorkContext.Layout.DisplaySocialNetwork(widgetShape);
            }
            #endregion

            #region BannerRightFirst
            var view = viewRenderer.RenderPartialView(Extensions.Constants.DivDisplayFilePath, null);
            WorkContext.Layout.AdBannerRightFirst.Add(new MvcHtmlString(view));
            #endregion

            #region HomeFacebookFanpage
            var homeFacebookFanpage = widget.GetWidget(HomeWidgets.HomeFacebookFanpage.ToString());
            if (homeFacebookFanpage != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = homeFacebookFanpage;
                WorkContext.Layout.AdFacebookFanpage(widgetShape);
            }
            #endregion

            #region News
            var viewNews = viewRenderer.RenderPartialView(Extensions.Constants.NewsViewFilePath, null);
            WorkContext.Layout.DisplayNews.Add(new MvcHtmlString(viewNews));
            #endregion

            #region Tags
            var serviceTags = WorkContext.Resolve<ITagService>();
            var modelTags = new TagViewModel { ListTags = serviceTags.GetDisplayTags() };
            var viewTags = viewRenderer.RenderPartialView(Extensions.Constants.TagViewFilePath, modelTags);
            WorkContext.Layout.DisplayTags.Add(new MvcHtmlString(viewTags));
            #endregion

            #region CategoryContentFirst
            if (Request.QueryString["trang"] != null)
            {
                PageIndex = int.Parse(Request.QueryString["trang"]);
            }
            PageSize = 100;
            SiteId = (int)Site.Home;
            ViewData[Extensions.Constants.HeaderTitle] = "Từ khóa " + keyword + " trang " + PageIndex;
            ViewData[Extensions.Constants.HeaderDescription] = "xem phim, phim hay, phim online, phim hd, phim miễn phí, xem phim hay, xem phim online, xem phim hd, xem phim miễn phí";
            ViewData[Extensions.Constants.HeaderKeywords] = "Từ khóa " + keyword + " trang " + PageIndex;

            var condition = new List<SearchCondition>
            {
                new SearchCondition(new[]
                {
                    SearchField.Title.ToString(), 
                    SearchField.Keyword.ToString(), 
                    SearchField.KeywordEN.ToString()
                }, keyword)
            };

            var service = WorkContext.Resolve<ISearchService>();
            service.SiteId = SiteId;
            var totalRow = 0;
            var data = service.Search(condition, PageIndex, PageSize, ref totalRow);

            var modelFirst = new DataViewCategoryModel();
            if (data != null && data.Count > 0)
            {
                modelFirst.ListSearchFilms = data.Where(x => x.IsFilm).ToList();
                modelFirst.ListSearchClip = data.Where(x => x.IsClip).ToList();
                modelFirst.ListSearchShow = data.Where(x => x.IsShow).ToList();
                modelFirst.ListSearchTrailer = data.Where(x => x.IsTrailer).ToList();
            }

            modelFirst.PageIndex = PageIndex;
            modelFirst.PageSize = PageSize;
            modelFirst.TotalRow = totalRow;
            modelFirst.Keyword = keyword;

            var viewFilmFirst = viewRenderer.RenderPartialView(Extensions.Constants.SearchResultsViewFilePath, modelFirst);
            WorkContext.Layout.CategoryContentLeftFirst.Add(new MvcHtmlString(viewFilmFirst));
            #endregion
        }
    }
}
<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class SliderModel
    {
        [ControlHidden]
        public int Id { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Chọn ngôn ngữ", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.CategoryId + "').empty();")]
        public string LanguageCode { get; set; }

        [ControlCascadingDropDown(LabelText = "Chọn trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public int SiteId { get; set; }

        [ControlCascadingDropDown(LabelText = "Chọn chuyên mục", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public int CategoryId { get; set; }

        [ControlCascadingDropDown(EnableChosen = true, CssClass = Extensions.Constants.CssControlCustom, LabelText = "Chọn phim", ParentControl = "CategoryId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public long FilmId { get; set; }

        [ControlChoice(ControlChoice.DropDownList, LabelText = "Trang hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public int PageId { get; set; }

        [ControlNumeric(LabelText = "Thứ tự", Required = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public int OrderBy { get; set; }

        [ControlFileUpload(EnableFineUploader = true, LabelText = "Ảnh nền", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 6, ShowThumbnail = true)]
        public string Images { get; set; }

        public static implicit operator SliderModel(SliderInfo entity)
        {
            return new SliderModel
            {
                Id = entity.Id,
                LanguageCode = entity.LanguageCode,
                SiteId = entity.SiteId,
                CategoryId = entity.CategoryId,
                FilmId = entity.FilmId,
                PageId = entity.PageId,
                OrderBy = entity.OrderBy,
                Images = entity.Images
            };
        }
    }
}<file_sep>﻿using System.ComponentModel;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class DownloadGameInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("Code")]
        public string Code { get; set; }

        [DataMember]
        [DisplayName("UrlBanner")]
        public string UrlBanner { get; set; }

        [DataMember]
        [DisplayName("Logo")]
        public string Logo { get; set; }

        [DataMember]
        [DisplayName("Title")]
        public string Title { get; set; }

        [DataMember]
        [DisplayName("GooglePlayUrl")]
        public string GooglePlayUrl { get; set; }

        [DataMember]
        [DisplayName("WebsiteUrl")]
        public string WebsiteUrl { get; set; }

        [DataMember]
        [DisplayName("VipXu")]
        public int VipXu { get; set; }
        
        [DataMember]
        [DisplayName("IsActived")]
        public bool IsActived { get; set; }
    }

    public class DownloadGameMap : EntityTypeConfiguration<DownloadGameInfo>, IEntityTypeConfiguration
    {
        public DownloadGameMap()
        {
            ToTable("Modules_DownloadGames");
            HasKey(m => m.Id);
            Property(m => m.Code).IsRequired().HasMaxLength(100);
            Property(m => m.UrlBanner).IsRequired().HasMaxLength(500);
            Property(m => m.Logo).IsRequired().HasMaxLength(500);
            Property(m => m.Title).IsRequired().HasMaxLength(250);
            Property(m => m.GooglePlayUrl).IsRequired().HasMaxLength(500);
            Property(m => m.WebsiteUrl).HasMaxLength(500);
            Property(m => m.VipXu).IsRequired();
        }
    }
}<file_sep>﻿using System;
using CMSSolutions.ContentManagement.Messages.Services;
using CMSSolutions.Net.Mail;
using CMSSolutions.Tasks;
using CMSSolutions.Websites.Services;
using Castle.Core.Logging;

namespace CMSSolutions.Websites.Tasks
{
    public class SendEmailTasks: IScheduleTask
    {
        public SendEmailTasks()
        {
            Logger = NullLogger.Instance;
        }

        public ILogger Logger { get; set; }

        public string Name { get { return "Gửi danh sách phim tự động qua email"; } }

        public bool Enabled { get { return false; } }

        public string CronExpression { get { return "0 0 23 ? * MON-FRI *"; } }

        public bool DisallowConcurrentExecution { get { return true; } }

        public void Execute(IWorkContextScope scope)
        {
            int maxTries = 1;
            int pageSize = 100;
            int pageIndex = 1;
            int totalRecord = 0;
            int totalPage = 1;

            var smtpSettings = scope.Resolve<SmtpSettings>();
            if (smtpSettings.MessagesPerBatch > 0)
            {
                maxTries = smtpSettings.MaxTries;
                pageSize = smtpSettings.MessagesPerBatch;
            }

            var emailSender = scope.Resolve<IEmailSender>();
            var messageService = scope.Resolve<IMessageService>();
            var customerService = scope.Resolve<ICustomerService>();
            try
            {
                customerService.AddEmailMessages();
            }
            catch (Exception)
            {
               
            }
            var queuedEmails = customerService.GetQueuedEmails(maxTries, DateTime.Parse("01/01/1900"), pageIndex, pageSize, out totalRecord);
            if (queuedEmails != null && totalRecord > 0)
            {
                if (totalRecord <= pageSize)
                {
                    totalPage = 1;
                }
                else
                {
                    var count = totalRecord % pageSize;
                    if ((count == 0))
                    {
                        totalPage = totalRecord / pageSize;
                    }
                    else
                    {
                        totalPage = ((totalRecord - count) / pageSize) + 1;
                    }
                }

                for (int i = 1; i <= totalPage; i++)
                {
                    try
                    {
                        if (i > 1)
                        {
                            queuedEmails = customerService.GetQueuedEmails(maxTries, DateTime.Parse("01/01/1900"), pageIndex, pageSize, out totalRecord);
                        }

                        foreach (var queuedEmail in queuedEmails)
                        {
                            try
                            {
                                var mailMessage = queuedEmail.GetMailMessage();
                                emailSender.Send(mailMessage);
                                queuedEmail.SentOnUtc = DateTime.UtcNow;
                            }
                            catch (Exception exc)
                            {
                                Logger.Error(string.Format("Error sending e-mail. {0}", exc.Message), exc);
                            }
                            finally
                            {
                                queuedEmail.SentTries = queuedEmail.SentTries + 1;
                                messageService.Update(queuedEmail);
                            }
                        }
                    }
                    catch (Exception)
                    {

                    }

                    pageIndex++;
                }
            }
        }
    }
}<file_sep>using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class AdvertisementGroupInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("SiteId")]
        public int SiteId { get; set; }

        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }

        [DataMember]
        [DisplayName("CategoryId")]
        public int CategoryId { get; set; }

        [NotMapped]
        [DisplayName("CategoryName")]
        public string CategoryName { get; set; }

        [DataMember]
        [DisplayName("Code")]
        public string Code { get; set; }

        [DataMember]
        [DisplayName("GroupName")]
        public string GroupName { get; set; }

        [DataMember]
        [DisplayName("Description")]
        public string Description { get; set; }

        [DataMember]
        [DisplayName("AdvertisementIds")]
        public string AdvertisementIds { get; set; }

        [DataMember]
        [DisplayName("IsGenerate")]
        public bool IsGenerate { get; set; }

        [DataMember]
        [DisplayName("IsActived")]
        public bool IsActived { get; set; }

        [DataMember]
        [DisplayName("FolderPath")]
        public string FolderPath { get; set; }

        [DataMember]
        [DisplayName("FileName")]
        public string FileName { get; set; }

        [DataMember]
        [DisplayName("FullPath")]
        public string FullPath { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string EncodeFullPath
        {
            get
            {
                if (!string.IsNullOrEmpty(FullPath))
                {
                    return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(FullPath));
                }

                return string.Empty;
            }
        }

        [DataMember]
        [DisplayName("CreateDate")]
        public DateTime CreateDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextCreateDate
        {
            get
            {
                return string.Format("{0}", CreateDate.ToString(Extensions.Constants.DateTimeFomat));
            }
        }

        [DataMember]
        [DisplayName("FinishDate")]
        public DateTime FinishDate { get; set; }

        [DataMember]
        [DisplayName("EndTime")]
        public string FinishTime { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextFinishTime
        {
            get
            {
                return string.Format("{0} {1}", FinishDate.ToString(Extensions.Constants.DateTimeFomat), FinishTime);
            }
        }
    }

    public class AdvertisementGroupMap : EntityTypeConfiguration<AdvertisementGroupInfo>, IEntityTypeConfiguration
    {

        public AdvertisementGroupMap()
        {
            ToTable("Modules_AdvertisementGroup");
            Property(m => m.LanguageCode).HasMaxLength(50);
            Property(m => m.Code).HasMaxLength(50);
            Property(m => m.GroupName).HasMaxLength(250);
            Property(m => m.AdvertisementIds).HasMaxLength(250);
            Property(m => m.FolderPath).HasMaxLength(250);
            Property(m => m.FileName).HasMaxLength(250);
            Property(m => m.FullPath).HasMaxLength(500);
            Property(m => m.Description).HasMaxLength(2000);
        }
    }
}
<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class FilmServerModel
    {
        [ControlHidden]
        public int Id { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 0)]
        public string LanguageCode { get; set; }

        [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 0)]
        public int SiteId { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Tên máy chủ", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 0)]
        public string ServerName { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 50, LabelText = "Địa chỉ IP", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 1)]
        public string ServerIP { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 50, LabelText = "Thư mục gốc", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 1)]
        public string FolderRoot { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, LabelText = "Tài khoản FTP", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 2)]
        public string UserName { get; set; }

        [ControlText(Type = ControlText.Password, LabelText = "Mật khẩu", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 2)]
        public string Password { get; set; }

        [ControlText(Type = ControlText.TextBox, MaxLength = 250, LabelText = "Địa điểm đặt", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)]
        public string Locations { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Máy chủ VIP", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)]
        public bool IsVip { get; set; }
        
        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Máy chủ mặc định", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)]
        public bool IsDefault { get; set; }

        [ControlChoice(ControlChoice.DropDownList, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 4)]
        public int Status { get; set; }

        [ControlText(Type = ControlText.MultiText, Rows = 2, MaxLength = 2000, LabelText = "Ghi chú", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 6)]
        public string Description { get; set; }
        
        public static implicit operator FilmServerModel(FilmServerInfo entity)
        {
            return new FilmServerModel
            {
                Id = entity.Id,
                LanguageCode =  entity.LanguageCode,
                SiteId = entity.SiteId,
                ServerName = entity.ServerName,
                ServerIP = entity.ServerIP,
                UserName = entity.UserName,
                Password = <PASSWORD>,
                Locations = entity.Locations,
                IsVip = entity.IsVip,
                IsDefault = entity.IsDefault,
                Description = entity.Description,
                Status = entity.Status,
                FolderRoot = entity.FolderRoot
            };
        }
    }
}
<file_sep>using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IRateService : IGenericService<RateInfo, long>, IDependency
    {
        IList<RateInfo> SearchPaged(string searchText, int pageIndex, int pageSize, out int totalRecord);

        RateInfo GetByFilmCustomer(long filmId, string customerCode);
    }
    
    public class RateService : GenericService<RateInfo, long>, IRateService
    {
        public RateService(IRepository<RateInfo, long> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public IList<RateInfo> SearchPaged(string searchText, int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Keyword", searchText),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<RateInfo>("sp_Rates_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public RateInfo GetByFilmCustomer(long filmId, string customerCode)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@FilmId", filmId),
                AddInputParameter("@CustomerCode", customerCode),
            };

            return ExecuteReaderRecord<RateInfo>("sp_Rates_GetByFilmAndCustomer", list.ToArray());
        }

        public override RateInfo GetById(long id)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Id", id),
            };

            return ExecuteReaderRecord<RateInfo>("sp_Rates_GetById", list.ToArray());
        }
    }
}
<file_sep>﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;

namespace CMSSolutions.Websites.Models
{
    public class DataViewerModel
    {
        public string CustomerCode { get; set; }

        public int DataType { get; set; }

        public int TotalRow { get; set; }

        public int TotalPage
        {
            get
            {
                if (TotalRow <= PageSize)
                {
                    return 1;
                }

                var count = TotalRow % PageSize;
                if ((count == 0))
                {
                    return TotalRow / PageSize;
                }

                return ((TotalRow - count) / PageSize) + 1;
            }
        }

        public int PageSize { get; set; }

        public int PageIndex { get; set; }

        public string Title { get; set; }

        public string SliderName { get; set; }

        public int SiteId { get; set; }

        public bool IsShow { get; set; }

        public bool Status { get; set; }

        public string Data { get; set; }

        public string Url { get; set; }

        public CustomerInfo Customer { get; set; }

        public List<CityInfo> ListCities { get; set; }

        public List<FilmTypesInfo> ListFilmTypes { get; set; }

        public List<CountryInfo> ListCountries { get; set; }

        public List<SelectListItem> ListDay { get; set; }

        public List<SelectListItem> ListMonth { get; set; }

        public List<SelectListItem> ListYear { get; set; }

        public FilmInfo FilmDetails { get; set; }

        public string JwplayerKey { get; set; }

        public int EpisodeId { get; set; }

        public List<PicasaInfo> ListFilmsPicasa { get; set; }

        public AdvertisementGroupInfo Advertisement { get; set; }

        public string UrlSwitch 
        { 
            get
            {
                var url = string.Empty;
                switch (DataType)
                {
                    case (int)LinkType.Streaming:
                        url = FilmDetails.EncodeStreamingUrl;
                        break;
                    case (int)LinkType.Picasa:
                        if (ListFilmsPicasa != null && ListFilmsPicasa.Count > 0)
                        {
                            url = ListFilmsPicasa.FirstOrDefault().EncodeUrl;
                            if (ListFilmsPicasa.Count > 1)
                            {
                                url = ListFilmsPicasa[1].EncodeUrl;
                            }
                        }
                        break;
                    case (int)LinkType.Youtube:
                        url = FilmDetails.EncodeSourceUrl;
                        break;
                }

                return url;
            } 
        }

        public string Skin { get; set; }

        public string AdvertisementsPath { get; set; }

        public List<DownloadGameInfo> ListGames { get; set; }

        public List<DownloadCustomerInfo> ListDownloadCustomer { get; set; }

        public DataTable ListHistoryDownload { get; set; }

        public DownloadCustomerInfo GetByGame(int id)
        {
            if (ListDownloadCustomer != null)
            {
                return ListDownloadCustomer.FirstOrDefault(x => x.DownloadId == id);
            }

            return null;
        }
    }
}<file_sep>﻿using System.Web.Mvc;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminRateController : BaseAdminController
    {
            public AdminRateController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
            TableName = "tblRates";
        }
        
        [Url("admin/rates")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Đánh giá và Báo lỗi phim"), Url = "#" });

            var result = new ControlGridFormResult<RateInfo>
            {
                Title = T("Đánh giá và Báo lỗi phim"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetRates,
                DefaultPageSize = WorkContext.DefaultPageSize,
                EnablePaginate = true,
                UpdateActionName = "Update",
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml,
                ClientId = TableName,
                ActionsColumnWidth = 100
            };

            result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true);

            result.AddColumn(x => x.FilmId, T("Mã phim"));
            result.AddColumn(x => x.FilmName, T("Tên phim"));
            result.AddColumn(x => x.CustomerCode, T("Mã KH"));
            result.AddColumn(x => x.CustomerName, T("Họ và Tên"));

            result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
               .HasText(T("Xem"))
               .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
               .HasButtonStyle(ButtonStyle.Default)
               .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");

            return result;
        }

        private ControlGridAjaxData<RateInfo> GetRates(ControlGridFormRequest options)
        {
            var searchText = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText]))
            {
                searchText = Request.Form[Extensions.Constants.SearchText];
            }

            int totals;
            var items = WorkContext.Resolve<IRateService>().SearchPaged(searchText, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<RateInfo>(items, totals);

            return result;
        }
        
        [Url("admin/rates/edit/{id}")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Đánh giá và Báo lỗi phim"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin đánh giá và Báo lỗi phim"), Url = "#" });

            var model = new RateModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<IRateService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<RateModel>(model)
            {
                Title = T("Thông tin đánh giá và Báo lỗi phim"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                CancelButtonText = T("Trở về"),
                ShowBoxHeader = false,
                ShowSubmitButton = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.ReadOnly = true;

            return result;
        }
    }
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using CMSSolutions.Caching;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IFilmService : ICacheService<FilmInfo, long>, IGenericService<FilmInfo, long>, IDependency
    {
        string LanguageCode { get; set; }

        int SiteId { get; set; }

        int CategoryId { get; set; }

        bool CheckAlias(long id, string alias);

        bool CheckName(string filmName);

        List<FilmInfo> SearchPaged(
            string searchText,
            string languageCode,
            int siteId,
            int categoryId,
	        int filmTypeId,
	        int countryId,
	        int directorId,
	        int actorId,
	        int collectionId,
	        int articlesId,
	        long createByUserId,
	        int serverId,
	        int releaseYear,
	        DateTime fromDate,
	        DateTime toDate,
	        DateTime createDate,
	        DateTime publishedDate,
	        int isPublished,
	        int isHot,
	        int isHome,
            int isFilmRetail,
            int isFilmLengthEpisodes,
	        int status,
	        int pageIndex,
	        int pageSize,
            out int totalRecord);

        string GetLatestFilmCode();

        IList<FilmInfo> BuildFilmHot();

        IList<FilmInfo> BuildFilmRetail();

        IList<FilmInfo> BuildFilmManyEpisodes();

        IList<FilmInfo> BuildFilmJJChannelIntroduce();

        IList<FilmInfo> BuildFilmTheater();

        IList<FilmInfo> BuildTVShow();

        IList<FilmInfo> BuildClips();

        IList<FilmInfo> GetFilmHot(int pageIndex, int pageSize, out int totalRecord);

        IList<FilmInfo> GetFilmRetail(int pageIndex, int pageSize, out int totalRecord);

        IList<FilmInfo> GetFilmManyEpisodes(int pageIndex, int pageSize, out int totalRecord);

        IList<FilmInfo> GetFilmJJChannelIntroduce(int pageIndex, int pageSize, out int totalRecord);

        IList<FilmInfo> GetFilmTheater(int pageIndex, int pageSize, out int totalRecord);

        IList<FilmInfo> GetTVShow(int pageIndex, int pageSize, out int totalRecord);

        IList<FilmInfo> GetClips(int pageIndex, int pageSize, out int totalRecord);

        void RefreshFilmJJChannelIntroduce(int categoryId);

        void RefreshTVShows(int categoryId);

        void RefreshClips(int categoryId);

        FilmInfo GetFilmDetails(long filmId);

        void RefreshStatistical1(int top, int type);

        IList<FilmInfo> GetStatistical1(int top, int type);

        IList<FilmInfo> BuildStatistical1(int top, int type);

        IList<FilmInfo> GetStatistical2(int top, int type);

        IList<FilmInfo> BuildStatistical2(int top, int type);

        void RefreshStatistical2(int top, int type);

        IList<FilmInfo> BuildStatistical3(int top, int type);

        IList<FilmInfo> GetStatistical3(int top, int type);

        void RefreshStatistical3(int top, int type);

        IList<FilmInfo> BuildStatistical4(int top, int type);

        IList<FilmInfo> GetStatistical4(int top, int type);

        void RefreshStatistical4(int top, int type);

        IList<FilmInfo> BuildStatistical5(int top, int type);

        IList<FilmInfo> GetStatistical5(int top, int type);

        void RefreshStatistical5(int top, int type);

        IList<FilmInfo> GetByCategoryId(int siteId, string languageCode,
                                        int categoryId, int parentId, int filmType, int countryId, int type, int orderBy,
                                        int sortBy,
                                        int pageIndex, int pageSize, out int totalRecord);

        IList<FilmInfo> GetByCategoryJJChannelPaged(int siteId, string languageCode,
                                                    int categoryId, int parentId, int filmType, int countryId,
                                                    int orderBy, int sortBy,
                                                    int pageIndex, int pageSize, out int totalRecord);

        IList<FilmInfo> GetByFilmTheater(int siteId, string languageCode,
            int filmType, int countryId, int orderBy, int sortBy,
            int pageIndex, int pageSize, out int totalRecord);

        IList<FilmInfo> GetByShows(int siteId, string languageCode,
            int categoryId, int parentId, int showType, int countryId, int orderBy, int sortBy,
            int pageIndex, int pageSize, out int totalRecord);

        IList<FilmInfo> GetByClips(int siteId, string languageCode,
            int categoryId, int parentId, int showType, int orderBy, int sortBy,
            int pageIndex, int pageSize, out int totalRecord);

        IList<FilmInfo> GetByTrailer(int siteId, string languageCode, int pageIndex, int pageSize, out int totalRecord);

        FilmInfo GetFilmsMovie(long filmId, int episodeId);

        FilmInfo GetTrailerMovie(long filmId);

        IList<FilmInfo> GetFilmEpisodes(long filmId, int pageIndex, int pageSize, out int totalRecord);

        int UpdateViewCount(long filmId);

        IList<FilmInfo> GetAllByCategoryId();

        int UpdateCommentCount(long filmId);
    }

    public class FilmService : GenericService<FilmInfo, long>, IFilmService
    {
        private readonly ICacheInfo cacheManager;
        private readonly ICategoryService categoryService;
        public string LanguageCode { get; set; }
        public int SiteId { get; set; }
        public int CategoryId { get; set; }

        public FilmService(IRepository<FilmInfo, long> repository, 
            IEventBus eventBus, ICacheInfo cacheManager, 
            ICategoryService categoryService) 
            : base(repository, eventBus)
        {
            this.cacheManager = cacheManager;
            this.categoryService = categoryService;
        }

        public bool CheckAlias(long id, string alias)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@FilmAlias", alias),
                AddInputParameter("@Id", id)
            };

            var result = (int)ExecuteReaderResult("sp_Film_CheckAlias", list.ToArray());
            return result > 0;
        }

        public bool CheckName(string filmName)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@FilmName", filmName)
            };

            var result = (int)ExecuteReaderResult("sp_Film_CheckName", list.ToArray());
            return result > 0;
        }

        public List<FilmInfo> SearchPaged(
            string searchText,
            string languageCode,
            int siteId,
            int categoryId,
            int filmTypeId,
            int countryId,
            int directorId,
            int actorId,
            int collectionId,
            int articlesId,
            long createByUserId,
            int serverId,
            int releaseYear,
            DateTime fromDate,
            DateTime toDate,
            DateTime createDate,
            DateTime publishedDate,
            int isPublished,
            int isHot,
            int isHome,
            int isFilmRetail,
            int isFilmLengthEpisodes,
            int status,
            int pageIndex,
            int pageSize,
            out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SearchText", searchText),
                AddInputParameter("@SiteId", siteId),
                AddInputParameter("@CategoryId", categoryId),
                AddInputParameter("@LanguageCode", languageCode),
                AddInputParameter("@FilmTypeId", filmTypeId),
                AddInputParameter("@CountryId", countryId),
                AddInputParameter("@DirectorId", directorId),
                AddInputParameter("@ActorId", actorId),
                AddInputParameter("@CollectionId", collectionId),
                AddInputParameter("@ArticlesId", articlesId),
                AddInputParameter("@CreateByUserId", createByUserId),
                AddInputParameter("@ServerId", serverId),
                AddInputParameter("@ReleaseYear", releaseYear),
                AddInputParameter("@FromDate", fromDate),
                AddInputParameter("@ToDate", toDate),
                AddInputParameter("@CreateDate", createDate),
                AddInputParameter("@PublishedDate", publishedDate),
                AddInputParameter("@IsPublished", isPublished),
                AddInputParameter("@IsHot", isHot),
                AddInputParameter("@IsHome", isHome),
                AddInputParameter("@IsFilmRetail", isFilmRetail),
                AddInputParameter("@IsFilmLengthEpisodes", isFilmLengthEpisodes),
                AddInputParameter("@Status", status),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmInfo>("sp_Film_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public string GetLatestFilmCode()
        {
            return (string)ExecuteReaderResult("NextFilmCode");
        }

        public IList<FilmInfo> GetFilmHot(int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmInfo>("sp_Films_GetFilmHot_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public IList<FilmInfo> BuildFilmHot()
        {
            var list = cacheManager.Get(Extensions.Constants.CacheKeys.HOME_FILM_HOT);
            if (list == null)
            {
                int totalRecord;
                list = GetFilmHot(1, 16, out totalRecord);
                cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_HOT);
                cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_HOT, list);
            }

            return (IList<FilmInfo>)list;
        }

        public IList<FilmInfo> GetFilmRetail(int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmInfo>("sp_Films_GetFilmRetail_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public IList<FilmInfo> BuildFilmRetail()
        {
            var list = cacheManager.Get(Extensions.Constants.CacheKeys.HOME_FILM_RETAIL);
            if (list == null)
            {
                int totalRecord;
                list = GetFilmRetail(1, 16, out totalRecord);
                cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_RETAIL);
                cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_RETAIL, list);
            }

            return (IList<FilmInfo>)list;
        }

        public IList<FilmInfo> BuildFilmManyEpisodes()
        {
            var list = cacheManager.Get(Extensions.Constants.CacheKeys.HOME_FILM_MANY_EPISODES);
            if (list == null)
            {
                int totalRecord;
                list = GetFilmManyEpisodes(1, 16, out totalRecord);
                cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_MANY_EPISODES);
                cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_MANY_EPISODES, list);
            }

            return (IList<FilmInfo>)list;
        }

        public IList<FilmInfo> GetFilmManyEpisodes(int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmInfo>("sp_Films_GetFilmManyEpisodes_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public IList<FilmInfo> BuildFilmJJChannelIntroduce()
        {
            var list = cacheManager.Get(Extensions.Constants.CacheKeys.HOME_FILM_JJ_CHANNEL_INTRODUCE);
            if (list == null)
            {
                int totalRecord;
                list = GetFilmJJChannelIntroduce(1, 16, out totalRecord);
                cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_JJ_CHANNEL_INTRODUCE);
                cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_JJ_CHANNEL_INTRODUCE, list);
            }

            return (IList<FilmInfo>)list;
        }
        
        public IList<FilmInfo> GetFilmJJChannelIntroduce(int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@CategoryId", CategoryId),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmInfo>("sp_Films_GetFilmJJChannelIntroduce_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public IList<FilmInfo> BuildFilmTheater()
        {
            var list = cacheManager.Get(Extensions.Constants.CacheKeys.HOME_FILM_THEATER);
            if (list == null)
            {
                int totalRecord;
                list = GetFilmTheater(1, 16, out totalRecord);
                cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_THEATER);
                cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_THEATER, list);
            }

            return (IList<FilmInfo>)list;
        }

        public IList<FilmInfo> GetFilmTheater(int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmInfo>("sp_Films_GetFilmTheater_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public IList<FilmInfo> BuildTVShow()
        {
            var list = cacheManager.Get(Extensions.Constants.CacheKeys.HOME_FILM_TV_SHOWS);
            if (list == null)
            {
                int totalRecord;
                list = GetTVShow(1, 10, out totalRecord);
                cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_TV_SHOWS);
                cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_TV_SHOWS, list);
            }

            return (IList<FilmInfo>)list;
        }

        public IList<FilmInfo> GetTVShow(int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@CategoryId", CategoryId),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmInfo>("sp_Films_GetTVShows_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public IList<FilmInfo> BuildClips()
        {
            var list = cacheManager.Get(Extensions.Constants.CacheKeys.HOME_FILM_TV_CLIPS);
            if (list == null)
            {
                int totalRecord;
                list = GetClips(1, 16, out totalRecord);
                cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_TV_CLIPS);
                cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_TV_CLIPS, list);
            }

            return (IList<FilmInfo>)list;
        }

        public IList<FilmInfo> GetClips(int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@CategoryId", 0),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmInfo>("sp_Films_GetClips_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public void RefreshFilmJJChannelIntroduce(int categoryId)
        {
            CategoryId = categoryId;
            var totalRecord = 0;
            cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_JJ_CHANNEL_INTRODUCE);
            cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_JJ_CHANNEL_INTRODUCE, GetFilmJJChannelIntroduce(1, 16, out totalRecord));
        }

        public void RefreshTVShows(int categoryId)
        {
            CategoryId = categoryId;
            var totalRecord = 0;
            cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_TV_SHOWS);
            cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_TV_SHOWS, GetTVShow(1, 10, out totalRecord));
        }

        public void RefreshClips(int categoryId)
        {
            CategoryId = categoryId;
            var totalRecord = 0;
            cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_TV_CLIPS);
            cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_TV_CLIPS, GetClips(1, 16, out totalRecord));
        }

        public FilmInfo GetByIdCache(long id)
        {
            throw new NotImplementedException();
        }

        public IList<FilmInfo> GetAllCache()
        {
            throw new NotImplementedException();
        }

        public IList<FilmInfo> ResetCache()
        {
            int totalRecord;
            cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_HOT);
            cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_HOT, GetFilmHot(1, 16, out totalRecord));
            cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_RETAIL);
            cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_RETAIL, GetFilmRetail(1, 16, out totalRecord));
            cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_MANY_EPISODES);
            cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_MANY_EPISODES, GetFilmManyEpisodes(1, 16, out totalRecord));
            cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_THEATER);
            cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_THEATER, GetFilmTheater(1, 16, out totalRecord));
            return null;
        }

        public FilmInfo GetFilmDetails(long filmId)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@FilmId", filmId)
            };

            return ExecuteReaderRecord<FilmInfo>("sp_Films_GetFilmDetails", list.ToArray());
        }

        public void RefreshStatistical1(int top, int type)
        {
            cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_1_TYPE, type));
            cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_1_TYPE, type), GetStatistical1(top, type));
        }

        public IList<FilmInfo> BuildStatistical1(int top, int type)
        {
            var list = cacheManager.Get(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_1_TYPE, type));
            if (list == null)
            {
                list = GetStatistical1(top, type);
                cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_1_TYPE, type));
                cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_1_TYPE, type), list);
            }

            return (IList<FilmInfo>)list;
        }

        public IList<FilmInfo> GetStatistical1(int top, int type)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@TopRecord", top),
                AddInputParameter("@Type", type)
            };

            return ExecuteReader<FilmInfo>("sp_Films_GetStatistical", list.ToArray());
        }


        public void RefreshStatistical2(int top, int type)
        {
            cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_2_TYPE, type));
            cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_2_TYPE, type), GetStatistical2(top, type));
        }

        public void RefreshStatistical3(int top, int type)
        {
            cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_3_TYPE, type));
            cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_3_TYPE, type), GetStatistical3(top, type));
        }

        public IList<FilmInfo> GetStatistical4(int top, int type)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@TopRecord", top),
                AddInputParameter("@Type", type)
            };

            return ExecuteReader<FilmInfo>("sp_Films_GetStatisticalClips", list.ToArray());
        }

        public void RefreshStatistical4(int top, int type)
        {
            cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_4_TYPE, type));
            cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_4_TYPE, type), GetStatistical4(top, type));
        }

        public IList<FilmInfo> BuildStatistical5(int top, int type)
        {
            var list = cacheManager.Get(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_5_TYPE, type));
            if (list == null)
            {
                list = GetStatistical5(top, type);
                cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_5_TYPE, type));
                cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_5_TYPE, type), list);
            }

            return (IList<FilmInfo>)list;
        }

        public IList<FilmInfo> GetStatistical5(int top, int type)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@TopRecord", top),
                AddInputParameter("@Type", type)
            };

            return ExecuteReader<FilmInfo>("sp_Films_GetStatisticalTrailer", list.ToArray());
        }

        public void RefreshStatistical5(int top, int type)
        {
            cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_5_TYPE, type));
            cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_5_TYPE, type), GetStatistical5(top, type));
        }

        public IList<FilmInfo> BuildStatistical4(int top, int type)
        {
            var list = cacheManager.Get(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_4_TYPE, type));
            if (list == null)
            {
                list = GetStatistical4(top, type);
                cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_4_TYPE, type));
                cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_4_TYPE, type), list);
            }

            return (IList<FilmInfo>)list;
        }

        public IList<FilmInfo> GetStatistical2(int top, int type)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@TopRecord", top),
                AddInputParameter("@Type", type)
            };

            return ExecuteReader<FilmInfo>("sp_Films_GetStatisticalLengthEpisodes", list.ToArray());
        }

        public IList<FilmInfo> BuildStatistical2(int top, int type)
        {
            var list = cacheManager.Get(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_2_TYPE, type));
            if (list == null)
            {
                list = GetStatistical2(top, type);
                cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_2_TYPE, type));
                cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_2_TYPE, type), list);
            }

            return (IList<FilmInfo>)list;
        }

        public IList<FilmInfo> BuildStatistical3(int top, int type)
        {
            var list = cacheManager.Get(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_3_TYPE, type));
            if (list == null)
            {
                list = GetStatistical3(top, type);
                cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_3_TYPE, type));
                cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_3_TYPE, type), list);
            }

            return (IList<FilmInfo>)list;
        }

        public IList<FilmInfo> GetStatistical3(int top, int type)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@TopRecord", top),
                AddInputParameter("@Type", type)
            };

            return ExecuteReader<FilmInfo>("sp_Films_GetStatisticalShows", list.ToArray());
        }

        public IList<FilmInfo> GetByCategoryId(int siteId, string languageCode,
            int categoryId, int parentId, int filmType, int countryId, int type,int orderBy, int sortBy, 
            int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@CategoryId", categoryId),
                AddInputParameter("@ParentId", parentId),
                AddInputParameter("@FilmTypeId", filmType),
                AddInputParameter("@CountryId", countryId),
                AddInputParameter("@Type", type),
                AddInputParameter("@OrderBy", orderBy),
                AddInputParameter("@SortBy", sortBy),               
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmInfo>("sp_Film_GetByCategoryId", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public IList<FilmInfo> GetByCategoryJJChannelPaged(int siteId, string languageCode,
            int categoryId, int parentId, int filmType, int countryId, int orderBy, int sortBy,
            int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@CategoryId", categoryId),
                AddInputParameter("@ParentId", parentId),
                AddInputParameter("@FilmTypeId", filmType),
                AddInputParameter("@CountryId", countryId),
                AddInputParameter("@OrderBy", orderBy),
                AddInputParameter("@SortBy", sortBy),               
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmInfo>("sp_Film_GetByCategoryJJChannel_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public IList<FilmInfo> GetByFilmTheater(int siteId, string languageCode,
            int filmType, int countryId, int orderBy, int sortBy,
            int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@FilmTypeId", filmType),
                AddInputParameter("@CountryId", countryId),
                AddInputParameter("@OrderBy", orderBy),
                AddInputParameter("@SortBy", sortBy),               
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmInfo>("sp_Film_GetFilmsTheater", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public IList<FilmInfo> GetByShows(int siteId, string languageCode, 
            int categoryId, int parentId, int showType, 
            int countryId, int orderBy, int sortBy, int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@CategoryId", categoryId),
                AddInputParameter("@ParentId", parentId),
                AddInputParameter("@ShowTypeId", showType),
                AddInputParameter("@CountryId", countryId),
                AddInputParameter("@OrderBy", orderBy),
                AddInputParameter("@SortBy", sortBy),               
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmInfo>("sp_Film_GetShows", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public IList<FilmInfo> GetByClips(int siteId, string languageCode, int categoryId, int parentId, int showType, int orderBy, int sortBy, int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@CategoryId", categoryId),
                AddInputParameter("@ParentId", parentId),
                AddInputParameter("@ShowTypeId", showType),
                AddInputParameter("@OrderBy", orderBy),
                AddInputParameter("@SortBy", sortBy),               
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmInfo>("sp_Film_GetClips", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public IList<FilmInfo> GetByTrailer(int siteId, string languageCode, 
            int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),              
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmInfo>("sp_Film_GetTrailer", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public FilmInfo GetFilmsMovie(long filmId, int episodeId)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@LanguageCode", LanguageCode), 
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@FilmId", filmId),
                AddInputParameter("@EpisodeId", episodeId)
            };

            return ExecuteReaderRecord<FilmInfo>("sp_Films_Movies", list.ToArray());
        }

        public FilmInfo GetTrailerMovie(long filmId)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@LanguageCode", LanguageCode), 
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@FilmId", filmId)
            };

            return ExecuteReaderRecord<FilmInfo>("sp_Films_TrailerMovies", list.ToArray());
        }

        public IList<FilmInfo> GetFilmEpisodes(long filmId, int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@FilmId", filmId),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<FilmInfo>("sp_Films_GetFilmEpisodes", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public int UpdateViewCount(long filmId)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@FilmId", filmId)
            };

            return ExecuteNonQuery("sp_Films_UpdateViewCount", list.ToArray());
        }

        public int UpdateCommentCount(long filmId)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@FilmId", filmId)
            };

            return ExecuteNonQuery("sp_Films_UpdateCommentCount", list.ToArray());
        }

        public IList<FilmInfo> GetAllByCategoryId()
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@CategoryId", CategoryId)
            };

            return ExecuteReader<FilmInfo>("sp_Films_GetAllByCategoryId", list.ToArray());
        }
    }
}
<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;

namespace CMSSolutions.Websites.Models
{
    public class VideoRefreshModel
    {
        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Máy chủ", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.ChildrenFolders + "').empty();")]
        public int ServerId { get; set; }

        [ControlCascadingDropDown(LabelText = "Thư mục gốc", ParentControl = "ServerId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)]
        public string RootFolders { get; set; }

        [ControlCascadingDropDown(AllowMultiple = true, LabelText = "Thư mục con", ParentControl = "RootFolders", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)]
        public string ChildrenFolders { get; set; }
    }
}<file_sep>﻿using System;
using System.Web.Mvc;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminVipCardController : BaseAdminController
    {
        public AdminVipCardController(IWorkContextAccessor workContextAccessor) : 
                base(workContextAccessor)
        {
            TableName = "tblVipcards";
        }
        
        [Url("admin/vipcards")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý thẻ VIP"), Url = "#" });

            var result = new ControlGridFormResult<VIPCardInfo>
            {
                Title = T("Quản lý thẻ VIP"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetVipCards,
                UpdateActionName = "Update",
                ActionsColumnWidth = 100,
                ClientId = TableName,
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml
            };

            result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.ServerId + "').val();", true);

            result.AddColumn(x => x.VIPCode, T("Mã thẻ")).AlignCenter().HasWidth(100);
            result.AddColumn(x => x.VIPName, T("Tên thẻ"));
            result.AddColumn(x => x.ServerName, T("Máy chủ"));
            result.AddColumn(x => x.VIPValue, T("Định mức"));

            result.AddAction().HasText(T("Thêm mới"))
                .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
                .HasButtonStyle(ButtonStyle.Primary)
                .HasBoxButton(false)
                .HasCssClass(Constants.RowLeft)
                .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildSiteServers(true, Extensions.Constants.ServerId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildServers)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
                 .HasText(T("Sửa"))
                 .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                 .HasButtonStyle(ButtonStyle.Default)
                 .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");
            return result;
        }

        private ControlGridAjaxData<VIPCardInfo> GetVipCards(ControlGridFormRequest options)
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var serverId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ServerId]))
            {
                serverId = Convert.ToInt32(Request.Form[Extensions.Constants.ServerId]);
            }

            int totals;
            var items = WorkContext.Resolve<IVIPCardService>().SearchPaged(string.Empty, languageCode, siteId, serverId, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<VIPCardInfo>(items, totals);

            return result;
        }

        [Url("admin/vipcards/edit/{id}")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý thẻ VIP"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin thẻ VIP"), Url = "#" });

            var model = new VIPCardModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<IVIPCardService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<VIPCardModel>(model)
            {
                Title = T("Thông tin thẻ VIP"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                ShowCancelButton = true,
                ShowBoxHeader = false,
                CancelButtonText = T("Trở về"),
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages());
            result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage"));
            result.RegisterCascadingDropDownDataSource(x => x.ServerId, Url.Action("GetServersBySite"));
          
            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/vipcards/update")]
        public ActionResult Update(VIPCardModel model)
        {
            if (!ModelState.IsValid)
            {
				return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var service = WorkContext.Resolve<IVIPCardService>();
            VIPCardInfo item = model.Id == 0 ? new VIPCardInfo() : service.GetById(model.Id);

            if (service.CheckVipCode(item.Id, model.VIPCode))
            {
                return new AjaxResult()
                    .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                    .Alert(T("Đã tồn tại mã thẻ VIP này!"));
            }

            item.VIPCode = model.VIPCode.ToUpper();
            item.VIPName = model.VIPName;
            item.VIPValue = model.VIPValue;
            item.LanguageCode = model.LanguageCode;
            item.SiteId = model.SiteId;
            item.ServerId = model.ServerId;

            service.Save(item);

            return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"))
                .CloseModalDialog();
        }
    }
}
<file_sep>﻿using System;
using System.Configuration;

namespace CMSSolutions.Websites.Extensions
{
    public class Constants
    {
        public const string SearchText = "SearchText";
        public const string FromDate = "FromDate";
        public const string ToDate = "ToDate";
        public const string LanguageCode = "LanguageCode";
        public const string SiteId = "SiteId";
        public const string CategoryId = "CategoryId";
        public const string CategoryIds = "CategoryIds";
        public const string ParentId = "ParentId";
        public const string ServerId = "ServerId";
        public const string IsNull = "null";
        public const string IsUndefined = "undefined";
        public const string UserId = "UserId";
        public const string DirectorId = "DirectorId";
        public const string ActorId = "ActorId";
        public const string FilmTypesId = "FilmTypesId";
        public const string FilmGroup = "FilmGroup";
        public const string StatusId = "StatusId";
        public const string TypeId = "TypeId";
        public const string BankCode = "BankCode";
        public const string CardCode = "CardCode";
        public const string Locked = "Locked";
        public const string TypeSearch = "TypeSearch";
        public const string ChildrenFolders = "ChildrenFolders";
        public const string RootFolders = "RootFolders";
        public const string FolderDay = "FolderDay";
        public const string ValueAll = "All";
        public const string FilmId = "FilmId";
        public const string Id = "id";
        public const string PageId = "PageId";
        public const string AdId = "AdId";
        public const string CountryId = "CountryId";
        public const string GlobalCapcha = "GLObAL_CAPCHA";
        public const string GlobalCustomerCode = "GLObAL_LOGIN_USER_CODE";
        public const string GlobalUserName = "GLObAL_LOGIN_USERNAME";
        public const string GlobalFullName = "GLObAL_LOGIN_USER_FULLNAME";
        public const string GlobalUserId = "GLObAL_LOGIN_USERID";
        public const string GlobalVipXu = "GLObAL_LOGIN_USER_VIPXU";
        public const string GlobalSiteId = "GLObAL_SITE_ID";
        public const string TransactionCode = "TRANSACTION_CODE";
        public const string CurrentDate = "CURRENT_DATETIME";
        public const string UrlLoginHistory = "URL_LOGIN_HISTORY";
        public const string PageIndex = "pageIndex";
        public const string ReturnUrl = "returnUrl";
        public const string BackPageIndex = "BackPageIndex";

        public const string GlobalTotalMoney = "GLObAL_TOTAL_MONEY";
        public const string GlobalTotalDay = "GLObAL_TOTAL_DAY";
        public const string GlobalStartDate = "GLObAL_START_DATE";
        public const string GlobalEndDate = "GLObAL_END_DATE";

        public const string DefaultPassword = "<PASSWORD>";
        
        public const string CssControlCustom = "form-control-custom";
        public const string RecieveSmsParameters = "RecieveSms?partnerid={partnerid}&moid={moid}&userid={userid}&shortcode={shortcode}&keyword={keyword}&content={content}&transdate={transdate}&checksum={checksum}&amount={amount}";
        public const string SMSSyntax = "Tin nhan sai cu phap vui long kiem tra lai.";
        public const string SMSCustomerNotFound = "Rat tiec ID khong ton tai. Vui long dang nhap viphd.vn vao muc GOI TAI TRO va nhap ma giao dich sau {0}";
        public const string SMSKeywordNotFound = "Tin nhan sai cu phap. Soan VIPXU HD GUI 8376 de nhan huong dan dich vu cua 8x76 (Cuoc phi tin nhan 3.000VND)";
        public const string SMSUserHelp = "Soan tin VIPXU MaKH GUI 8576(5.000VND/SMS) hoac VIPXU MaKH GUI 8676(10.000VND/SMS) hoac VIPXU MaKH GUI 8776(15.000VND/SMS)";
        public const string SMSSystemError = "He thong thanh toan dang qua tai ban vui long thu lai sau.";
        public const string VipXuKeyword = "VIPXU";

        public const string CategoryContentFirstViewFilePath = "~/Views/Shared/CategoryContentFirst.cshtml";
        public const string HomeFilmHotViewFilePath = "~/Views/Shared/HomeFilmHot.cshtml";
        public const string SliderOneViewFilePath = "~/Views/Shared/SliderViewOne.cshtml";
        public const string CategoryListViewViewFilePath = "~/Views/Shared/CategoryListView.cshtml";
        public const string CategoryJJListViewFilePath = "~/Views/Shared/CategoryJJListView.cshtml";
        public const string NewsDetailsViewFilePath = "~/Views/Shared/NewsDetails.cshtml";
        public const string NewsCategoryViewFilePath = "~/Views/Shared/NewsCategory.cshtml";
        public const string FilmTheaterViewFilePath = "~/Views/Shared/FilmTheater.cshtml";
        public const string ShowListViewFilePath = "~/Views/Shared/ShowListView.cshtml";
        public const string ClipListViewFilePath = "~/Views/Shared/ClipListView.cshtml";
        public const string TrailerListViewFilePath = "~/Views/Shared/TrailerListView.cshtml";
        public const string SupportsViewFilePath = "~/Views/Shared/HomeSupports.cshtml";
        public const string ListMoviesViewFilePath = "~/Views/Shared/ListMovies.cshtml";
        public const string SearchResultsViewFilePath = "~/Views/Shared/SearchResults.cshtml";

        public const string CategoryContentSecondViewFilePath = "~/Views/Shared/CategoryContentSecond.cshtml";
        public const string CategoryContentThirdViewFilePath = "~/Views/Shared/CategoryContentThird.cshtml";
        public const string CategoryContentFourthViewFilePath = "~/Views/Shared/CategoryContentFourth.cshtml";
        public const string CategoryContentFifthViewFilePath = "~/Views/Shared/CategoryContentFifth.cshtml";
        public const string CategoryContentSixthViewFilePath = "~/Views/Shared/CategoryContentSixth.cshtml";
        public const string CategoryContentSeventhViewFilePath = "~/Views/Shared/CategoryContentSeventh.cshtml";
        public const string SocialNetworkViewFilePath = "~/Views/Shared/SocialNetwork.cshtml";
        public const string CustomerViewFilePath = "~/Views/Shared/CustomerInfomations.cshtml";
        public const string NewsViewFilePath = "~/Views/Shared/NewsViewer.cshtml";
        public const string TagViewFilePath = "~/Views/Shared/Tags.cshtml";
        public const string DivDisplayFilePath = "~/Views/Shared/DivDisplay.cshtml";

        public const string Statistic1FilePath = "~/Views/Shared/Statistic1.cshtml";
        public const string Statistic2FilePath = "~/Views/Shared/Statistic2.cshtml";
        public const string Statistic3FilePath = "~/Views/Shared/Statistic3.cshtml";
        public const string Statistic4FilePath = "~/Views/Shared/Statistic4.cshtml";
        public const string Statistic5FilePath = "~/Views/Shared/Statistic5.cshtml";
        public const string Statistic6FilePath = "~/Views/Shared/Statistic6.cshtml";

        public const string RegisterResourceFilePath = "~/Views/Shared/HomeRegisterResource.cshtml";
        public const string MoviesFilePath = "~/Views/Shared/Movies.cshtml";
        public const string FacebookCommentsFilePath = "~/Views/Shared/FacebookComments.cshtml";
        public const string FilmRateFilePath = "~/Views/Shared/FilmRate.cshtml";
        public const string SliderBannerFilePath = "~/Views/Shared/HomeSliderBanner.cshtml";
        public const string DigCoinsFilePath = "~/Views/Shared/DigCoins.cshtml";
        public const string DaoXuInformationsFilePath = "~/Views/Shared/DaoXuInformations.cshtml";
        public const string DaoXuHelpsFilePath = "~/Views/Shared/DaoXuHelps.cshtml";
        public const string DaoXuLogsFilePath = "~/Views/Shared/DaoXuLogs.cshtml";

        public const string ImageMale = "/Images/avatars/avatar-no-image.png";
        public const string ImageFemale = "/Images/avatars/female-user.png";
        public const string DateTimeFomat = "dd/MM/yyyy";
        public const string DateTimeFomat2 = "dd.MM.yyyy";
        public const string DateTimeFomatFull = "dd/MM/yyyy H:mm:ss";
        public const string DateTimeFomatFull2 = "dd-MM-yyyy H:mm:ss";
        public const string DateTimeMin = "01/01/1900";
        public const string CssThumbsSize = "thumbs-size";
        public const string HeaderTitle = "HeaderTitle";
        public const string HeaderDescription = "HeaderDescription";
        public const string HeaderKeywords = "HeaderKeywords";
        //public static string SiteName = ConfigurationManager.AppSettings["SiteName"];
        //public static string ContactEmail = ConfigurationManager.AppSettings["ContactEmail"];
        public static string HomeDomainName = ConfigurationManager.AppSettings["HomeDomainName"];
        public static string JJDomainName = ConfigurationManager.AppSettings["JJDomainName"];
        public static string SmsLogFiles = ConfigurationManager.AppSettings["SmsLogFiles"];
        public static string SearchEngineDBPath = ConfigurationManager.AppSettings["SearchEngineDBPath"];
        public static string JWplayerSkin = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["JWplayerSkin"]));
        public static string JWplayerKey = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["JWplayerKey"]));
        public static string StreamingUrl = ConfigurationManager.AppSettings["StreamingUrl"];

        public class CacheKeys
        {
            public const string CATEGORY_ALL_TABLE = "CATEGORY_ALL_TABLE_{0}_{1}";
            public const string ARTICLES_BY_CATEGORY_ID = "ARTICLES_BY_CATEGORY_ID";
            public const string CATALOG_ALL_TABLE = "CATALOG_ALL_TABLE";
            public const string SETTING_ALL_TABLE = "SETTING_ALL_TABLE_{0}";
            public const string PRODUCT_ALL_TABLE = "PRODUCT_ALL_TABLE_{0}";
            public const string HOME_FILM_HOT = "HOME_FILM_HOT";
            public const string HOME_FILM_RETAIL = "HOME_FILM_RETAIL";
            public const string HOME_FILM_MANY_EPISODES = "HOME_FILM_MANY_EPISODES";
            public const string HOME_FILM_JJ_CHANNEL_INTRODUCE = "HOME_FILM_JJ_CHANNEL_INTRODUCE";
            public const string HOME_FILM_THEATER = "HOME_FILM_THEATER"; 
            public const string HOME_FILM_TV_SHOWS = "HOME_FILM_TV_SHOWS";
            public const string HOME_FILM_TV_CLIPS = "HOME_FILM_TV_CLIPS";
            public const string HOME_CATEGORY_ID = "HOME_CATEGORY_{0}";
            public const string SEARCH_TEXT = "HOME_SEARCH_TEXT_{0}";
            public const string HOME_STATISTICAL_1_TYPE = "HOME_STATISTICAL_1_TYPE_{0}";
            public const string HOME_STATISTICAL_2_TYPE = "HOME_STATISTICAL_2_TYPE_{0}";
            public const string HOME_STATISTICAL_3_TYPE = "HOME_STATISTICAL_3_TYPE_{0}";
            public const string HOME_STATISTICAL_4_TYPE = "HOME_STATISTICAL_4_TYPE_{0}";
            public const string HOME_STATISTICAL_5_TYPE = "HOME_STATISTICAL_5_TYPE_{0}";
            public const string HOME_SLIDER_PAGE = "HOME_SLIDER_PAGE_{0}";
            public const string CUSTOMERS_DATA_CARD = "CUSTOMERS_DATA_CARD";
        }
    }
}<file_sep>using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IAdvertisementGroupService : IGenericService<AdvertisementGroupInfo, int>, IDependency
    {
        List<AdvertisementGroupInfo> SearchPaged(
            string languageCode,
            int siteId,
            int categoryId,
            int pageIndex,
            int pageSize,
            out int totalRecord);

        AdvertisementGroupInfo GetAdByCategories(string languageCode, int siteId, string categoryIds);

        DataTable GetDataGenerateXml(string languageCode);

        IList<AdvertisementGroupInfo> GetGroupGenerateXml(string languageCode);
    }
    
    public class AdvertisementGroupService : GenericService<AdvertisementGroupInfo, int>, IAdvertisementGroupService
    {
        public AdvertisementGroupService(IRepository<AdvertisementGroupInfo, int> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public List<AdvertisementGroupInfo> SearchPaged(string languageCode, int siteId, int categoryId, int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@LanguageCode", languageCode),
                AddInputParameter("@SiteId", siteId),
                AddInputParameter("@CategoryId", categoryId),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<AdvertisementGroupInfo>("sp_AdvertisementGroup_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public AdvertisementGroupInfo GetAdByCategories(string languageCode, int siteId, string categoryIds)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@LanguageCode", languageCode),
                AddInputParameter("@SiteId", siteId),
                AddInputParameter("@CategoryIds", categoryIds)
            };

            return ExecuteReaderRecord<AdvertisementGroupInfo>("sp_AdvertisementGroup_GetAdByCategory", list.ToArray());
        }

        public DataTable GetDataGenerateXml(string languageCode)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@LanguageCode", languageCode)
            };

            return ExecuteReader("sp_Advertisement_GetGenerateXml", list.ToArray()).Tables[0];
        }

        public IList<AdvertisementGroupInfo> GetGroupGenerateXml(string languageCode)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@LanguageCode", languageCode)
            };

            return ExecuteReader<AdvertisementGroupInfo>("sp_AdvertisementGroup_GetGenerateXml", list.ToArray());
        }
    }
}
<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class SupportModel
    {
        [ControlHidden]
        public int Id { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.ParentId+ "').empty();")]
        public string LanguageCode { get; set; }

        [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public int SiteId { get; set; }

        [ControlCascadingDropDown(LabelText = "Chọn nhóm", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public int ParentId { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Tạo nhóm", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public bool IsGroup { get; set; }

        [ControlNumeric(LabelText = "Sắp xếp theo nhóm", Required = true, MaxLength = 15, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public int OrderBy { get; set; }

        [ControlChoice(ControlChoice.DropDownList, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public int Status { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Câu hỏi", PlaceHolder = "Tối đa 250 ký tự", Required = true, MaxLength = 400, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 2)]
        public string Title { get; set; }

        [ControlText(LabelText = "Trả lời câu hỏi", Type = ControlText.RichText, MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)]
        public string Messages { get; set; }

        public static implicit operator SupportModel(SupportInfo entity)
        {
            return new SupportModel
            {
                Id = entity.Id,
                LanguageCode = entity.LanguageCode,
                SiteId = entity.SiteId,
                Title = entity.Title,
                OrderBy = entity.OrderBy,
                Messages = entity.Messages,
                Status = entity.Status,
                ParentId = entity.ParentId
            };
        }
    }
}<file_sep>﻿using System.ComponentModel;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class CityInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("Code")]
        public string Code { get; set; }

        [DataMember]
        [DisplayName("Name")]
        public string Name { get; set; }

        [DataMember]
        [DisplayName("CountryId")]
        public int CountryId { get; set; }

        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }
    }

    public class CityMap : EntityTypeConfiguration<CityInfo>, IEntityTypeConfiguration
    {
        public CityMap()
        {
            ToTable("Modules_City");
            HasKey(x => x.Id);
            Property(x => x.Code).HasMaxLength(50);
            Property(x => x.Name).IsRequired().HasMaxLength(250);
            Property(x => x.CountryId).IsRequired();
        }
    }
}<file_sep>using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface ICollectionService : IGenericService<CollectionInfo, int>, IDependency
    {
        bool CheckExist(int id, string keyword);

        IList<CollectionInfo> GetPaged(string languageCode, int siteId, string keyword, int status, int pageIndex, int pageSize, out int totals);
    }
    
    public class CollectionService : GenericService<CollectionInfo, int>, ICollectionService
    {
        public CollectionService(IEventBus eventBus, 
            IRepository<CollectionInfo, int> repository) : 
                base(repository, eventBus)
        {

        }

        public bool CheckExist(int id, string keyword)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Id", id),
                AddInputParameter("@Keyword", keyword)
            };
            var result = (int)ExecuteReaderResult("sp_Collections_CheckName", list.ToArray());

            return result > 0;
        }

        public IList<CollectionInfo> GetPaged(string languageCode, int siteId, string keyword, int status, int pageIndex, int pageSize, out int totals)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", siteId),
                AddInputParameter("@LanguageCode", languageCode),
                AddInputParameter("@Keyword", keyword),
                AddInputParameter("@Status", status),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<CollectionInfo>("sp_Collections_Search_Paged", "@TotalRecord", out totals, list.ToArray());
        }
    }
}
<file_sep>﻿using System;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;

namespace CMSSolutions.Websites.Models
{
    public class FilmModel
    {
        public FilmModel()
        {
            PublishedDate = DateTime.Now.ToString(Extensions.Constants.DateTimeFomat);
            IsPublished = true;
            VideoType = (int)VideoTypes.IsFilm;
            Status = (int)Extensions.Status.Approved;
        }

        [ControlHidden]
        public long Id { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.CategoryIds + "').empty();")]
        public string LanguageCode { get; set; }

        [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public int SiteId { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Máy chủ mặc định", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public int ServerId { get; set; }

        [ControlChoice(ControlChoice.DropDownList, EnableChosen = true, CssClass = Extensions.Constants.CssControlCustom, Required = true, LabelText = "Đạo diễn", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public int DirectorId { get; set; }

        [ControlCascadingDropDown(AllowMultiple = true, EnableChosen = true, LabelText = "Chuyên mục hiển thị", ParentControl = "SiteId", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public int[] CategoryIds { get; set; }

        [ControlChoice(ControlChoice.DropDownList, AllowMultiple = true, CssClass = Extensions.Constants.CssControlCustom, EnableChosen = true, Required = true, LabelText = "Thể loại phim", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public int[] FilmTypeIds { get; set; }

        [ControlChoice(ControlChoice.DropDownList, AllowMultiple = true, EnableChosen = true, CssClass = Extensions.Constants.CssControlCustom, Required = true, LabelText = "Diễn viên", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public int[] ActorIds { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Phim chiếu rạp", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)]
        public bool IsTheater { get; set; }

        [ControlChoice(ControlChoice.DropDownList, LabelText = "Nhóm phim", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)]
        public int FilmGroup { get; set; }

        [ControlCascadingDropDown(LabelText = "Tên bộ phim", EnableChosen = true, CssClass = Extensions.Constants.CssControlCustom, ParentControl = "FilmGroup", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)]
        public int CollectionId { get; set; }

        [ControlChoice(ControlChoice.DropDownList, EnableChosen = true, CssClass = Extensions.Constants.CssControlCustom, Required = true, LabelText = "Nước sản xuất", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)]
        public int CountryId { get; set; }

        [ControlChoice(ControlChoice.DropDownList, LabelText = "Loại video", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 3)]
        public int VideoType { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Tên phim tiếng việt", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 3)]
        public string FilmName { get; set; }

        [ControlText(Type = ControlText.TextBox, MaxLength = 250, LabelText = "Tên phim tiếng anh", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 3)]
        public string FilmNameEnglish { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Tên không dấu", PlaceHolder = "Mặc định để trống tự sinh theo tên phim tiếng việt", MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)]
        public string FilmAlias { get; set; } 

        [ControlFileUpload(EnableFineUploader = true, LabelText = "Ảnh đại diện", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 4, Required = true, ShowThumbnail = true)]
        public string ImageIcon { get; set; }

        [ControlFileUpload(EnableFineUploader = true, LabelText = "Ảnh đại diện lớn", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 4, Required = true, ShowThumbnail = true)]
        public string ImageThumb { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Hiện trên trang chủ", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 5)]
        public bool IsHome { get; set; }

        [ControlNumeric(LabelText = "Năm sản xuất", MinimumValue = "1900", MaximumValue = "2050", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 5)]
        public int ReleaseYear { get; set; }

        [ControlText(Required = true, MaxLength = 50, LabelText = "Thời gian(Phút)", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 5)]
        public string Time { get; set; }

        [ControlText(Required = true, MaxLength = 50, LabelText = "Tổng dung lượng(MB)", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 5)]
        public string Capacity { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Có bản quyền", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 6)]
        public bool HasCopyright { get; set; }

        [ControlNumeric(LabelText = "Giá nhập", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 6)]
        public float Prices { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Xuất bản", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 6)]
        public bool IsPublished { get; set; }

        [ControlDatePicker(LabelText = "Ngày xuất bản", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 6)]
        public string PublishedDate { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Phim hot", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 7)]
        public bool IsHot { get; set; }

        [ControlDatePicker(LabelText = "Từ ngày", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 7)]
        public string StartDate { get; set; }

        [ControlDatePicker(LabelText = "Đến ngày", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 7)]
        public string EndDate { get; set; }

        [ControlChoice(ControlChoice.DropDownList, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 7)]
        public int Status { get; set; }

        [ControlText(LabelText = "Tóm tắt phim", PlaceHolder = "Tối đa 400 ký tự.", Type = ControlText.MultiText, Rows = 3, Required = true, MaxLength = 400, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 8)]
        public string Summary { get; set; }

        [ControlText(LabelText = "Nội dung phim", Required = true, Type = ControlText.RichText, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 9)]
        public string Contents { get; set; }

        [ControlText(LabelText = "Từ khóa SEO", Required = true, PlaceHolder = "Tối đa 400 ký tự.", Type = ControlText.MultiText, Rows = 2, MaxLength = 400, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 10)]
        public string Description { get; set; }

        [ControlText(LabelText = "Tags SEO", Required = true, PlaceHolder = "Nhập từ khóa SEO cách nhau bởi dấu ','và tối đa 250 ký tự.", Type = ControlText.MultiText, Rows = 2, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 10)]
        public string Tags { get; set; }
        
        public static implicit operator FilmModel(FilmInfo entity)
        {
            var item = new FilmModel
            {
                Id = entity.Id,
                FilmNameEnglish = entity.FilmNameEnglish,
                FilmName = entity.FilmName,
                FilmAlias = entity.FilmAlias,
                LanguageCode = entity.LanguageCode,
                SiteId = entity.SiteId,
                CategoryIds = Utilities.ParseListInt(entity.CategoryIds),
                FilmTypeIds = Utilities.ParseListInt(entity.FilmTypeIds),
                CountryId = entity.CountryId,
                DirectorId = entity.DirectorId,
                ActorIds = Utilities.ParseListInt(entity.ActorIds),
                CollectionId = entity.CollectionId,
                Time = entity.Time,
                Capacity = entity.Capacity,
                ReleaseYear = entity.ReleaseYear,
                Contents = entity.Contents,
                Summary = entity.Summary,
                Description = entity.Description,
                Tags = entity.Tags,
                IsPublished = entity.IsPublished,
                IsHot = entity.IsHot,
                IsHome = entity.IsHome,
                Prices = (float)entity.Prices,
                HasCopyright = entity.HasCopyright,
                ImageIcon = entity.ImageIcon,
                ImageThumb = entity.ImageThumb,
                ServerId = entity.ServerId,
                Status = entity.Status,
                IsTheater = entity.IsTheater
            };
            if (entity.IsFilm)
            {
                item.VideoType = (int)VideoTypes.IsFilm;
            }
            if (entity.IsShow)
            {
                item.VideoType = (int)VideoTypes.IsShow;
            }
            if (entity.IsClip)
            {
                item.VideoType = (int)VideoTypes.IsClip;
            }
            if (entity.IsTrailer)
            {
                item.VideoType = (int)VideoTypes.IsTrailer;
            }
            if (entity.PublishedDate != null 
                && entity.PublishedDate.Value.ToString(Extensions.Constants.DateTimeFomat) != Extensions.Constants.DateTimeMin)
            {
                item.PublishedDate = entity.PublishedDate.Value.ToString(Extensions.Constants.DateTimeFomat);
            }

            if (entity.StartDate != null 
                && entity.StartDate.Value.ToString(Extensions.Constants.DateTimeFomat) != Extensions.Constants.DateTimeMin)
            {
                item.StartDate = entity.StartDate.Value.ToString(Extensions.Constants.DateTimeFomat);
            }

            if (entity.EndDate != null 
                && entity.EndDate.Value.ToString(Extensions.Constants.DateTimeFomat) != Extensions.Constants.DateTimeMin)
            {
                item.EndDate = entity.EndDate.Value.ToString(Extensions.Constants.DateTimeFomat);
            }

            return item;
        }
    }
}
<file_sep>﻿using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IDownloadGameService : IGenericService<DownloadGameInfo, int>, IDependency
    {
        IList<DownloadGameInfo> SearchPaged(string keyword, int pageIndex, int pageSize, out int totalRecord);

        List<DownloadGameInfo> GetPaged(int pageIndex, int pageSize, out int totalRecord);
    }

    public class DownloadGameService : GenericService<DownloadGameInfo, int>, IDownloadGameService
    {
        public DownloadGameService(IRepository<DownloadGameInfo, int> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public IList<DownloadGameInfo> SearchPaged(string keyword, int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Keyword", keyword),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<DownloadGameInfo>("sp_DownloadGames_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public List<DownloadGameInfo> GetPaged(int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<DownloadGameInfo>("sp_DownloadGames_GetPaged", "@TotalRecord", out totalRecord, list.ToArray());
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Caching;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IArticlesService : ICacheService<ArticlesInfo, int>, IGenericService<ArticlesInfo, int>, IDependency
    {
        bool CheckAlias(string alias);

        string LanguageCode { get; set; }

        int CategoryId { get; set; }

        int SiteId { get; set; }

        List<ArticlesInfo> SearchPaged(
            string searchText, 
            int siteId,
            int userId,
            DateTime fromDate, 
            DateTime toDate, 
            int status,
            int pageIndex, 
            int pageSize,
            out int totalRecord);

        IList<ArticlesInfo> BuildNewsByCategory();

        IList<ArticlesInfo> GetByCategory();

        IList<ArticlesInfo> GetByCategoryPaged(int pageIndex, int pageSize, out int totalRecord);
    }

    public class ArticlesService : GenericService<ArticlesInfo, int>, IArticlesService
    {
        private readonly ICacheInfo cacheManager;
        public string LanguageCode { get; set; }
        public int CategoryId { get; set; }
        public int SiteId { get; set; }

        public ArticlesService(
            IRepository<ArticlesInfo, int> repository, 
            IEventBus eventBus, ICacheInfo cacheManager) 
            : base(repository, eventBus)
        {
            this.cacheManager = cacheManager;
        }

        public bool CheckAlias(string alias)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Alias", alias)
            };
            var result = (int)ExecuteReaderResult("sp_Articles_CheckAlias", list.ToArray());

            return result > 0;
        }

        public List<ArticlesInfo> SearchPaged(string searchText, int siteId, int userId, DateTime fromDate, DateTime toDate, int status, int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SearchText", searchText),
                AddInputParameter("@SiteId", siteId),
                AddInputParameter("@CategoryId", CategoryId),
                AddInputParameter("@UserId", userId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@FromDate", fromDate),
                AddInputParameter("@Todate", toDate),
                AddInputParameter("@Status", status),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<ArticlesInfo>("sp_Articles_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public IList<ArticlesInfo> GetByCategory()
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@CategoryId", CategoryId)
            };

            return ExecuteReader<ArticlesInfo>("sp_Articles_GetByCategory", list.ToArray());
        }

        public IList<ArticlesInfo> GetByCategoryPaged(int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                 AddInputParameter("@SiteId", SiteId),
                AddInputParameter("@LanguageCode", LanguageCode),
                AddInputParameter("@CategoryId", CategoryId),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<ArticlesInfo>("sp_Articles_GetByCategory_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public IList<ArticlesInfo> BuildNewsByCategory()
        {
            var list = cacheManager.Get(string.Format(Extensions.Constants.CacheKeys.HOME_CATEGORY_ID, CategoryId));
            if (list == null)
            {
                list = ResetCache();
            }

            return (IList<ArticlesInfo>)list;
        }

        public ArticlesInfo GetByIdCache(int id)
        {
            throw new NotImplementedException();
        }

        public IList<ArticlesInfo> GetAllCache()
        {
            throw new NotImplementedException();
        }

        public IList<ArticlesInfo> ResetCache()
        {
            cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_CATEGORY_ID, CategoryId));
            var list = GetByCategory();
            cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_CATEGORY_ID, CategoryId), list);

            return list;
        }
    }
}
<file_sep>using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class CustomerInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("CustomerCode")]
        public string CustomerCode { get; set; }

        [DataMember]
        [DisplayName("UserName")]
        public string UserName { get; set; }

        [DataMember]
        [DisplayName("Password")]
        public string Password { get; set; }

        [DataMember]
        [DisplayName("FullName")]
        public string FullName { get; set; }

        [DataMember]
        [DisplayName("Email")]
        public string Email { get; set; }

        [DataMember]
        [DisplayName("Address")]
        public string Address { get; set; }

        [DataMember]
        [DisplayName("PhoneNumber")]
        public string PhoneNumber { get; set; }

        [DataMember]
        [DisplayName("CityId")]
        public string CityId { get; set; }

        [DataMember]
        [DisplayName("Birthday")]
        public System.DateTime Birthday { get; set; }

        [DataMember]
        [DisplayName("Sex")]
        public int Sex { get; set; }

        [DataMember]
        [DisplayName("ImageIcon")]
        public string ImageIcon { get; set; }

        [DataMember]
        [DisplayName("FilmTypeIds")]
        public string FilmTypeIds { get; set; }

        [DataMember]
        [DisplayName("CountryIds")]
        public string CountryIds { get; set; }

        [DataMember]
        [DisplayName("MemberDate")]
        public System.DateTime MemberDate { get; set; }

        [DataMember]
        [DisplayName("Skype")]
        public string Skype { get; set; }

        [DataMember]
        [DisplayName("ZingMe")]
        public string ZingMe { get; set; }

        [DataMember]
        [DisplayName("Facebook")]
        public string Facebook { get; set; }

        [DataMember]
        [DisplayName("Google")]
        public string Google { get; set; }

        [DataMember]
        [DisplayName("Yahoo")]
        public string Yahoo { get; set; }

        [DataMember]
        [DisplayName("VipXu")]
        public decimal VipXu { get; set; }

        [DataMember]
        [DisplayName("TotalMoney")]
        public decimal TotalMoney { get; set; }

        [DataMember]
        [DisplayName("IsBlock")]
        public bool IsBlock { get; set; }

        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }

        [DataMember]
        [DisplayName("Description")]
        public string Description { get; set; }

        [DataMember]
        [DisplayName("TotalDay")]
        public int TotalDay { get; set; }

        [DataMember]
        [DisplayName("StartDate")]
        public DateTime? StartDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextStartDate
        {
            get
            {
                if (StartDate == null)
                {
                    return "";
                }

                return StartDate.Value.ToString(Extensions.Constants.DateTimeFomatFull);
            }
        }

        [DataMember]
        [DisplayName("EndDate")]
        public DateTime? EndDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextEndDate
        {
            get
            {
                if (EndDate == null)
                {
                    return "";
                }

                return EndDate.Value.ToString(Extensions.Constants.DateTimeFomatFull);
            }
        }

        [DataMember]
        [DisplayName("IsTest")]
        public bool IsTest { get; set; }
    }

    public class CustomerMap : EntityTypeConfiguration<CustomerInfo>, IEntityTypeConfiguration
    {

        public CustomerMap()
        {
            ToTable("Modules_Customers");
            HasKey(m => m.Id);
            Property(m => m.CustomerCode).IsRequired().HasMaxLength(250);
            Property(m => m.UserName).IsRequired().HasMaxLength(50);
            Property(m => m.Password).IsRequired().HasMaxLength(500);
            Property(m => m.FullName).IsRequired().HasMaxLength(250);
            Property(m => m.Email).IsRequired().HasMaxLength(50);
            Property(m => m.Address).HasMaxLength(2000);
            Property(m => m.PhoneNumber).HasMaxLength(50);
            Property(m => m.CityId).HasMaxLength(250);
            Property(m => m.ImageIcon).IsRequired().HasMaxLength(300);
            Property(m => m.FilmTypeIds).HasMaxLength(2000);
            Property(m => m.CountryIds).HasMaxLength(2000);
            Property(m => m.MemberDate).IsRequired();
            Property(m => m.Skype).HasMaxLength(50);
            Property(m => m.ZingMe).HasMaxLength(50);
            Property(m => m.Facebook).HasMaxLength(50);
            Property(m => m.Google).HasMaxLength(50);
            Property(m => m.Yahoo).HasMaxLength(50);
            Property(m => m.IsBlock).IsRequired();
            Property(m => m.Description).HasMaxLength(500);
        }
    }
}
<file_sep>﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class TransactionBankInfo : BaseEntity<long>
    {
        [DataMember]
        [DisplayName("CustomerCode")]
        public string CustomerCode { get; set; }

        [DataMember]
        [DisplayName("TransactionCode")]
        public string TransactionCode { get; set; }

        [DataMember]
        [DisplayName("CreateDate")]
        public DateTime CreateDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextStartDate
        {
            get
            {
                return CreateDate.ToString(Extensions.Constants.DateTimeFomatFull);
            }
        }

        [DataMember]
        [DisplayName("BankCode")]
        public string BankCode { get; set; }

        [NotMapped]
        [DisplayName("BankName")]
        public string BankName { get; set; }

        [DataMember]
        [DisplayName("Amount")]
        public string Amount { get; set; }

        [DataMember]
        [DisplayName("ResponCode")]
        public string ResponCode { get; set; }

        [DataMember]
        [DisplayName("Mac")]
        public string Mac { get; set; }

        [DataMember]
        [DisplayName("TransId")]
        public string TransId { get; set; }

        [DataMember]
        [DisplayName("Type")]
        public int Type { get; set; }

        [DataMember]
        [DisplayName("Description")]
        public string Description { get; set; }

        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }

        [DataMember]
        [DisplayName("IsLock")]
        public bool IsLock { get; set; }

        [NotMapped]
        [DisplayName("FullName")]
        public string FullName { get; set; }
    }

    public class TransactionBankMap : EntityTypeConfiguration<TransactionBankInfo>, IEntityTypeConfiguration
    {
        public TransactionBankMap()
        {
            ToTable("Modules_TransactionBank");
            HasKey(m => m.Id);
            Property(m => m.CustomerCode).HasMaxLength(50);
            Property(m => m.TransactionCode).HasMaxLength(250);
            Property(m => m.BankCode).HasMaxLength(50);
            Property(m => m.Amount).HasMaxLength(250);
            Property(m => m.ResponCode).HasMaxLength(100);
            Property(m => m.Mac).HasMaxLength(250);
            Property(m => m.TransId).HasMaxLength(250);
            Property(m => m.Description).HasMaxLength(2000);
        }
    }
}<file_sep>﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace CMSSolutions.Websites.Extensions
{
    public class FTPClient
    {
        public string ServerIP { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public int BufferSize { get; set; }

        public FTPClient()
        {
            BufferSize = 2048;
        }

        public FTPClient(string hostIP, string userName, string password)
        {
            ServerIP = hostIP;
            UserName = userName;
            Password = <PASSWORD>;
            BufferSize = 2048;
        }

        private string GetUrl(string path)
        {
            return "ftp://" + ServerIP + "/" + path;
        }

        public void Download(string remoteFile, string localFile)
        {
            try
            {
                var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(remoteFile));
                ftpRequest.Credentials = new NetworkCredential(UserName, Password);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                Stream ftpStream = ftpResponse.GetResponseStream();
                if (ftpStream != null)
                {
                    var localFileStream = new FileStream(localFile, FileMode.Create);
                    var byteBuffer = new byte[BufferSize];
                    int bytesRead = ftpStream.Read(byteBuffer, 0, BufferSize);
                    while (bytesRead > 0)
                    {
                        localFileStream.Write(byteBuffer, 0, bytesRead);
                        bytesRead = ftpStream.Read(byteBuffer, 0, BufferSize);
                    }
                    localFileStream.Close();
                    ftpStream.Close();
                }

                ftpResponse.Close();               
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Upload(string remoteFile, string localFile)
        {
            try
            {
                var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(remoteFile));
                ftpRequest.Credentials = new NetworkCredential(UserName, Password);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
                Stream ftpStream = ftpRequest.GetRequestStream();
                if (ftpStream != null)
                {
                    var localFileStream = new FileStream(localFile, FileMode.Create);
                    var byteBuffer = new byte[BufferSize];
                    int bytesSent = localFileStream.Read(byteBuffer, 0, BufferSize);
                    while (bytesSent != 0)
                    {
                        ftpStream.Write(byteBuffer, 0, bytesSent);
                        bytesSent = localFileStream.Read(byteBuffer, 0, BufferSize);
                    }
                    localFileStream.Close();
                    ftpStream.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Delete(string deleteFile)
        {
            try
            {
                var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(deleteFile));
                ftpRequest.Credentials = new NetworkCredential(UserName, Password);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
                var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                ftpResponse.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Rename(string currentFileNameAndPath, string newFileName)
        {
            try
            {
                var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(currentFileNameAndPath));
                ftpRequest.Credentials = new NetworkCredential(UserName, Password);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Method = WebRequestMethods.Ftp.Rename;
                ftpRequest.RenameTo = newFileName;
                var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                ftpResponse.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void CreateDirectory(string newDirectory)
        {
            try
            {
                var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(newDirectory));
                ftpRequest.Credentials = new NetworkCredential(UserName, Password);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
                var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                ftpResponse.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string GetFileCreatedDateTime(string fileName)
        {
            try
            {
                var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(fileName));
                ftpRequest.Credentials = new NetworkCredential(UserName, Password);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp;
                var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                Stream ftpStream = ftpResponse.GetResponseStream();
                if (ftpStream != null)
                {
                    var ftpReader = new StreamReader(ftpStream);
                    string fileInfo = ftpReader.ReadToEnd();
                    ftpReader.Close();
                    ftpStream.Close();
                    ftpResponse.Close();
                    return fileInfo;
                }

                ftpResponse.Close();
                return string.Empty;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string GetFileSize(string fileName)
        {
            try
            {
                var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(fileName));
                ftpRequest.Credentials = new NetworkCredential(UserName, Password);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
                var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                Stream ftpStream = ftpResponse.GetResponseStream();
                if (ftpStream != null)
                {
                    var ftpReader = new StreamReader(ftpStream);
                    string fileInfo = null;
                    while (ftpReader.Peek() != -1)
                    {
                        fileInfo = ftpReader.ReadToEnd();
                    }
                    ftpReader.Close();
                    ftpStream.Close();
                    ftpResponse.Close();

                    return fileInfo;
                }

                ftpResponse.Close();
                return string.Empty;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string[] DirectoryList(string directory)
        {
            try
            {
                var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(directory));
                ftpRequest.Credentials = new NetworkCredential(UserName, Password);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
                var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                Stream ftpStream = ftpResponse.GetResponseStream();
                if (ftpStream != null)
                {
                    var ftpReader = new StreamReader(ftpStream);
                    string directoryRaw = null;
                    while (ftpReader.Peek() != -1)
                    {
                        directoryRaw += ftpReader.ReadLine() + "|";
                    }

                    ftpReader.Close();
                    ftpStream.Close();
                    ftpResponse.Close();
                    if (directoryRaw != null)
                    {
                        return directoryRaw.Split("|".ToCharArray());
                    }
                }

                ftpResponse.Close();
                return new[] { "" }; 
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string[] DirectoryListDetailed(string directory)
        {
            try
            {
                var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(directory));
                ftpRequest.Credentials = new NetworkCredential(UserName, Password);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                Stream ftpStream = ftpResponse.GetResponseStream();
                if (ftpStream != null)
                {
                    var ftpReader = new StreamReader(ftpStream);
                    string directoryRaw = null;
                    while (ftpReader.Peek() != -1)
                    {
                        directoryRaw += ftpReader.ReadLine() + "|";
                    }
                    ftpReader.Close();
                    ftpStream.Close();
                    ftpResponse.Close();
                    if (directoryRaw != null)
                    {
                        string[] directoryList = directoryRaw.Split("|".ToCharArray());
                        return directoryList;
                    }
                }

                ftpResponse.Close();
                return new[] { "" }; 
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}<file_sep>using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IBankCardService : IGenericService<BankCardInfo, int>, IDependency
    {
        IList<BankCardInfo> GetPaged(int status, int pageIndex, int pageSize, out int totals);

        BankCardInfo GetByCode(string code);
    }

    public class BankCardService : GenericService<BankCardInfo, int>, IBankCardService
    {
        public BankCardService(IRepository<BankCardInfo, int> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public IList<BankCardInfo> GetPaged(int status, int pageIndex, int pageSize, out int totals)
        {
            var results = Repository.Table.Where(x => x.Status == status).ToList();
            {
                totals = results.Count();
                return (from x in results select x).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
        }

        public BankCardInfo GetByCode(string code)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Code", code)
            };

            return ExecuteReaderRecord<BankCardInfo>("sp_BankCards_GetByCode", list.ToArray());
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface ILogService : IGenericService<LogInfo, long>, IDependency
    {
        IList<LogInfo> GetPaged(string keyword, DateTime fromDate, DateTime toDate, int type, int status, int pageIndex, int pageSize, out int totals);
    }

    public class LogService : GenericService<LogInfo, long>, ILogService
    {
        public LogService(IRepository<LogInfo, long> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        protected override IOrderedQueryable<LogInfo> MakeDefaultOrderBy(IQueryable<LogInfo> queryable)
        {
            return queryable.OrderByDescending(x => x.CreateDate);
        }

        public IList<LogInfo> GetPaged(string keyword, DateTime fromDate, DateTime toDate, 
            int type, int status, int pageIndex, int pageSize, out int totals)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SearchText", keyword),
                AddInputParameter("@FromDate", fromDate),
                AddInputParameter("@ToDate", toDate),
                AddInputParameter("@Type", type),
                AddInputParameter("@Status", status),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<LogInfo>("sp_Logs_Search_Paged", "@TotalRecord", out totals, list.ToArray());
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IAdvertisementService : IGenericService<AdvertisementInfo, int>, IDependency
    {
        List<AdvertisementInfo> SearchPaged(
            string searchText,
            string languageCode,
            int siteId,
            DateTime fromDate,
            DateTime toDate,
            int pageIndex,
            int pageSize,
            out int totalRecord);

        List<AdvertisementInfo> GetAdBySite(string languageCode, int siteId);
    }

    public class AdvertisementService : GenericService<AdvertisementInfo, int>, IAdvertisementService
    {
        public AdvertisementService(IRepository<AdvertisementInfo, int> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public List<AdvertisementInfo> SearchPaged(string searchText, string languageCode, int siteId, DateTime fromDate, DateTime toDate, int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SearchText", searchText),
                AddInputParameter("@LanguageCode", languageCode),
                AddInputParameter("@SiteId", siteId),
                AddInputParameter("@FromDate", fromDate),
                AddInputParameter("@Todate", toDate),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<AdvertisementInfo>("sp_Advertisement_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }

        public List<AdvertisementInfo> GetAdBySite(string languageCode, int siteId)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@LanguageCode", languageCode),
                AddInputParameter("@SiteId", siteId)
            };

            return ExecuteReader<AdvertisementInfo>("sp_Advertisement_GetAdBySite", list.ToArray());
        }
    }
}<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Extensions;

namespace CMSSolutions.Websites.Models
{
    public class PromotionCustomersModel
    {
        public PromotionCustomersModel()
        {
            Code = Utilities.GenerateUniqueNumber();
            Value = 50;
        }

        [ControlHidden]
        public int PromotionId { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 50, LabelText = "Chương trình khuyến mãi", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 0)]
        public string PromotionName { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 50, LabelText = "Mã khuyến mãi", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 1)]
        public string Code { get; set; }

        [ControlNumeric(LabelText = "Giá trị khuyến mãi (VIPXU)", MinimumValue = "50", Required = true, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 1)]
        public int Value { get; set; }

        [ControlChoice(ControlChoice.DropDownList, AllowMultiple = true, CssClass = Extensions.Constants.CssControlCustom, EnableChosen = true, Required = true, LabelText = "Chọn khách hàng", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 2)]
        public int[] CustomerIds { get; set; }
    }
}<file_sep>﻿using System.ComponentModel;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    /// <summary>
    /// Bộ phim
    /// </summary>
    [DataContract]
    public class CollectionInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }
        
        [DataMember]
        [DisplayName("SiteId")]
        public int SiteId { get; set; }
        
        [DataMember]
        [DisplayName("Name")]
        public string Name { get; set; }

        [DataMember]
        [DisplayName("IsHost")]
        public bool IsHot { get; set; }

        [DataMember]
        [DisplayName("OrderBy")]
        public int OrderBy { get; set; }

        [DataMember]
        [DisplayName("Description")]
        public string Description { get; set; }
        
        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }
    }

    public class CollectionMap : EntityTypeConfiguration<CollectionInfo>, IEntityTypeConfiguration
    {

        public CollectionMap()
        {
            ToTable("Modules_Collections");
            HasKey(m => m.Id);
            Property(m => m.LanguageCode).IsRequired().HasMaxLength(50);
            Property(m => m.SiteId).IsRequired();
            Property(m => m.Name).IsRequired().HasMaxLength(250);
            Property(m => m.Description).HasMaxLength(2000);
        }
    }
}
<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class FilmTypesModel
    {
        [ControlHidden]
        public int Id { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public string LanguageCode { get; set; }

        [ControlCascadingDropDown(LabelText = "Trang web", Required = true, ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public int SiteId { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Tên thể loại phim", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)]
        public string Name { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Phim trang chủ", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 3)]
        public bool IsFilm { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Show", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 3)]
        public bool IsShow { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Clip", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 3)]
        public bool IsClip { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Phim trang JJ", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 3)]
        public bool IsJJFilm { get; set; }

        [ControlChoice(ControlChoice.DropDownList, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 3)]
        public int Status { get; set; }

        [ControlText(Type = ControlText.MultiText, Rows = 2, MaxLength = 2000, LabelText = "Giới thiệu", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 4)]
        public string Description { get; set; }
        
        public static implicit operator FilmTypesModel(FilmTypesInfo entity)
        {
            return new FilmTypesModel
            {
                Id = entity.Id,
                LanguageCode = entity.LanguageCode,
                SiteId = entity.SiteId,
                Name = entity.Name,
                Description = entity.Description,
                Status = entity.Status,
                IsFilm =  entity.IsFilm,
                IsShow = entity.IsShow,
                IsClip = entity.IsClip,
                IsJJFilm = entity.IsJJFilm
            };
        }
    }
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IFilmServersService : IGenericService<FilmServerInfo, int>, IDependency
    {
        IList<FilmServerInfo> GetPaged(string languageCode, int siteId, int status, int pageIndex, int pageSize, out int totals);
    }

    public class FilmServersService : GenericService<FilmServerInfo, int>, IFilmServersService
    {
        public FilmServersService(IRepository<FilmServerInfo, int> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public IList<FilmServerInfo> GetPaged(string languageCode, int siteId, int status, int pageIndex, int pageSize, out int totals)
        {
            var results = Repository.Table.Where(x => x.Status == status && x.LanguageCode == languageCode && x.SiteId == siteId).ToList();
            {
                totals = results.Count();
                return (from x in results select x).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
        }
    }
}
<file_sep>function dialogBox(id) {
    $(id).fadeIn("slow");
    $('body').append('<div id="over"></div>');
    $('#over').fadeIn(300);
}

$(document).ready(function () {
    $(document).on('click', "a.close-reveal-modal, #over", function () {
        $('#over, .reveal-modal').fadeOut(300, function () {
            $('#over').remove();  
        });
        
        return false;
    });
});


<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using CMSSolutions.Configuration;
using CMSSolutions.Security.Cryptography;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Security;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class FilmFilesController : BaseAdminController
    {
        public FilmFilesController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor)
        {
            TableName = "tblVideoFiles";
        }

        [Url("admin/video-files")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý video files"), Url = "#" });

            var result = new ControlGridFormResult<FilmFilesInfo>
            {
                Title = T("Quản lý video files"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetFilmFiles,
                DefaultPageSize = WorkContext.DefaultPageSize,
                EnablePaginate = true,
                UpdateActionName = "Update",
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml,
                ClientId = TableName,
                ActionsColumnWidth = 100
            };

            result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.ServerId + "').val();", true);

            result.AddColumn(x => x.Name, T("Tên file"));
            result.AddColumn(x => x.FullPath, T("Đường dẫn đầy đủ"));
            result.AddColumn(x => x.ServerName, T("Máy chủ"));
            result.AddColumn(x => x.DisplayDate, T("Ngày tạo")).HasWidth(100);
            result.AddColumn(x => x.Size, T("Kích thước")).HasWidth(100).AlignCenter();
            result.AddColumn(x => x.HasUse, T("Sử dụng"))
                .HasHeaderText(T("Sử dụng"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage();

            result.AddAction().HasText(T("Đồng bộ videos"))
                .HasUrl(Url.Action("RefreshVideos"))
                .HasButtonStyle(ButtonStyle.Primary)
                .HasBoxButton(false)
                .HasRow(false)
                .HasCssClass(Constants.RowLeft)
                .HasRow(true)
                .ShowModalDialog();

            result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildSiteServers(true, Extensions.Constants.ServerId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildServers)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
                 .HasText(T("Xem"))
                 .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                 .HasButtonStyle(ButtonStyle.Default)
                 .HasButtonSize(ButtonSize.ExtraSmall);

            //result.AddRowAction(true)
            //   .HasText(T("Xóa"))
            //   .HasName("Delete")
            //   .HasValue(x => x.Id)
            //   .HasButtonStyle(ButtonStyle.Danger)
            //   .HasButtonSize(ButtonSize.ExtraSmall)
            //   .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");
            return result;
        }

        private ControlGridAjaxData<FilmFilesInfo> GetFilmFiles(ControlGridFormRequest options)
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var serverId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ServerId]))
            {
                serverId = Convert.ToInt32(Request.Form[Extensions.Constants.ServerId]);
            }

            int totals;
            var items = WorkContext.Resolve<IFilmFilesService>().SearchPaged(string.Empty, languageCode, siteId, serverId, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<FilmFilesInfo>(items, totals);

            return result;
        }

        [Themed(false)]
        [Url("admin/video-files/refresh-videos")]
        public ActionResult RefreshVideos()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý video files"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Đồng bộ videos từ máy chủ"), Url = "#" });
            var model = new VideoRefreshModel();
            var result = new ControlFormResult<VideoRefreshModel>(model)
            {
                Title = T("Đồng bộ videos từ máy chủ"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Refresh",
                SubmitButtonText = T("Đồng bộ"),
                CancelButtonText = T("Đóng"),
                ShowBoxHeader = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.RegisterExternalDataSource(x => x.ServerId, y => BindServers());
            result.RegisterCascadingDropDownDataSource(x => x.RootFolders, Url.Action("GetRootFolders"));
            result.RegisterCascadingDropDownDataSource(x => x.ChildrenFolders, Url.Action("GetChildrenFolders"));

            return result;
        }

        [Url("admin/video-files/get-children-folders")]
        public ActionResult GetChildrenFolders()
        {
            var serverId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ServerId]))
            {
                serverId = Convert.ToInt32(Request.Form[Extensions.Constants.ServerId]);
            }

            var rootFolderName = Extensions.Constants.ValueAll;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.RootFolders]))
            {
                rootFolderName = Request.Form[Extensions.Constants.RootFolders];
            }

            var items = new List<SelectListItem>();
            string rootFolder;
            string languageCode;
            int siteId;
            var client = GetConnectionFtp(serverId, out rootFolder, out languageCode, out siteId);
            if (client != null)
            {
                var list = client.DirectoryList(rootFolderName);
                foreach (var folderPath in list)
                {
                    if (string.IsNullOrEmpty(folderPath))
                    {
                        continue;
                    }

                    if (rootFolderName == Extensions.Constants.ValueAll)
                    {
                        items.Add(new SelectListItem {Text = folderPath, Value = folderPath});
                        continue;
                    }

                    var index = folderPath.LastIndexOf('/');
                    if (index != -1)
                    {
                        var folderName = folderPath.Substring(index + 1, folderPath.Length - (index + 1));
                        items.Add(new SelectListItem { Text = string.Format("{0}/{1}", rootFolder, folderName), Value = folderName });
                    }
                }
            }

            return Json(items);
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/video-files/refresh")]
        public ActionResult Refresh(VideoRefreshModel model)
        {
            var childrenFolders = Extensions.Constants.ValueAll;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ChildrenFolders]))
            {
                childrenFolders = Request.Form[Extensions.Constants.ChildrenFolders];
            }

            if (!string.IsNullOrEmpty(childrenFolders))
            {
                var service = WorkContext.Resolve<IFilmFilesService>();
                string rootFolder;
                string languageCode;
                int siteId;
                var client = GetConnectionFtp(model.ServerId, out rootFolder, out languageCode, out siteId);
                if (client != null)
                {
                    var folder = string.Empty;
                    var f = rootFolder.LastIndexOf('/');
                    if (f != -1)
                    {
                        folder = rootFolder.Substring(f + 1, rootFolder.Length - (f + 1));
                    }
                    var list = childrenFolders.Split(',');
                    foreach (var path in list)
                    {
                        if (string.IsNullOrEmpty(path))
                        {
                            continue;
                        }

                        var listFolderFiles = client.DirectoryList(string.Format("{0}/{1}", rootFolder, path));
                        if (listFolderFiles != null && listFolderFiles.Any())
                        {
                            foreach (var folderFilePath in listFolderFiles)
                            {
                                if (string.IsNullOrEmpty(folderFilePath))
                                {
                                    continue;
                                }

                                var listFiles = client.DirectoryList(string.Format("{0}/{1}", rootFolder, folderFilePath));
                                if (listFiles != null && listFiles.Any())
                                {
                                    var folderName = string.Empty;
                                    var n = folderFilePath.LastIndexOf('/');
                                    if (n != -1)
                                    {
                                        folderName = folderFilePath.Substring(n + 1, folderFilePath.Length - (n + 1));
                                    }
                                    foreach (var filePath in listFiles)
                                    {
                                        if (string.IsNullOrEmpty(filePath))
                                        {
                                            continue;
                                        }

                                        var index = filePath.LastIndexOf('/');
                                        if (index != -1)
                                        {
                                            var fileName = filePath.Substring(index + 1, filePath.Length - (index + 1));
                                            var fullPath = string.Format("{0}/{1}/{2}", rootFolder, folderFilePath, fileName);
                                            var info = service.GetByFullPathFile(fullPath);
                                            if (info == null)
                                            {
                                                var y = fileName.LastIndexOf('.');
                                                if (y != -1)
                                                {
                                                    var extentions = fileName.Substring(y + 1, fileName.Length - (y + 1));
                                                    var file = new FilmFilesInfo
                                                    {
                                                        Id = 0,
                                                        LanguageCode = languageCode,
                                                        SiteId = siteId,
                                                        ServerId = model.ServerId,
                                                        Name = string.Empty,
                                                        FolderRoot = rootFolder,
                                                        FileName = fileName,
                                                        FolderName = folderName,
                                                        FolderDay = path,
                                                        FolderPath = string.Format("{0}/{1}", folder, folderFilePath),
                                                        Extentions = extentions,
                                                        FullPath = fullPath,
                                                        Size = "",//client.GetFileSize(fullPath),
                                                        CreateDate = DateTime.Now.Date,
                                                        HasUse = false,
                                                        FileCode = Guid.NewGuid().ToString().Replace("-", string.Empty)
                                                    };

                                                    service.Insert(file);
                                                }
                                            }
                                        }  
                                    }
                                }
                            }
                        }
                    }
                }
            }
            
            return new AjaxResult()
                .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"));
        }

        [Url("admin/video-files/edit/{id}")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý video files"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin video files"), Url = "#" });

            var model = new FilmFilesModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<IFilmFilesService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<FilmFilesModel>(model)
            {
                Title = T("Thông tin video files"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                ShowCancelButton = true,
                ShowSubmitButton = false,
                ShowBoxHeader = false,
                CancelButtonText = T("Trở về"),
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages());
            result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage"));
            result.RegisterCascadingDropDownDataSource(x => x.ServerId, Url.Action("GetServersBySite"));

            result.MakeReadOnlyProperty(x => x.FolderName);
            result.MakeReadOnlyProperty(x => x.FullPath);
            result.MakeReadOnlyProperty(x => x.FileName);
            result.MakeReadOnlyProperty(x => x.FolderPath);
            result.MakeReadOnlyProperty(x => x.Extentions);
            result.MakeReadOnlyProperty(x => x.FileCode);
            result.MakeReadOnlyProperty(x => x.Size);
            result.MakeReadOnlyProperty(x => x.Name);
            result.MakeReadOnlyProperty(x => x.HasUse);

            return result;
        }
        
        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/video-files/update")]
        public ActionResult Update(FilmFilesModel model)
        {
            if (!ModelState.IsValid)
            {
				return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var service = WorkContext.Resolve<IFilmFilesService>();
            FilmFilesInfo item = model.Id == 0 ? new FilmFilesInfo() : service.GetById(model.Id);

            item.Name = model.Name;
            item.FolderName = model.FolderName;
            item.HasUse = model.HasUse;

            service.Save(item);

            return new AjaxResult()
                .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"));
        }

        //[FormButton("Delete")]
        //[HttpPost, ActionName("Update")]
        //public ActionResult Delete(int id)
        //{
        //    return new AjaxResult()
        //        .NotifyMessage("DELETE_ENTITY_COMPLETE")
        //        .Alert(T("Đã xóa videos thành công !"));
        //}
    }
}
<file_sep>﻿using System;
using System.Web.Mvc;
using CMSSolutions.Configuration;
using CMSSolutions.Extensions;
using CMSSolutions.Security.Cryptography;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Security;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminFilmServerController : BaseAdminController
    {
        public AdminFilmServerController(IWorkContextAccessor workContextAccessor) : 
                base(workContextAccessor)
        {
            TableName = "tblFilmServers";
        }

        [Url("admin/server-films")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý máy chủ phim"), Url = "#" });

            var result = new ControlGridFormResult<FilmServerInfo>
            {
                Title = T("Quản lý máy chủ phim"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetFilmServer,
                UpdateActionName = "Update",
                ActionsColumnWidth = 100,
                ClientId = TableName,
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml
            };

            result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true);

            result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(60);
            result.AddColumn(x => x.ServerName, T("Tên máy chủ"));
            result.AddColumn(x => x.ServerIP, T("Địa chỉ IP"));
            result.AddColumn(x => x.Locations,T("Địa điểm"));
            result.AddColumn(x => x.IsVip)
                .HasHeaderText(T("Máy chủ VIP"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage(false);
            result.AddColumn(x => EnumExtensions.GetDisplayName((Status)x.Status), T("Trạng thái"));

            result.AddAction().HasText(T("Thêm mới"))
                .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
                .HasButtonStyle(ButtonStyle.Primary)
                .HasBoxButton(false)
                .HasCssClass(Constants.RowLeft)
                .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildSites(false, string.Empty))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
                 .HasText(T("Sửa"))
                 .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                 .HasButtonStyle(ButtonStyle.Default)
                 .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddRowAction(true)
                .HasText(T("Xóa"))
                .HasName("Delete")
                .HasValue(x => x.Id)
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");
            return result;
        }

        private ControlGridAjaxData<FilmServerInfo> GetFilmServer(ControlGridFormRequest options)
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var statusId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId]))
            {
                statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]);
            }

            int totals;
            var items = WorkContext.Resolve<IFilmServersService>().GetPaged(languageCode, siteId, statusId, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<FilmServerInfo>(items, totals);

            return result;
        }
       
        [Url("admin/server-films/edit/{id}")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý máy chủ phim"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin máy chủ phim"), Url = "#" });

            var service = WorkContext.Resolve<IFilmServersService>();
            var model = new FilmServerModel();
            if (id > 0)
            {
                model = service.GetById(id);
                string password = EncryptionExtensions.Decrypt(KeyConfiguration.PublishKey, model.Password);
                if (string.IsNullOrEmpty(password))
                {
                    throw new ArgumentException(T(SecurityConstants.ErrorConfigKey).Text);
                }
                model.Password = <PASSWORD>;
                string userName = EncryptionExtensions.Decrypt(KeyConfiguration.PublishKey, model.UserName);
                if (string.IsNullOrEmpty(userName))
                {
                    throw new ArgumentException(T(SecurityConstants.ErrorConfigKey).Text);
                }
                model.UserName = userName;
            }

            var result = new ControlFormResult<FilmServerModel>(model)
            {
                Title = T("Thông tin máy chủ phim"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                CancelButtonText = T("Trở về"),
                ShowBoxHeader = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages());
            result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage"));
            result.RegisterExternalDataSource(x => x.Status, y => BindStatus());

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/server-films/update")]
        public ActionResult Update(FilmServerModel model)
        {
            if (!ModelState.IsValid)
            {
				return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            string password = EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, model.Password);
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException(T(SecurityConstants.ErrorConfigKey).Text);
            }

            string userName = EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, model.UserName);
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentException(T(SecurityConstants.ErrorConfigKey).Text);
            }

            var service = WorkContext.Resolve<IFilmServersService>();
            FilmServerInfo item = model.Id == 0 ? new FilmServerInfo() : service.GetById(model.Id);

            item.LanguageCode = model.LanguageCode;
            item.SiteId = model.SiteId;
            item.ServerName = model.ServerName;
            item.ServerIP = model.ServerIP;
            item.Password = <PASSWORD>;
            item.UserName = userName;
            item.FolderRoot = model.FolderRoot;
            item.IsDefault = model.IsDefault;
            item.Locations = model.Locations;
            item.IsVip = model.IsVip;
            item.Description = model.Description;
            item.Status = model.Status;
            service.Save(item);

            return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"));
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<IFilmServersService>();
            var item = service.GetById(id);
            item.Status = (int)Status.Deleted;
            service.Update(item);

            return new AjaxResult()
                .NotifyMessage("DELETE_ENTITY_COMPLETE")
                .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!"));
        }
    }
}
<file_sep>using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{   
    [DataContract]
    public class VIPCardInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }

        [DataMember]
        [DisplayName("SiteId")]
        public int SiteId { get; set; }

        [DataMember]
        [DisplayName("ServerId")]
        public int ServerId { get; set; }

        [NotMapped]
        [DisplayName("ServerName")]
        public string ServerName { get; set; }

        [DataMember]
        [DisplayName("VIPCode")]
        public string VIPCode { get; set; }

        [DataMember]
        [DisplayName("VIPName")]
        public string VIPName { get; set; }

        [DataMember]
        [DisplayName("VIPValue")]
        public decimal VIPValue { get; set; }
    }

    public class VIPCardMap : EntityTypeConfiguration<VIPCardInfo>, IEntityTypeConfiguration
    {
        public VIPCardMap()
        {
            ToTable("Modules_VIPCards");
            HasKey(m => m.Id);
            Property(m => m.LanguageCode).HasMaxLength(50).IsRequired();
            Property(m => m.SiteId).IsRequired();
            Property(m => m.VIPCode).HasMaxLength(50).IsRequired();
            Property(m => m.VIPName).HasMaxLength(250);
            Property(m => m.VIPValue).IsRequired();
            Property(m => m.ServerId).IsRequired();
        }
    }
}
<file_sep>﻿using System.ComponentModel;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    /// <summary>
    /// Tập phim
    /// </summary>
    [DataContract]
    public class EpisodeInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }
        
        [DataMember]
        [DisplayName("SiteId")]
        public int SiteId { get; set; }
        
        [DataMember]
        [DisplayName("EpisodeName")]
        public string EpisodeName { get; set; }
        
        [DataMember]
        [DisplayName("OrderBy")]
        public int OrderBy { get; set; }
        
        [DataMember]
        [DisplayName("Description")]
        public string Description { get; set; }
        
        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }
    }
    
    public class EpisodeMap : EntityTypeConfiguration<EpisodeInfo>, IEntityTypeConfiguration
    {
        
        public EpisodeMap()
        {
            ToTable("Modules_Episodes");
            HasKey(m => m.Id);
            Property(m => m.LanguageCode).IsRequired().HasMaxLength(50);
            Property(m => m.SiteId).IsRequired();
            Property(m => m.EpisodeName).HasMaxLength(50);
            Property(m => m.Description).HasMaxLength(2000);
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface ITransactionCardService : IGenericService<TransactionCardInfo, long>, IDependency
    {
        int CardProcessing(TransactionCardInfo entity, int vipXu);

        IList<TransactionCardInfo> GetPaged(string keyword, string cardCode, int status, int isLock,
            DateTime fromDate, DateTime toDate, int pageIndex, int pageSize, out int totals);

        IList<TransactionCardInfo> ExportExcelAtm(DateTime fromDate, DateTime toDate);

        int CardClosed(DateTime toDate);
    }

    public class TransactionCardService : GenericService<TransactionCardInfo, long>, ITransactionCardService
    {
        public TransactionCardService(IRepository<TransactionCardInfo, long> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public int CardProcessing(TransactionCardInfo entity, int vipXu)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@CustomerCode", entity.CustomerCode),
                AddInputParameter("@TransactionCode", entity.TransactionCode),
                AddInputParameter("@CreateDate", entity.CreateDate),
                AddInputParameter("@CardCode", entity.CardCode),
                AddInputParameter("@Amount", entity.Amount),
                AddInputParameter("@SeriNumber", entity.SeriNumber),
                AddInputParameter("@PinCode", entity.PinCode),
                AddInputParameter("@Description", entity.Description),
                AddInputParameter("@Status", entity.Status),
                AddInputParameter("@VipXu", vipXu)
            };

            return ExecuteNonQuery("sp_TransactionCard_CardProcessing", list.ToArray());
        }

        public IList<TransactionCardInfo> GetPaged(string keyword, string cardCode, int status, 
            int isLock, DateTime fromDate, DateTime toDate, int pageIndex, int pageSize, out int totals)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@SearchText", keyword),
                AddInputParameter("@CardCode", cardCode),
                AddInputParameter("@Status", status),
                AddInputParameter("@IsLock", isLock),
                AddInputParameter("@FromDate", fromDate),
                AddInputParameter("@ToDate", toDate),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<TransactionCardInfo>("sp_TransactionCard_Search_Paged", "@TotalRecord", out totals, list.ToArray());
        }

        public IList<TransactionCardInfo> ExportExcelAtm(DateTime fromDate, DateTime toDate)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@FromDate", fromDate),
                AddInputParameter("@ToDate", toDate)
            };

            return ExecuteReader<TransactionCardInfo>("sp_TransactionBank_ReportCard", list.ToArray());
        }

        public int CardClosed(DateTime toDate)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@ToDate", toDate)
            };

            return ExecuteNonQuery("sp_TransactionCard_Closed", list.ToArray());
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Xml.Serialization;
using CMSSolutions.Extensions;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Extensions
{
    public class Utilities
    {
        public static string GetStatusDownload(DownloadCustomerInfo download)
        {
            var displayDay = "Sẵn sàng";
            if (download != null && download.EndDate.HasValue && download.EndDate.Value.Date >= DateTime.Now.Date)
            {
                int date = download.EndDate.Value.Day;
                int date2 = DateTime.Now.Date.Day;
                if ((date - date2) >= 3)
                {
                    displayDay = "3 ngày";
                }

                if ((date - date2) == 2)
                {
                    displayDay = "2 ngày";
                }

                if ((date - date2) == 1)
                {
                    displayDay = "1 ngày";
                }
            }

            return displayDay;
        }

        public static bool IsNumeric(string val, NumberStyles numberStyle)
        {
            Double result;
            return Double.TryParse(val, numberStyle, CultureInfo.CurrentCulture, out result);
        }

        public static string SerializeXml<T>(T dataToSerialize)
        {
            var stringwriter = new StringWriter();
            var serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(stringwriter, dataToSerialize);
            return stringwriter.ToString();
        }

        public static T DeserializeXml<T>(string xmlText)
        {
            var stringReader = new StringReader(xmlText);
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stringReader);
        }

        public static void WriteEventLog(string messages)
        {
            try
            {
                var eventLogName = "ErrorVipHD";
                if (!EventLog.SourceExists(eventLogName))
                {
                    EventLog.CreateEventSource(eventLogName, "Error VIPHD.VN");
                }

                var log = new EventLog { Source = eventLogName };
                log.WriteEntry(messages, EventLogEntryType.Error);   
            }
            catch (Exception)
            {
            } 
        }

        public static string RemoveInjection(string query)
        {
            query = query.Replace("'", "''");
            return query;
        }

        public static string GenerateUniqueNumber()
        {
            var bytes = new byte[4];
            var rng = RandomNumberGenerator.Create();
            rng.GetBytes(bytes);
            uint random = BitConverter.ToUInt32(bytes, 0) % 100000000;
            return String.Format("{0:D8}", random);
        }

        public static bool ValidateUserName(string userName)
        {
            if (IsEmailValid(userName))
            {
                return true;
            }  

            var userNameAllowedRegEx = new Regex(@"^[a-zA-Z]{1}[a-zA-Z0-9\._\-]{0,23}[^.-]$", RegexOptions.Compiled);
            var userNameIllegalEndingRegEx = new Regex(@"(\.|\-|\._|\-_)$", RegexOptions.Compiled);
            if (string.IsNullOrEmpty(userName)
                || !userNameAllowedRegEx.IsMatch(userName)
                || userNameIllegalEndingRegEx.IsMatch(userName))
            {
                return false;
            }

            return true;
        }

        public static string GetBankMessages(int errorCode)
        {
            var list = EnumExtensions.ToSelectList<BankErrorMessages>();
            var message = "Bank: Lỗi không xác định từ hệ thống ngân hàng đối tác.";
            foreach (var item in list)
            {
                var value = Convert.ToInt32(item.Value);
                if (value == errorCode)
                {
                    message = EnumExtensions.GetDisplayName((BankErrorMessages)value);
                    break;
                }
            }

            return message;
        }

        public static string GetMessages(int errorCode)
        {
            var list = EnumExtensions.ToSelectList<ErrorMessages>();
            var message = "Card: Lỗi không xác định từ hệ thống đối tác.";
            foreach (var item in list)
            {
                var value = Convert.ToInt32(item.Value);
                if (value == errorCode)
                {
                    message = EnumExtensions.GetDisplayName((ErrorMessages)value);
                    break;
                }
            }

            return message;
        }

        public static int[] ParseListInt(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return new int[0];
            }

            return value.Split(',').Select(Int32.Parse).ToArray();
        }

        public static string ParseString(int[] list)
        {
            if (list != null && list.Length > 0)
            {
                return string.Join(", ", list);
            }

            return string.Empty;
        }

        public static bool IsDirectory(string path)
        {
            FileAttributes attr = File.GetAttributes(path);
            if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
            {
                return true;
            }

            return false;
        }

        public static bool IsPathExists(string path)
        {
            if (Directory.Exists(path))
            {
                return true;
            }

            if (File.Exists(path))
            {
                return true;
            }

            return false;
        }

        public static string DateString(DateTime? dateTime)
        {
            if (dateTime == null)
            {
                return "01/01/1900";
            }

            return dateTime.Value.ToString(Constants.DateTimeFomat);
        }

        public static DateTime DateNull()
        {
            return new DateTime(1900, 01, 01);
        }

        public static bool IsNotNull(object value)
        {
            if (value == null)
            {
                return false;
            }

            if (value.Equals(Constants.IsNull) || value.Equals(""))
            {
                return false;
            }

            if (value.Equals(Constants.IsUndefined))
            {
                return false;
            }

            return true;
        }

        private static string DomainMapper(Match match)
        {
            var idn = new IdnMapping();
            string domainName = match.Groups[2].Value;
            try
            {
                domainName = idn.GetAscii(domainName);
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }

            return match.Groups[1].Value + domainName;
        }

        public static bool IsEmailValid(string emailaddress)
        {
            if (String.IsNullOrEmpty(emailaddress))
            {
                return false;
            }

            emailaddress = Regex.Replace(emailaddress, @"(@)(.+)$", DomainMapper);
            return Regex.IsMatch(emailaddress,
                   @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                   @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
                   RegexOptions.IgnoreCase);
        }

        public static string GetAlias(string values)
        {
            if (string.IsNullOrEmpty(values))
            {
                return string.Empty;
            }

            var regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
            string temp = values.Normalize(NormalizationForm.FormD);
            var  converttext = regex.Replace(temp, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');

            converttext = Regex.Replace(converttext, "[^a-zA-Z0-9_.]+", " ", RegexOptions.Compiled);

            var list = new char[] { ' ','/',',','&','\"','?','|',':','"', '`', '\\', ';', '~', '!', '@', '#', '$', '%', '^', '*', '(', ')', '\'', '_', '=', '+', '{', '}', '[', ']', '.', '>', '<' };
            converttext = list.Aggregate(converttext, (current, schar) => current.Replace(schar, '-'));

            converttext = converttext.Replace("--", "-").Trim('.').TrimEnd('-').TrimStart('-');

            return converttext.ToLower();
        }

        public static string GetCharUnsigned(string values)
        {
            if (string.IsNullOrEmpty(values))
            {
                return string.Empty;
            }

            var regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
            string temp = values.Normalize(NormalizationForm.FormD);
            var converttext = regex.Replace(temp, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');

            converttext = Regex.Replace(converttext, "[^a-zA-Z0-9_.]+", " ", RegexOptions.Compiled);

            var list = new char[] { ' ', '/', ',', '&', '\"', '?', '|', ':', '"', '`', '\\', ';', '~', '!', '@', '#', '$', '%', '^', '*', '(', ')', '\'', '_', '=', '+', '{', '}', '[', ']', '.', '>', '<' };
            converttext = list.Aggregate(converttext, (current, schar) => current.Replace(schar, ' '));

            converttext = converttext.Replace("--", " ").Trim('.').TrimEnd(' ').TrimStart(' ');

            return converttext.ToLower();
        }

        public static T ConvertJsonToObject<T>(string input)
        {
            var json = new JavaScriptSerializer();
            return json.Deserialize<T>(input.Trim());
        }

        public static string ConvertObjectToJson<T>(T input)
        {
            var json = new JavaScriptSerializer();
            return json.Serialize(input);
        }

        public static List<SelectListItem> GetListDay()
        {
            var list = new List<SelectListItem>();
            for (int i = 1; i <= 31; i++)
            {
                var text = (i <= 9 ? "0" + i : i.ToString());
                list.Add(new SelectListItem
                {
                    Value = text,
                    Text = text,
                });
            }

            return list;
        }

        public static List<SelectListItem> GetListMonth()
        {
            var list = new List<SelectListItem>();
            for (int i = 1; i <= 12; i++)
            {
                var text = (i <= 9 ? "0" + i : i.ToString());
                list.Add(new SelectListItem
                {
                    Value = text,
                    Text = "Tháng " + text,
                });
            }

            return list;
        }

        public static List<SelectListItem> GetListYear()
        {
            var year = DateTime.Now.Year;
            var list = new List<SelectListItem>();
            for (int i = 1900; i <= year; i++)
            {
                var text = i.ToString();
                list.Add(new SelectListItem
                {
                    Value = text,
                    Text = text,
                });
            }

            return list.OrderByDescending(x => x.Value).ToList();
        }
    }
}<file_sep>﻿using System.IO;
using System.Web.Mvc;
using CMSSolutions.Websites.Controllers;

namespace CMSSolutions.Websites.Extensions
{
    public class ViewRenderer
    {
        public ControllerContext Context { get; set; }
        public string RenderView(string viewPath, object model)
        {
            return RenderViewToStringInternal(viewPath, model, false);
        }

        public string RenderPartialView(string viewPath, object model)
        {
            return RenderViewToStringInternal(viewPath, model, true);
        }

        protected string RenderViewToStringInternal(string viewPath, object model, bool partial = false)
        {
            // first find the ViewEngine for this view
            ViewEngineResult viewEngineResult = null;
            if (partial)
                viewEngineResult = ViewEngines.Engines.FindPartialView(Context, viewPath);
            else
                viewEngineResult = ViewEngines.Engines.FindView(Context, viewPath, null);

            if (viewEngineResult == null)
                throw new FileNotFoundException("ViewCouldNotBeFound");

            // get the view and attach the model to view data
            var view = viewEngineResult.View;
            Context.Controller.ViewData.Model = model;

            string result = null;

            using (var sw = new StringWriter())
            {
                var ctx = new ViewContext(Context, view,
                                            Context.Controller.ViewData,
                                            Context.Controller.TempData,
                                            sw);
                view.Render(ctx, sw);
                result = sw.ToString();
            }

            return result;
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web.Mvc;
using CMSSolutions.Extensions;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Services;
using GemBox.Spreadsheet;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminReportBankController : BaseAdminController
    {
        public AdminReportBankController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
            TableName = "tblReportAtm";
        }

        [Url("admin/report/bank")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Báo cáo ATM"), Url = "#" });

            var result = new ControlGridFormResult<TransactionBankInfo>
            {
                Title = T("Báo cáo ATM"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetReportBank,
                DefaultPageSize = WorkContext.DefaultPageSize,
                EnablePaginate = true,
                UpdateActionName = "Update",
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml,
                ClientId = TableName,
                ActionsColumnWidth = 150
            };

            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.BankCode, "$('#" + Extensions.Constants.BankCode + "').val();", true);
            result.AddCustomVar(Extensions.Constants.TypeId, "$('#" + Extensions.Constants.TypeId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.Locked, "$('#" + Extensions.Constants.Locked + "').val();", true);
            result.AddCustomVar(Extensions.Constants.FromDate, "$('#" + Extensions.Constants.FromDate + "').val();", true);
            result.AddCustomVar(Extensions.Constants.ToDate, "$('#" + Extensions.Constants.ToDate + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true);

            result.AddColumn(x => x.TransactionCode, T("Mã GD")).HasWidth(60).AlignCenter();
            result.AddColumn(x => x.CustomerCode, T("Mã KH"));
            result.AddColumn(x => x.FullName, T("Tên KH"));
            result.AddColumn(x => x.Amount, T("Số tiền"));
            result.AddColumn(x => x.TextStartDate, T("Ngày giao dịch"));
            result.AddColumn(x => EnumExtensions.GetDisplayName((PaymentStatus)x.Status), T("Trạng thái"));
            result.AddColumn(x => x.IsLock)
                .HasHeaderText(T("Đang khóa"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage();

            result.AddAction().HasText(T("Chốt đối soát"))
                .HasUrl(Url.Action("Index", "AdminClosedBank"))
                .HasButtonStyle(ButtonStyle.Danger)
                .HasCssClass(Constants.RowLeft);

            result.AddAction().HasText(T("Xuất dữ liệu gửi giao dịch"))
                .HasUrl(Url.Action("ExportExcelSend"))
                .HasButtonStyle(ButtonStyle.Info)
                .HasCssClass(Constants.RowLeft);

            result.AddAction().HasText(T("Xuất dữ liệu nhận giao dịch"))
               .HasUrl(Url.Action("ExportExcelRereceive"))
               .HasButtonStyle(ButtonStyle.Info)
               .HasCssClass(Constants.RowLeft)
               .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildBanks)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildTypes)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildLocked)).HasParentClass(Constants.ContainerCssClassCol3).HasRow(true);
            result.AddAction(new ControlFormHtmlAction(() => BuildFromDate())).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildToDate())).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3);

            return result;
        }

        public override string BuildStatus()
        {
            var list = EnumExtensions.GetListItems<PaymentStatus>();
            var sb = new StringBuilder();
            sb.AppendFormat(T("Trạng thái") + " <select id=\"" + Extensions.Constants.StatusId + "\" name=\"" + Extensions.Constants.StatusId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var status in list)
            {
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        private string BuildBanks()
        {
            var list = WorkContext.Resolve<IBankCardService>().GetRecords();
            var sb = new StringBuilder();
            sb.AppendFormat(T("Ngân hàng") + " <select id=\"" + Extensions.Constants.BankCode + "\" name=\"" + Extensions.Constants.BankCode + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var status in list)
            {
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.BankName, status.BankCode);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        private string BuildTypes()
        {
            var list = EnumExtensions.GetListItems<TransferType>();
            var sb = new StringBuilder();
            sb.AppendFormat(T("Loại xử lý") + " <select id=\"" + Extensions.Constants.TypeId + "\" name=\"" + Extensions.Constants.TypeId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var status in list)
            {
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        private string BuildLocked()
        {
            var list = new List<SelectListItem>
            {
                new SelectListItem{Value = "0", Text = "Chưa chốt sổ đối soát"},
                new SelectListItem{Value = "1", Text = "Đã chốt sổ đối soát"}
            };
            var sb = new StringBuilder();
            sb.AppendFormat(T("Đối soát") + " <select id=\"" + Extensions.Constants.Locked + "\" name=\"" + Extensions.Constants.Locked + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            foreach (var status in list)
            {
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value);
            }

            sb.Append("</select>");
            return sb.ToString();
        }

        private ControlGridAjaxData<TransactionBankInfo> GetReportBank(ControlGridFormRequest options)
        {
            var searchText = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText]))
            {
                searchText = Request.Form[Extensions.Constants.SearchText];
            }

            var bankCode = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.BankCode]))
            {
                bankCode = Request.Form[Extensions.Constants.BankCode];
            }

            var type = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.TypeId]))
            {
                type = Convert.ToInt32(Request.Form[Extensions.Constants.TypeId]);
            }

            var status = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId]))
            {
                status = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]);
            }

            var locked = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.Locked]))
            {
                locked = Convert.ToInt32(Request.Form[Extensions.Constants.Locked]);
            }

            var fromDate = DateTime.Now.Date;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FromDate]))
            {
                fromDate = DateTime.ParseExact(Request.Form[Extensions.Constants.FromDate], "dd/MM/yyyy", CultureInfo.InvariantCulture);
            }

            var toDate = DateTime.Now.Date;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ToDate]))
            {
                toDate = DateTime.ParseExact(Request.Form[Extensions.Constants.ToDate], "dd/MM/yyyy", CultureInfo.InvariantCulture);
            }

            int totals;
            var items = WorkContext.Resolve<ITransactionBankService>().GetPaged(searchText, bankCode, type, status, locked, fromDate, toDate, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<TransactionBankInfo>(items, totals);

            return result;
        }

        [Url("admin/report/sms/export-excel-send")]
        public ActionResult ExportExcelSend()
        {
            var ef = new ExcelFile();
            string fileName = Server.MapPath("/Media/Default/ExcelTemplate/DuLieuATM.xls");
            ef.LoadXls(fileName, XlsOptions.PreserveAll);
            byte[] fileContents;
            ExcelWorksheet ws = ef.Worksheets[0];
            var data = WorkContext.Resolve<ITransactionBankService>().ExportExcelAtm(Utilities.DateNull(), Utilities.DateNull(), (int)TransferType.Send);
            if (data != null && data.Count > 0)
            {
                int index = 1;
                foreach (var item in data)
                {
                    ws.Cells[index, 0].Value = index;
                    ws.Cells[index, 1].Value = item.CustomerCode;
                    ws.Cells[index, 2].Value = item.FullName;
                    ws.Cells[index, 3].Value = item.Amount;
                    ws.Cells[index, 4].Value = item.CreateDate.ToString(Extensions.Constants.DateTimeFomatFull);
                    ws.Cells[index, 5].Value = EnumExtensions.GetDisplayName((RequestStatus)item.Status);
                    index++;
                    ws.Rows[index].InsertCopy(1, ws.Rows[1]);
                }

                ws.Rows[index].Delete();
            }

            using (var stream = new MemoryStream())
            {
                ef.SaveXls(stream);

                fileContents = stream.ToArray();
            }

            return File(fileContents, "application/vnd.ms-excel");
        }

        [Url("admin/report/sms/export-excel-rereceive")]
        public ActionResult ExportExcelRereceive()
        {
            var ef = new ExcelFile();
            string fileName = Server.MapPath("/Media/Default/ExcelTemplate/DuLieuATM.xls");
            ef.LoadXls(fileName, XlsOptions.PreserveAll);
            ExcelWorksheet ws = ef.Worksheets[0];
            var data = WorkContext.Resolve<ITransactionBankService>().ExportExcelAtm(Utilities.DateNull(), Utilities.DateNull(), (int)TransferType.Rereceive);
            if (data != null && data.Count > 0)
            {
                int index = 1;
                foreach (var item in data)
                {
                    ws.Cells[index, 0].Value = index;
                    ws.Cells[index, 1].Value = item.CustomerCode;
                    ws.Cells[index, 2].Value = item.FullName;
                    ws.Cells[index, 3].Value = item.Amount;
                    ws.Cells[index, 4].Value = item.CreateDate.ToString(Extensions.Constants.DateTimeFomatFull);
                    ws.Cells[index, 5].Value = EnumExtensions.GetDisplayName((RequestStatus)item.Status);
                    index++;
                    ws.Rows[index].InsertCopy(1, ws.Rows[1]);
                }

                ws.Rows[index].Delete();
            }

            byte[] fileContents;
            using (var stream = new MemoryStream())
            {
                ef.SaveXls(stream);

                fileContents = stream.ToArray();
            }

            return File(fileContents, "application/vnd.ms-excel");
        }
    }
}
<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class BankCardModel
    {
        [ControlHidden]
        public int Id { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Mã ngân hàng", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public string BankCode { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Tên ngân hàng", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public string BankName { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)]
        public int Status { get; set; }
        
        public static implicit operator BankCardModel(BankCardInfo entity)
        {
            return new BankCardModel
            {
                Id = entity.Id,
                BankCode = entity.BankCode,
                BankName = entity.BankName,
                Status = entity.Status
            };
        }
    }
}
<file_sep>﻿using System.ComponentModel.DataAnnotations;

namespace CMSSolutions.Websites.Extensions
{
    public enum AlertErrorVideo
    {
        [Display(Name = "..Chọn thông báo lỗi..")]
        None = 0,

        [Display(Name = "Lỗi tiêu đề")]
        Aler1 = 1,

        [Display(Name = "Lỗi hình ảnh")]
        Aler2 = 2,

        [Display(Name = "Lỗi âm thanh")]
        Aler3 = 3,

        [Display(Name = "Không xem được")]
        Aler4 = 4,

        [Display(Name = "Lỗi đứng hình, tiếng vẫn phát")]
        Aler5 = 5,

        [Display(Name = "Lỗi khác")]
        Aler6 = 6,
    }

    public enum LinkType
    {
        Streaming = 1,

        Picasa = 2,

        Youtube = 3
    }

    public enum SliderPages
    {
        [Display(Name = "Trang chủ")]
        Home = 1,

        [Display(Name = "Chuyên mục phim lẻ")]
        CatetegoryPhimLe = 2,

        [Display(Name = "Phim mới nhất")]
        FilmHot = 3,

        [Display(Name = "Chiếu rạp")]
        FilmTheater = 4,

        [Display(Name = "Show")]
        Show = 5,

        [Display(Name = "Clip")]
        Clip = 6,

        [Display(Name = "Trailer")]
        Trailer = 7,

        [Display(Name = "JJ Channel")]
        JJChannel = 8,

        [Display(Name = "Chuyên mục phim bộ")]
        CatetegoryPhimBo = 9,
    }

    public enum SearchSortBy
    {
        [Display(Name = "Tăng dần")]
        ASC = 1,

        [Display(Name = "Giảm dần")]
        DESC = 2,
    }

    public enum SearchOrderBy
    {
        [Display(Name = "Xếp theo")]
        Id = 0,

        [Display(Name = "Mới Up")]
        CreateDate = 1,

        [Display(Name = "Năm sản xuất")]
        ReleaseYear = 2,

        [Display(Name = "Tên phim")]
        FilmName = 3,

        [Display(Name = "Lượt xem")]
        ViewCount = 4,

        [Display(Name = "Lượt like")]
        CommentCount = 5
    }

    public enum FixCategories
    {
        [Display(Name = "Nạp VIP")]
        NapVIP = 63,

        [Display(Name = "Phim hót")]
        FilmHot = 101,

        [Display(Name = "Phim lẻ")]
        FilmLe = 2,

        [Display(Name = "Phim bộ")]
        FilmBo = 3,

        [Display(Name = "Tất cả")]
        AllNews = 59,

        [Display(Name = "Sự kiện")]
        Events = 60,

        [Display(Name = "Tin tức")]
        News = 61,
        
        [Display(Name = "Tuyển  dụng")]
        Recruitment = 62,

        [Display(Name = "Phim chiếu rạp")]
        FilmTheater = 102,

        [Display(Name = "Hỗ trợ")]
        Support = 64
    }

    public enum PromotionStatus
    {
        [Display(Name = "Đang thực hiện")]
        Running = 1,

        [Display(Name = "Đã kết thúc")]
        Finish = 2
    }

    public enum ExchangeMoney
    {
        [Display(Name = "10.000")]
        VipXu10 = 100,

        [Display(Name = "20.000")]
        VipXu20 = 200,

        [Display(Name = "30.000")]
        VipXu30 = 300,

        [Display(Name = "50.000")]
        VipXu50 = 500,

        [Display(Name = "100.000")]
        VipXu100 = 1000,

        [Display(Name = "200.000")]
        VipXu200 = 2000,

        [Display(Name = "300.000")]
        VipXu300 = 3000,

        [Display(Name = "500.000")]
        VipXu500 = 5000
    }

    public enum  ExchangeDay
    {
        [Display(Name = "15 Ngày")]
        Package15 = 15,

        [Display(Name = "50 Ngày")]
        Package50 = 50,

        [Display(Name = "100 Ngày")]
        Package100 = 100,

        [Display(Name = "300 Ngày")]
        Package300 = 300
    }

    public enum CardStatus
    {
        [Display(Name = "Nạp thẻ thất bại")]
        Error = 1,

        [Display(Name = "Nạp thẻ thành công")]
        Success = 2
    }

    public enum PaymentStatus
    {
        [Display(Name = "Đang thực hiện")]
        Open = 1,

        [Display(Name = "Đã hoàn thành")]
        Close = 2
    }

    public enum TransferType
    {
        [Display(Name = "Gửi đi")]
        Send = 1,

        [Display(Name = "Nhận về")]
        Rereceive = 2
    } 

    public enum VideoTypes
    {
        [Display(Name = "Phim")]
        IsFilm = 1,

        [Display(Name = "Show")]
        IsShow = 2,

        [Display(Name = "Clip")]
        IsClip = 3,

        [Display(Name = "Trailer")]
        IsTrailer = 4
    }

    public enum Site
    {
        [Display(Name = "viphd.vn")]
        Home = 1,

        [Display(Name = "jj.viphd.vn")]
        JJHome = 2
    }

    public enum HomeDisplayFilmType
    {
        [Display(Name = "Sự kiện: Phim Đang HOT")]
        FilmHot = 1,

        [Display(Name = "Phim lẻ mới up")]
        FilmRetail = 2,

        [Display(Name = "Phim bộ mới up")]
        FilmLengthEpisodes = 3,

        [Display(Name = "JJ Channel giới thiệu")]
        FilmJJChannelIntroduce = 4,

        [Display(Name = "Phim chiếu rạp")]
        FilmTheater = 5,

        [Display(Name = "TV Show")]
        TVShow = 6,

        [Display(Name = "Clip")]
        Clip = 7,

        [Display(Name = "Bình luận Facebook")]
        FacebookComments = 8,

        [Display(Name = "Phim lẻ xem nhiều nhất")]
        StatisticalFilmRetail = 9,

        [Display(Name = "Phim bộ xem nhiều nhất")]
        StatisticalLengthEpisodes = 10,

        [Display(Name = "Show xem nhiều nhất")]
        StatisticalShows = 11,

        [Display(Name = "Clip xem nhiều nhất")]
        StatisticalClips = 12,

        [Display(Name = "Phim sắp chiếu")]
        StatisticalTrailer = 13,

        [Display(Name = "Phim liên quan")]
        StatisticalNextFilm = 14
    }

    public enum LogStatus
    {
        [Display(Name = "Thông báo lỗi")]
        Error = 1,

        [Display(Name = "Thông báo thành công")]
        Success = 2,

        [Display(Name = "Cập nhập dữ liệu")]
        Information = 3
    }

    public enum LogType
    {
        [Display(Name = "Tin nhắn tổng đài")]
        SMS = 1,

        [Display(Name = "Thẻ ngân hàng")]
        BankCard = 2,

        [Display(Name = "Thẻ cào")]
        ScratchCard = 3,

        [Display(Name = "Khác")]
        Other = 4,
    }

    public enum CustomerLogType
    {
        [Display(Name = "Hệ thống log")]
        SystemLogs = 1,

        [Display(Name = "Nạp tiền")]
        NapVipLogs = 2,

        [Display(Name = "Đổi VipXu")]
        VipXuLogs = 3,

        [Display(Name = "Đào Xu")]
        DaoXuLogs = 4
    }

    public enum AmountType
    {
        [Display(Name = "Không tính tiền khách hàng")]
        NotAmount = 0,

        [Display(Name = "Tính tiền khách hàng")]
        Amount = 1,

        [Display(Name = "Trả lại tiền khách hàng")]
        ResultAmount = 2
    }

    public enum SMSType
    {
        [Display(Name = "Nhận dữ liệu từ nhà mạng")]
        MO = 1,

        [Display(Name = "Gửi thông báo cho khách hàng")]
        MT = 2
    }

    public enum RequestStatus
    {
        [Display(Name = "Thực hiện giao dịch thành công")]
        Messages200 = 200,

        [Display(Name = "Thực hiện giao dịch thất bại, yêu cầu gửi lại")]
        Messages01 = 1,

        [Display(Name = "Trùng MTID")]
        Messages02 = 2,

        [Display(Name = "IP của đối tác không hợp lệ hoặc chưa được cấu hình trong hệ thống")]
        Messages03 = 3,

        [Display(Name = "Không tìm thấy thông tin Command Code trên hệ thống")]
        Messages04 = 4,

        [Display(Name = "Không tìm thấy service number trên hệ thống")]
        Messages05 = 5,

        [Display(Name = "Hệ thống tạm thời gặp lỗi")]
        Messages06 = 6,

        [Display(Name = "Sai check sum")]
        Messages17 = 17,

        [Display(Name = "Sai định dạng MTID")]
        Messages18 = 18,

        [Display(Name = "Method không được hỗ trợ")]
        Messages19 = 19,

        [Display(Name = "Không tim thấy MO của MT này(trong trường hợp xử dụng method= mtReceiver)")]
        Messages20 = 20
    }

    public enum ShortCode
    {
        [Display(Name = "8076")]
        DauSo8076 = 8076,

        [Display(Name = "8176")]
        DauSo8176 = 8176,

        [Display(Name = "8276")]
        DauSo8276 = 8276,

        [Display(Name = "8376")]
        DauSo8376 = 8376,

        [Display(Name = "8476")]
        DauSo8476 = 8476,

        [Display(Name = "8576")]
        DauSo8576 = 8576,

        [Display(Name = "8676")]
        DauSo8676 = 8676,

        [Display(Name = "8776")]
        DauSo8776 = 8776
    }

    public enum Gender
    {
        [Display(Name = "Không xác định")]
        None = 0,

        [Display(Name = "Nam")]
        Male = 1,

        [Display(Name = "Nữ")]
        Female = 2,
    }

    public enum LoginTypes
    {
        [Display(Name = "Mặc định")]
        None = 0,

        [Display(Name = "Facebook")]
        Facebook = 1,

        [Display(Name = "Google")]
        Google = 2, 
    }

    public enum HomeWidgets
    {
        [Display(Name = "Banner ở bên trái slide chính")]
        BannerPageLeft = 1,

        [Display(Name = "Banner ở dưới slide chính")]
        BannerPageCenter = 2,

        [Display(Name = "Banner ở bên phải slide chính")]
        BannerPageRight = 3,

        [Display(Name = "Banner vị trí thứ nhất nội dung bên trái")]
        BannerContentLeftFirst = 4,

        [Display(Name = "Banner vị trí thứ hai nội dung bên trái")]
        BannerContentLeftSecond = 5,

        [Display(Name = "Banner vị trí thứ ba nội dung bên trái")]
        BannerContentLeftThird = 6,

        [Display(Name = "Banner vị trí thứ tư nội dung bên trái")]
        BannerContentLeftFourth = 7,

        [Display(Name = "Banner vị trí thứ năm nội dung bên trái")]
        BannerContentLeftFifth = 8,

        [Display(Name = "Banner vị trí thứ sáu nội dung bên trái")]
        BannerContentLeftSixth = 9,

        [Display(Name = "Banner vị trí thứ bảy nội dung bên trái")]
        BannerContentLeftSeventh = 10,

        [Display(Name = "Banner vị trí thứ nhất bên phải")]
        BannerRightFirst = 11,

        [Display(Name = "Banner vị trí thứ hai bên phải")]
        BannerRightSecond = 12,

        [Display(Name = "Banner vị trí thứ ba nội dung bên trái")]
        BannerRightThird = 13,

        [Display(Name = "Banner vị trí thứ tư nội dung bên trái")]
        BannerRightFourth = 14,

        [Display(Name = "Slider chính")]
        HomeSliderBanner = 15,

        [Display(Name = "Footer thông tin bản quyền")]
        HomeFooterLogoInformation = 16,

        [Display(Name = "Facebook Fanpage")]
        HomeFacebookFanpage = 17,

        [Display(Name = "Facebook Activity")]
        HomeFacebookActivity = 18,

        [Display(Name = "Facebook Follow")]
        HomeFacebookFollow = 19,

        [Display(Name = "Google Badge")]
        HomeGoogleBadge = 20,

        [Display(Name = "Banner vị trí thứ năm bên phải")]
        BannerRightFifth = 21,
        
        [Display(Name = "Banner vị trí thứ sáu bên phải")]
        BannerRightSixth = 22,

        [Display(Name = "Banner khu vực VIP")]
        BannerPageCenterVip = 23,

        [Display(Name = "Banner khu vực VIP trái")]
        BannerPageLeftVip = 24,

        [Display(Name = "Banner khu vực VIP phải")]
        BannerPageRightVip = 25,

        [Display(Name = "Chia sẻ mạng xã hội")]
        DisplaySocialNetwork = 26
    }

    public enum  BankErrorMessages
    {
        [Display(Name = "Thành công.")]
        Success = 0,

        [Display(Name = "Thất bại.")]
        Fail = 1,

        [Display(Name = "Chưa confirm được.")]
        NotConfirmedYet = 2,

        [Display(Name = "Đã confirm trước đó.")]
        ConfirmedBefore = 3,

        [Display(Name = "Giao dịch Pending.")]
        TransactionPending = 4,

        [Display(Name = "Sai MAC.")]
        MacFail = 5,

        [Display(Name = "Không xác định mã lỗi.")]
        Exception = 6,

        [Display(Name = "Giao dịch không tồn tại.")]
        NotExistTransaction = 7,

        [Display(Name = "Thông tin không đầy đủ.")]
        FieldsNotFull = 8,

        [Display(Name = "Đại lý không tồn tại.")]
        NotExistMerchant = 9,

        [Display(Name = "Sai định dạng.")]
        FalseFormat = 10,

        [Display(Name = "Sai thông tin.")]
        WrongInformation = 11,

        [Display(Name = "Ngân hàng tạm khóa hoặc không tồn tại.")]
        BankNotActive = 12,

        [Display(Name = "Có lỗi.")]
        Error = 13,

        [Display(Name = "Code không hợp lệ.")]
        NotExactlyCode = 14,

        [Display(Name = "Ngân hàng từ chối giao dịch.")]
        BankDeclined = 801,

        [Display(Name = "Mã đơn vị không tồn tại.")]
        MerchantNotExist = 803,

        [Display(Name = "Mã đơn vị không tồn tại.")]
        InvalidAccessCode = 804,

        [Display(Name = "Số tiền không hợp lệ.")]
        InvalidAmount = 805,

        [Display(Name = "Mã tiền tệ không tồn tại.")]
        InvalidCurrencyCode = 806,

        [Display(Name = "Lỗi không xác định.")]
        UnspecifiedFailure = 807,

        [Display(Name = "Số thẻ không đúng.")]
        InvalidCardNumber = 808,

        [Display(Name = "Tên chủ thẻ không đúng.")]
        InvalidCardName = 809,

        [Display(Name = "Thẻ hết hạn/thẻ bị khóa.")]
        ExpiredCard = 810,

        [Display(Name = "Thẻ chưa đăng ký dịch vụ Internet banking.")]
        CardNotRegisterService = 811,

        [Display(Name = "Ngày  phát  hành/hết  hạn  không đúng.")]
        InvalidCardDate = 812,

        [Display(Name = "Vượt quá hạn mức thanh toán.")]
        ExistAmount = 813,

        [Display(Name = "Số tiền không đủ để thanh toán.")]
        InsufficientFund = 821,

        [Display(Name = "Người sử dụng cancel.")]
        UserCancel = 899,

        [Display(Name = "Merchant_code không hợp lệ.")]
        InvalidMerchantCode = 901,

        [Display(Name = "Chuỗi mã hóa không hợp lệ.")]
        InvalidEncryption = 902,

        [Display(Name = "Merchant_tran_id không hợp lệ.")]
        InvalidMerchantTranId = 903,

        [Display(Name = "Không tìm thấy giao dịch trong hệ thống.")]
        NotFoundTransaction = 904,

        [Display(Name = "Đã xác nhận trước đó.")]
        AlreadyConfirmed = 906,

        [Display(Name = "Lỗi timeout xảy ra do không nhận thông điệp trả về.")]
        ErrorTimeout = 908,

        [Display(Name = "Số tiền không hợp lệ.")]
        NotInvalidAmount = 911,

        [Display(Name = "Phí không hợp lệ.")]
        InvalidFee = 912,

        [Display(Name = "Tax không hợp lệ.")]
        InvalidTax = 913
    }

    public enum ErrorMessages
    {
        [Display(Name = "Giao dịch thành công")]
        Success = 1,

        [Display(Name = "Thẻ đã sử dụng")]
        CardIsUsed = -1,

        [Display(Name = "Thẻ đã khóa")]
        CardIsLocked = -2,

        [Display(Name = "Thẻ đã hết hạn sử dụng")]
        CardIsExpired = -3,

        [Display(Name = "Mã thẻ chưa được kích hoạt")]
        CardIsNotActivate = -4,

        [Display(Name = "Mã thẻ sai định dạng")]
        CardFormatIsIncorrect = -10,

        [Display(Name = "Thẻ không tồn tại")]
        CardIsNotExist = -12,

        [Display(Name = "Lỗi thẻ VMS không đúng định dạng.")]
        VMSCardWrongFomat = -99,

        [Display(Name = "Partner nhập sai mã thẻ quá 5 lần.")]
        WrongCardInputExceed = 5,

        [Display(Name = "Sai thông tin partner.")]
        PartnerInformationError = 6,

        [Display(Name = "Chưa nhận được kết quả trả về từ nhà cung cấp mã thẻ.")]
        TransactionPending = 99,

        [Display(Name = "Dữ liệu carddata không đúng.")]
        BadCardData = -24,

        [Display(Name = "Nhà cung cấp không tồn tại.")]
        NoProviderFound = -11,

        [Display(Name = "Sai IP.")]
        InvalidIPRequest = 8,

        [Display(Name = "Sai Session.")]
        InvalidSessionID = 3,

        [Display(Name = "Session hết hạn.")]
        SessionTimeOut = 7,

        [Display(Name = "Thẻ không sử dụng được.")]
        CardIsIncorrect = 4,

        [Display(Name = "Hệ thống tạm thời bận.")]
        SystemBusy = 13,

        [Display(Name = "Giao dịch thất bại.")]
        Fail = 0,

        [Display(Name = "Tạm thời khóa kênh nạp VMS do quá tải.")]
        VMSChargingChanelOverload  = 9,

        [Display(Name = "Hệ thống nhà cung cấp gặp lỗi.")]
        ProviderError = 10,

        [Display(Name = "Nhà cung cấp tạm thời khóa partner do lỗi hệ thống.")]
        PartnerLocked = 10,

        [Display(Name = "Trùng TransactionId.")]
        TransactionDuplicate = 12,

        [Display(Name = "Thẻ đã sử dụng hoặc không tồn tại.")]
        CardIsUsedOrCardDoNotExist = 50,

        [Display(Name = "Seri thẻ không đúng.")]
        CardSerialIsInvalid = 51,

        [Display(Name = "Mã thẻ và serial không khớp.")]
        CardSerialAndPinIsNotMatch = 52,

        [Display(Name = "Serial hoặc mã thẻ không đúng.")]
        CardSerialOrPinIsIncorrect = 53,

        [Display(Name = "Serial hoặc mã thẻ không đúng.")]
        CardIsWaitingForActivate = 54,

        [Display(Name = "Các tạm thời bị block 24h.")]
        CardIsBlockFor24Hours = 55
    }

    public enum Sex
    {
        [Display(Name = "Không xác định")]
        Other = 0,

        [Display(Name = "Nam")]
        Male = 1,

        [Display(Name = "Nữ")]
        Female = 2
    }

    public enum Status
    {
        [Display(Name = "Đang sử dụng")]
        Approved = 1,

        [Display(Name = "Xóa tạm thời")]
        Deleted = 2
    }

    public enum FilmGroup
    {
        [Display(Name = "Phim một tập")]
        FilmRetail = 1,

        [Display(Name = "Phim dài tập")]
        FilmLengthEpisodes = 2
    }

    public enum  SearchType
    {
        [Display(Name = "Phim")]
        Film = 1,

        [Display(Name = "Tin tức")]
        Articles = 2,

        [Display(Name = "Chuyên mục")]
        Category = 3
    }
}<file_sep>﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class TransactionSmsInfo : BaseEntity<long>
    {
        [DataMember]
        [DisplayName("PartnerId")]
        public string PartnerId { get; set; }

        [DataMember]
        [DisplayName("MoId")]
        public string MoId { get; set; }

        [DataMember]
        [DisplayName("MtId")]
        public string MtId { get; set; }

        [DataMember]
        [DisplayName("UserId")]
        public string UserId { get; set; }

        [DataMember]
        [DisplayName("ShortCode")]
        public string ShortCode { get; set; }

        [DataMember]
        [DisplayName("Keyword")]
        public string Keyword { get; set; }

        [DataMember]
        [DisplayName("Subkeyword")]
        public string Subkeyword { get; set; }

        [DataMember]
        [DisplayName("Content")]
        public string Content { get; set; }

        [DataMember]
        [DisplayName("TransDate")]
        public string TransDate { get; set; }

        [DataMember]
        [DisplayName("CheckSum")]
        public string CheckSum { get; set; }

        [DataMember]
        [DisplayName("Amount")]
        public string Amount { get; set; }

        [DataMember]
        [DisplayName("CreateDate")]
        public DateTime CreateDate { get; set; }

        [DataMember]
        [DisplayName("Type")]
        public int Type { get; set; }

        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }

        [DataMember]
        [DisplayName("CustomerCode")]
        public string CustomerCode { get; set; }

        [NotMapped]
        [DisplayName("FullName")]
        public string FullName { get; set; }

        [DataMember]
        [DisplayName("TotalDay")]
        public int TotalDay { get; set; }

        [DataMember]
        [DisplayName("StartDate")]
        public DateTime? StartDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextStartDate
        {
            get
            {
                if (StartDate == null)
                {
                    return string.Empty;
                }
                return StartDate.Value.ToString(Extensions.Constants.DateTimeFomatFull);
            }
        }

        [DataMember]
        [DisplayName("EndDate")]
        public DateTime? EndDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextEndDate
        {
            get
            {
                if (EndDate == null)
                {
                    return string.Empty;
                }
                return EndDate.Value.ToString(Extensions.Constants.DateTimeFomatFull);
            }
        }

        [DataMember]
        [DisplayName("TransactionCode")]
        public string TransactionCode { get; set; }

        [DataMember]
        [DisplayName("IsLock")]
        public bool IsLock { get; set; }

        [DataMember]
        [DisplayName("IsClosed")]
        public bool IsClosed { get; set; }
    }

    public class TransactionSmsMap : EntityTypeConfiguration<TransactionSmsInfo>, IEntityTypeConfiguration
    {
        public TransactionSmsMap()
        {
            ToTable("Modules_TransactionSms");
            HasKey(m => m.Id);
            Property(m => m.MoId).HasMaxLength(50);
            Property(m => m.UserId).HasMaxLength(250);
            Property(m => m.ShortCode).HasMaxLength(50);
            Property(m => m.Keyword).HasMaxLength(250);
            Property(m => m.Subkeyword).HasMaxLength(250);
            Property(m => m.TransDate).HasMaxLength(100);
            Property(m => m.Amount).HasMaxLength(250);
            Property(m => m.CustomerCode).HasMaxLength(250);
            Property(m => m.TransactionCode).HasMaxLength(50);
        }  
    }
}<file_sep>﻿using System;
using System.Globalization;
using System.Web.Mvc;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminAdvertisementGroupController : BaseAdminController
    {
        public AdminAdvertisementGroupController(IWorkContextAccessor workContextAccessor)
            : base(workContextAccessor)
        {
            TableName = "tblAdvertisementGroup";
        }

        [Url("admin/advertisementgroup")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý nhóm quảng cáo"), Url = "#" });

            var result = new ControlGridFormResult<AdvertisementGroupInfo>
            {
                Title = T("Quản lý nhóm quảng cáo"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetAdvertisementGroup,
                DefaultPageSize = WorkContext.DefaultPageSize,
                EnablePaginate = true,
                UpdateActionName = "Update",
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml,
                ClientId = TableName,
                ActionsColumnWidth = 100
            };

            result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.CategoryId, "$('#" + Extensions.Constants.CategoryId + "').val();", true);

            result.AddColumn(x => x.Code, T("Mã Nhóm"));
            result.AddColumn(x => x.GroupName, T("Tên nhóm"));
            result.AddColumn(x => x.CategoryName, T("Chuyên mục"));
            result.AddColumn(x => x.FullPath, T("Đường dẫn Xml"));
            result.AddColumn(x => x.TextCreateDate, "Ngày bắt đầu");
            result.AddColumn(x => x.TextFinishTime, "Ngày hết hạn");
            result.AddColumn(x => x.IsActived)
                .HasHeaderText(T("Sử dụng"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage(false);

            result.AddAction().HasText(T("Thêm mới"))
                .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
                .HasButtonStyle(ButtonStyle.Primary)
                .HasCssClass(Constants.RowLeft);

            result.AddAction().HasText(T("Tạo Xml"))
                .HasUrl(Url.Action("Index", "AdminVastXml"))
                .HasButtonStyle(ButtonStyle.Success)
                .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildSites(true, Extensions.Constants.CategoryId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildCategories)).HasParentClass(Constants.ContainerCssClassCol3).HasRow(true);

            result.AddRowAction()
               .HasText(T("Sửa"))
               .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
               .HasButtonStyle(ButtonStyle.Default)
               .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddRowAction(true)
                .HasText(T("Xóa"))
                .HasName("Delete")
                .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString()))
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");

            return result;
        }

        private ControlGridAjaxData<AdvertisementGroupInfo> GetAdvertisementGroup(ControlGridFormRequest options)
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var categoryId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.CategoryId]))
            {
                categoryId = Convert.ToInt32(Request.Form[Extensions.Constants.CategoryId]);
            }

            int totals;
            var items = WorkContext.Resolve<IAdvertisementGroupService>().SearchPaged(languageCode, siteId, categoryId, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<AdvertisementGroupInfo>(items, totals);

            return result;
        }

        [Url("admin/advertisementgroup/edit")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý nhóm quảng cáo"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin nhóm quảng cáo"), Url = "#" });

            if (!ModelState.IsValid)
            {
                return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var model = new AdvertisementGroupModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<IAdvertisementGroupService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<AdvertisementGroupModel>(model)
            {
                Title = T("Thông tin nhóm quảng cáo"),
                UpdateActionName = "Update",
                FormMethod = FormMethod.Post,
                SubmitButtonText = T("Lưu lại"),
                ShowBoxHeader = false,
                ShowCancelButton = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.MakeReadOnlyProperty(x => x.Code);
            result.AddAction().HasText(T("Làm mới"))
                .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
                .HasCssClass("btn btn-success");

            result.AddAction().HasText(T("Trở về"))
               .HasUrl(Url.Action("Index"))
               .HasCssClass("btn btn-danger");

            result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages());
            result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage"));
            result.RegisterCascadingDropDownDataSource(x => x.CategoryId, Url.Action("GetCategoriesBySite"));
            result.RegisterCascadingDropDownDataSource(x => x.AdvertisementIds, Url.Action("GetAdBySite"));

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/advertisementgroup/update")]
        public ActionResult Update(AdvertisementGroupModel model)
        {
            if (!ModelState.IsValid)
            {
                return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var service = WorkContext.Resolve<IAdvertisementGroupService>();
            AdvertisementGroupInfo item = model.Id == 0 ? new AdvertisementGroupInfo() : service.GetById(model.Id);
            item.LanguageCode = model.LanguageCode;
            item.SiteId = model.SiteId;
            item.CategoryId = model.CategoryId;
            item.Code = model.Code;
            item.GroupName = model.GroupName;
            item.Description = model.Description;
            item.AdvertisementIds = Utilities.ParseString(model.AdvertisementIds);
            item.IsGenerate = model.IsGenerate;
            item.IsActived = model.IsActived;
            item.CreateDate = DateTime.Now;
            item.FinishDate = DateTime.ParseExact(model.FinishDate, Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture);
            item.FinishTime = model.FinishTime;
            service.Save(item);

            return new AjaxResult()
                .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"));
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<IAdvertisementGroupService>();
            var obj = service.GetById(id);
            obj.IsActived = false;
            service.Update(obj);

            return new AjaxResult()
                .NotifyMessage("DELETE_ENTITY_COMPLETE")
                .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!"));
        }
    }
}
<file_sep>﻿using System;
using System.Globalization;
using System.Web.Mvc;
using CMSSolutions.Extensions;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{   
    [Themed(IsDashboard = true), Authorize]
    public class AdminBankCardController : BaseAdminController
    {
        public AdminBankCardController(IWorkContextAccessor workContextAccessor) 
             : base(workContextAccessor)
        {
            TableName = "tblBankCards";
        }

        [Url("admin/bank-cards")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý dịch vụ thẻ ngân hàng"), Url = "#" });

            var result = new ControlGridFormResult<BankCardInfo>
            {
                Title = T("Quản lý dịch vụ thẻ ngân hàng"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetBankCards,
                DefaultPageSize = WorkContext.DefaultPageSize,
                EnablePaginate = true,
                UpdateActionName = "Update",
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml,
                ClientId = TableName,
                ActionsColumnWidth = 100
            };

            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true);

            result.AddColumn(x => x.Id, T("ID")).HasWidth(60).AlignCenter();
            result.AddColumn(x => x.BankCode, T("Mã ngân hàng")).AlignCenter().HasWidth(150);
            result.AddColumn(x => x.BankName, T("Tên ngân hàng"));
            result.AddColumn(x => EnumExtensions.GetDisplayName((Status)x.Status), T("Trạng thái"));

            result.AddAction().HasText(T("Thêm mới"))
                .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
                .HasButtonStyle(ButtonStyle.Primary)
                .HasBoxButton(false)
                .HasRow(false)
                .HasCssClass(Constants.RowLeft)
                .HasRow(true)
                .ShowModalDialog();

            result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
                .HasText(T("Sửa"))
                .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                .HasButtonStyle(ButtonStyle.Default)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .ShowModalDialog();

            result.AddRowAction(true)
                .HasText(T("Xóa"))
                .HasName("Delete")
                .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString()))
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");
            return result;
        }

        private ControlGridAjaxData<BankCardInfo> GetBankCards(ControlGridFormRequest options)
        {
            var status = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId]))
            {
                status = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]);
            }

            int totals;
            var items = WorkContext.Resolve<IBankCardService>().GetPaged(status, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<BankCardInfo>(items, totals);

            return result;
        }

        [Themed(false)]
        [Url("admin/bank-cards/edit/{id}")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý dịch vụ thẻ ngân hàng"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin dịch vụ thẻ ngân hàng"), Url = "#" });

            var model = new BankCardModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<IBankCardService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<BankCardModel>(model)
            {
                Title = T("Thông tin dịch vụ thẻ ngân hàng"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                CancelButtonText = T("Đóng"),
                ShowBoxHeader = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.RegisterExternalDataSource(x => x.Status, y => BindStatus());

            return result;
        }
        
        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/bank-cards/update")]
        public ActionResult Update(BankCardModel model)
        {
            if (!ModelState.IsValid)
            {
                return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var service = WorkContext.Resolve<IBankCardService>();
            BankCardInfo item = model.Id == 0 ? new BankCardInfo() : service.GetById(model.Id);

            item.BankCode = model.BankCode;
            item.BankName = model.BankName;
            item.Status = model.Status;
            service.Save(item);

            return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"))
                .CloseModalDialog();
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<IBankCardService>();
            var item = service.GetById(id);
            item.Status = (int)Status.Deleted;
            service.Update(item);

            return new AjaxResult()
                .NotifyMessage("DELETE_ENTITY_COMPLETE")
                .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!"));
        }
    }
}
<file_sep>﻿using System.Web.Mvc;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Themes;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = false)]
    public class HomeDigCoinsController : BaseHomeController
    {
        public HomeDigCoinsController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
            PageIndex = 1;
        }

        [HttpGet]
        [Url("{alias}/d{id}.html")]
        public ActionResult Index(string alias, int id)
        {
            if (!IsLogin)
            {
                return Redirect(Url.Action("Index", "Home"));
            }

            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            SiteId = (int)Site.Home;
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;
            serviceCategory.SiteId = SiteId;
            var category = serviceCategory.GetByIdCache(id);
            ViewData[Extensions.Constants.HeaderTitle] = category.Name;
            ViewData[Extensions.Constants.HeaderDescription] = category.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = category.Tags;

            if (Request.QueryString["trang"] != null)
            {
                PageIndex = int.Parse(Request.QueryString["trang"]);
            }
            PageSize = 10;

            BuildFilmModules();

            return View();
        }

        [Url("{alias}/thongtin/{id}.html")]
        public ActionResult ShowInformations(string alias, int id)
        {
            if (!IsLogin)
            {
                return Redirect(Url.Action("Index", "Home"));
            }

            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            SiteId = (int)Site.Home;
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;
            serviceCategory.SiteId = SiteId;
            var category = serviceCategory.GetByIdCache(id);
            ViewData[Extensions.Constants.HeaderTitle] = category.Name;
            ViewData[Extensions.Constants.HeaderDescription] = category.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = category.Tags;

            var viewRenderer = new ViewRenderer { Context = ControllerContext };
            var customerService = WorkContext.Resolve<ICustomerService>();
            var model = new DataViewerModel
            {
                Customer = customerService.GetCustomerByCacheId(UserId),
                DataType = 0
            };

            var view = viewRenderer.RenderPartialView(Extensions.Constants.DaoXuInformationsFilePath, model);
            WorkContext.Layout.FullContent.Add(new MvcHtmlString(view));

            return View("Index");
        }

        [Url("{alias}/xem-logs/{id}.html")]
        public ActionResult ShowLogs(string alias, int id)
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            SiteId = (int)Site.Home;
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;
            serviceCategory.SiteId = SiteId;
            var category = serviceCategory.GetByIdCache(id);
            ViewData[Extensions.Constants.HeaderTitle] = category.Name;
            ViewData[Extensions.Constants.HeaderDescription] = category.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = category.Tags;

            var viewRenderer = new ViewRenderer { Context = ControllerContext };
            var customerService = WorkContext.Resolve<ICustomerService>();
            var service = WorkContext.Resolve<IDownloadCustomerService>();
            var model = new DataViewerModel
            {
                Customer = customerService.GetCustomerByCacheId(UserId),
                DataType = 2,
                ListHistoryDownload = service.GetHistory(UserId)
            };

            var view = viewRenderer.RenderPartialView(Extensions.Constants.DaoXuLogsFilePath, model);
            WorkContext.Layout.FullContent.Add(new MvcHtmlString(view));

            return View("Index");
        }

        [Url("{alias}/huong-dan/{id}.html")]
        public ActionResult ShowHelps(string alias, int id)
        {
            if (!IsLogin)
            {
                return Redirect(Url.Action("Index", "Home"));
            }

            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            SiteId = (int)Site.Home;
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;
            serviceCategory.SiteId = SiteId;
            var category = serviceCategory.GetByIdCache(id);
            ViewData[Extensions.Constants.HeaderTitle] = category.Name;
            ViewData[Extensions.Constants.HeaderDescription] = category.Description;
            ViewData[Extensions.Constants.HeaderKeywords] = category.Tags;

            var viewRenderer = new ViewRenderer { Context = ControllerContext };
            var customerService = WorkContext.Resolve<ICustomerService>();
            var model = new DataViewerModel
            {
                Customer = customerService.GetCustomerByCacheId(UserId),
                DataType = 3
            };

            var view = viewRenderer.RenderPartialView(Extensions.Constants.DaoXuHelpsFilePath, model);
            WorkContext.Layout.FullContent.Add(new MvcHtmlString(view));

            return View("Index");
        }

        private void BuildFilmModules()
        {
            var viewRenderer = new ViewRenderer {Context = ControllerContext};
            if (!IsVip)
            {

            }

            var customerService = WorkContext.Resolve<ICustomerService>();
            var service = WorkContext.Resolve<IDownloadGameService>();
            var downloadService = WorkContext.Resolve<IDownloadCustomerService>();
            var model = new DataViewerModel
            {
                Customer = customerService.GetCustomerByCacheId(UserId),
                PageIndex = PageIndex,
                PageSize = PageSize,
                DataType = 1,
                ListDownloadCustomer = downloadService.GetByCustomer(UserId)
            };

            var totalRow = 0;
            model.ListGames = service.GetPaged(model.PageIndex, model.PageSize, out totalRow);
            model.TotalRow = totalRow;
            var view = viewRenderer.RenderPartialView(Extensions.Constants.DigCoinsFilePath, model);
            WorkContext.Layout.FullContent.Add(new MvcHtmlString(view));
        }
    }
}
<file_sep>using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class FilmVideoInfo : BaseEntity<long>
    {
        [DataMember]
        [DisplayName("FilmId")]
        public long FilmId { get; set; }

        [DataMember]
        [DisplayName("EpisodeId")]
        public int EpisodeId { get; set; }

        [NotMapped]
        [DisplayName("EpisodeName")]
        public string EpisodeName { get; set; }

        [NotMapped]
        [DisplayName("EpisodeCount")]
        public int EpisodeCount { get; set; }
        
        [DataMember]
        [DisplayName("FileId")]
        public long FileId { get; set; }

        [NotMapped]
        [DisplayName("FileName")]
        public string FileName { get; set; }
        
        [DataMember]
        [DisplayName("FullPath")]
        public string FullPath { get; set; }

        [DataMember]
        [DisplayName("ImageIcon")]
        public string ImageIcon { get; set; }

        [DataMember]
        [DisplayName("IsTraller")]
        public bool IsTraller { get; set; }

        [DataMember]
        [DisplayName("IsActived")]
        public bool IsActived { get; set; }

        [DataMember]
        [DisplayName("UrlSource")]
        public string UrlSource { get; set; }

        [DataMember]
        [DisplayName("UrlAlbum")]
        public string UrlAlbum { get; set; }
        
        [DataMember]
        [DisplayName("Subtitle")]
        public string Subtitle { get; set; }
        
        [DataMember]
        [DisplayName("StreamingUrl")]
        public string StreamingUrl { get; set; }

        [DataMember]
        [DisplayName("BaseUrl")]
        public string BaseUrl { get; set; }
    }

    public class FilmVideoMap : EntityTypeConfiguration<FilmVideoInfo>, IEntityTypeConfiguration
    {
        public FilmVideoMap()
        {
            ToTable("Modules_FilmVideos");
            HasKey(m => m.Id);
            Property(m => m.FilmId).IsRequired();
            Property(m => m.FileId).IsRequired();
            Property(m => m.FullPath).HasMaxLength(300);
            Property(m => m.EpisodeId).IsRequired();
            Property(m => m.ImageIcon).HasMaxLength(500);
            Property(m => m.UrlSource).HasMaxLength(500);
            Property(m => m.Subtitle).HasMaxLength(500);
            Property(m => m.BaseUrl).HasMaxLength(500);
            Property(m => m.StreamingUrl).HasMaxLength(500);
            Property(m => m.UrlAlbum).HasMaxLength(500);
        }
    }
}
<file_sep>﻿using System;
using System.Globalization;
using System.Web.Mvc;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminAdvertisementController : BaseAdminController
    {
        public AdminAdvertisementController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
            TableName = "tblAdvertisements";
        }

        [Url("admin/advertisements")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý quảng cáo"), Url = "#" });

            var result = new ControlGridFormResult<AdvertisementInfo>
            {
                Title = T("Quản lý quảng cáo"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetAdvertisements,
                DefaultPageSize = WorkContext.DefaultPageSize,
                EnablePaginate = true,
                UpdateActionName = "Update",
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml,
                ClientId = TableName,
                ActionsColumnWidth = 100
            };

            result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.FromDate, "$('#" + Extensions.Constants.FromDate + "').val();", true);
            result.AddCustomVar(Extensions.Constants.ToDate, "$('#" + Extensions.Constants.ToDate + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true);

            result.AddColumn(x => x.KeyCode, T("Mã QC"));
            result.AddColumn(x => x.Title, T("Tiêu đề"));
            result.AddColumn(x => x.Link, T("Đường dẫn vast"));
            result.AddColumn(x => x.IsBlock)
                .HasHeaderText(T("Tạm khóa"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage(false);

            result.AddAction().HasText(T("Thêm mới"))
                .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
                .HasButtonStyle(ButtonStyle.Primary)
                .HasBoxButton(false)
                .HasRow(false)
                .HasCssClass(Constants.RowLeft)
                .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildSites(true, Extensions.Constants.CategoryId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildFromDate(false))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildToDate(false))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
               .HasText(T("Sửa"))
               .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
               .HasButtonStyle(ButtonStyle.Default)
               .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddRowAction(true)
                .HasText(T("Khóa"))
                .HasName("Delete")
                .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString()))
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");

            return result;
        }

        private ControlGridAjaxData<AdvertisementInfo> GetAdvertisements(ControlGridFormRequest options)
        {
            var searchText = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText]))
            {
                searchText = Request.Form[Extensions.Constants.SearchText];
            }

            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var fromDate = Utilities.DateNull();
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FromDate]))
            {
                fromDate = DateTime.ParseExact(Request.Form[Extensions.Constants.FromDate], Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture);
            }

            var toDate = Utilities.DateNull();
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ToDate]))
            {
                toDate = DateTime.ParseExact(Request.Form[Extensions.Constants.ToDate], Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture);
            }

            int totals;
            var items = WorkContext.Resolve<IAdvertisementService>().SearchPaged(searchText, languageCode, siteId, fromDate, toDate, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<AdvertisementInfo>(items, totals);

            return result;
        }

        [Url("admin/advertisements/edit")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý quảng cáo"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin quảng cáo"), Url = "#" });

            if (!ModelState.IsValid)
            {
                return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var model = new AdvertisementModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<IAdvertisementService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<AdvertisementModel>(model)
            {
                Title = T("Thông tin quảng cáo"),
                UpdateActionName = "Update",
                FormMethod = FormMethod.Post,
                SubmitButtonText = T("Lưu lại"),
                ShowBoxHeader = false,
                ShowCancelButton = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };
            result.MakeReadOnlyProperty(x => x.KeyCode);
            result.AddAction().HasText(T("Làm mới"))
                .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
                .HasCssClass("btn btn-success");

            result.AddAction().HasText(T("Trở về"))
               .HasUrl(Url.Action("Index"))
               .HasCssClass("btn btn-danger");

            result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages());
            result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage"));

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/advertisements/update")]
        public ActionResult Update(AdvertisementModel model)
        {
            var service = WorkContext.Resolve<IAdvertisementService>();
            AdvertisementInfo adsInfo = model.Id == 0 ? new AdvertisementInfo() : service.GetById(model.Id);
            adsInfo.Id = model.Id;
            adsInfo.LanguageCode = model.LanguageCode;
            adsInfo.SiteId = model.SiteId;
            adsInfo.Title = model.Title;
            adsInfo.KeyCode = model.KeyCode;
            adsInfo.Price = Convert.ToDecimal(model.Price);
            adsInfo.Code = model.Code;
            adsInfo.Link = model.Link;
            adsInfo.Type = model.Type;
            adsInfo.Duration = model.Duration;
            adsInfo.Position = model.Position;
            adsInfo.Skip = model.Skip;
            adsInfo.IsBlock = model.IsBlock;
            adsInfo.Click = string.Empty;
            service.Save(adsInfo);

            return new AjaxResult()
                .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"));
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<IAdvertisementService>();
            var obj = service.GetById(id);
            obj.IsBlock = true;
            service.Update(obj);

            return new AjaxResult()
                .NotifyMessage("DELETE_ENTITY_COMPLETE")
                .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!"));
        }
    }
}
<file_sep>﻿using CMSSolutions.Localization;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Permissions;

namespace CMSSolutions.Websites.Menus
{
    public class NavigationProvider : INavigationProvider
    {
        public Localizer T { get; set; }

        public NavigationProvider()
        {
            T = NullLocalizer.Instance;
        }

        public void GetNavigation(NavigationBuilder builder)
        {
            builder.Add(T("Home"), "0", BuildHomeMenu);
            builder.Add(T("Danh mục"), "1", BuildManagers);

            builder.Add(T("Quản lý chuyên mục"), "2", b => b.Action("Index", "AdminCategory", new { area = "" })
                .IconCssClass("fa-th")
                .Permission(AdminPermissions.ManagerCategories));

            builder.Add(T("Quản lý tin tức"), "3", b => b.Action("Index", "AdminArticles", new { area = "" })
                .IconCssClass("fa-rss-square")
                .Permission(AdminPermissions.ManagerArticles));

            builder.Add(T("Quản lý phim"), "4", BuildMenuFilms);
            builder.Add(T("Quản lý giao dịch"), "5", BuildMenuCustomers);
            builder.Add(T("Quản lý logs"), "6", BuildMenuLogs);
            builder.Add(T("Quản lý đối soát"), "7", BuildReports);
            builder.Add(T("Hỏi đáp"), "8", BuildQandA);
            builder.Add(T("Đào xu"), "9", b => b.Action("Index", "AdminDownloadGames", new { area = "" })
                .IconCssClass("fa-bullseye")
                .Permission(AdminPermissions.ManagerDownloadGames));
            builder.Add(T("Quảng cáo"), "10", BuildAds);
        }

        private void BuildHomeMenu(NavigationItemBuilder builder)
        {
            builder.IconCssClass("fa-home")
                .Action("Index", "Admin", new { area = "" })
                .Permission(AdminPermissions.ManagerAdmin);
        }

        private void BuildManagers(NavigationItemBuilder builder)
        {
            builder.IconCssClass("fa-qrcode");

            builder.Add(T("Quản lý trang"), "0", b => b
                .Action("Index", "AdminSite", new {area = ""})
                .IconCssClass("fa-flag")
                .Permission(AdminPermissions.ManagerSites));

            builder.Add(T("Nước sản xuất"), "1", b => b
                .Action("Index", "AdminCountry", new { area = "" })
                .Permission(AdminPermissions.ManagerCountries));

            builder.Add(T("Đạo diễn"), "2", b => b
                .Action("Index", "AdminDirector", new { area = "" })
                .Permission(AdminPermissions.ManagerDirectors));

            builder.Add(T("Diễn viên"), "3", b => b
                .Action("Index", "AdminActor", new { area = "" })
                .Permission(AdminPermissions.ManagerActors));

            builder.Add(T("Thể loại phim"), "4", b => b
                .Action("Index", "AdminFilmTypes", new { area = "" })
                .Permission(AdminPermissions.ManagerFilmTypes));

            builder.Add(T("Bộ phim"), "5", b => b
                .Action("Index", "AdminCollection", new { area = "" })
                .Permission(AdminPermissions.ManagerCollections));

            builder.Add(T("Tập phim"), "6", b => b
                .Action("Index", "AdminEpisode", new { area = "" })
                .Permission(AdminPermissions.ManagerEpisodes));

            builder.Add(T("Tags"), "7", b => b
                .Action("Index", "AdminTag", new { area = "" })
                .Permission(AdminPermissions.ManagerTags));
        }

        private void BuildMenuFilms(NavigationItemBuilder builder)
        {
            builder.IconCssClass("fa-film");

            builder.Add(T("Máy chủ"), "0", b => b
                .Action("Index", "AdminFilmServer", new { area = "" })
                .Permission(AdminPermissions.ManagerServerFilms));

            builder.Add(T("Videos"), "1", b => b
               .Action("Index", "FilmFiles", new { area = "" })
               .Permission(AdminPermissions.ManagerFilmFiles));

            builder.Add(T("Phim"), "2", b => b
               .Action("Index", "AdminFilm", new { area = "" })
               .Permission(AdminPermissions.ManagerFilms));

            builder.Add(T("Slider"), "3", b => b
               .Action("Index", "AdminSlider", new { area = "" })
               .Permission(AdminPermissions.ManagerSlider));
        }

        private void BuildMenuCustomers(NavigationItemBuilder builder)
        {
            builder.IconCssClass("fa-shopping-cart");

            builder.Add(T("Loại thẻ cào"), "0", b => b
              .Action("Index", "AdminCardType", new { area = "" })
              .Permission(AdminPermissions.ManagerCardTypes));

            builder.Add(T("Thẻ ngân hàng"), "1", b => b
              .Action("Index", "AdminBankCard", new { area = "" })
              .Permission(AdminPermissions.ManagerBankCards));

            builder.Add(T("Thẻ VIP"), "2", b => b
              .Action("Index", "AdminVIPCard", new { area = "" })
              .Permission(AdminPermissions.ManagerVipCards));

            builder.Add(T("Khách hàng"), "3", b => b
              .Action("Index", "AdminCustomer", new { area = "" })
              .Permission(AdminPermissions.ManagerCustomers));

            builder.Add(T("Khuyến mãi"), "4", b => b
                .Action("Index", "AdminPromotion", new { area = "" })
                .Permission(AdminPermissions.ManagerPromotions));
        }

        private void BuildMenuLogs(NavigationItemBuilder builder)
        {
            builder.IconCssClass("fa-bug");

            builder.Add(T("Logs hệ thống"), "0", b => b
                .Action("Index", "AdminLog", new { area = "" })
                .Permission(AdminPermissions.ManagerSystemLogs));
        }

        private void BuildReports(NavigationItemBuilder builder)
        {
            builder.IconCssClass("fa fa-bar-chart-o");

            builder.Add(T("Đối soát SMS"), "0", b => b
                .Action("Index", "AdminReportSms", new { area = "" })
                .Permission(AdminPermissions.ManagerAdminReportSms));

            builder.Add(T("Đối soát ATM"), "1", b => b
                .Action("Index", "AdminReportBank", new { area = "" })
                .Permission(AdminPermissions.ManagerAdminReportAtm));

            builder.Add(T("Đối soát thẻ cào"), "2", b => b
                .Action("Index", "AdminReportCard", new { area = "" })
                .Permission(AdminPermissions.ManagerAdminReportCard));
        }

        private void BuildAds(NavigationItemBuilder builder)
        {
            builder.IconCssClass("fa-desktop");

            builder.Add(T("Danh mục"), "0", b => b
                .Action("Index", "AdminAdvertisement", new { area = "" })
                .Permission(AdminPermissions.ManagerAdvertisement));

            builder.Add(T("Nội dung"), "1", b => b
                .Action("Index", "AdminVast", new { area = "" })
                .Permission(AdminPermissions.ManagerVast));

            builder.Add(T("Phân nhóm"), "2", b => b
                .Action("Index", "AdminAdvertisementGroup", new { area = "" })
                .Permission(AdminPermissions.ManagerAdvertisementGroup));
        }

        private void BuildQandA(NavigationItemBuilder builder)
        {
            builder.IconCssClass("fa-comments-o");

            builder.Add(T("Hỏi đáp"), "0", b => b
                .Action("Index", "AdminSupport", new { area = "" })
               .Permission(AdminPermissions.ManagerSupports));

            builder.Add(T("Đánh giá, báo lỗi"), "1", b => b
                .Action("Index", "AdminRate", new { area = "" })
               .Permission(AdminPermissions.ManagerRates));
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using DotNetOpenAuth.AspNet.Clients;
using DotNetOpenAuth.Messaging;
using Newtonsoft.Json;

namespace CMSSolutions.Websites.Extensions
{
    public class GoogleClient : OAuth2Client
    {
        private const string AuthorizationEndpoint = "https://accounts.google.com/o/oauth2/auth";

        private const string TokenEndpoint = "https://accounts.google.com/o/oauth2/token";

        private const string UserInfoEndpoint = "https://www.googleapis.com/oauth2/v1/userinfo";

        private readonly string clientId;

        private readonly string clientSecret;

        public GoogleClient(string clientId, string clientSecret)
            : base("Google")
        {
            if (clientId == null)
                throw new ArgumentNullException("clientId");
            if (clientSecret == null)
                throw new ArgumentNullException("clientSecret");

            this.clientId = clientId;
            this.clientSecret = clientSecret;
        }

        protected override Uri GetServiceLoginUrl(Uri returnUrl)
        {
            var uriBuilder = new UriBuilder(AuthorizationEndpoint);
            uriBuilder.AppendQueryArgument("client_id", this.clientId);
            uriBuilder.AppendQueryArgument("redirect_uri", returnUrl.GetLeftPart(UriPartial.Path));
            uriBuilder.AppendQueryArgument("response_type", "code");
            uriBuilder.AppendQueryArgument("scope", "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email");
            uriBuilder.AppendQueryArgument("state", returnUrl.Query.Substring(1));

            return uriBuilder.Uri;
        }

        protected override IDictionary<string, string> GetUserData(string accessToken)
        {
            var uriBuilder = new UriBuilder(UserInfoEndpoint);
            uriBuilder.AppendQueryArgument("access_token", accessToken);

            WebRequest webRequest = WebRequest.Create(uriBuilder.Uri);
            using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
            {
                if (webResponse.StatusCode == HttpStatusCode.OK)
                {
                    using (var responseStream = webResponse.GetResponseStream())
                    {
                        if (responseStream == null)
                            return null;

                        var streamReader = new StreamReader(responseStream);

                        var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(streamReader.ReadToEnd());
                        if (values.ContainsKey("email") && !values.ContainsKey("username"))
                            values.Add("username", values["email"]);

                        return values;
                    }
                }
            }

            return null;
        }

        protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
        {
            var values = new Dictionary<string, string>
            {
                {"code", authorizationCode},
                {"client_id", this.clientId},
                {"client_secret", this.clientSecret},
                {"redirect_uri", returnUrl.GetLeftPart(UriPartial.Path)},
                {"grant_type", "authorization_code"}
            };
            string postData = String.Join("&", values.Select(x => Uri.EscapeDataString(x.Key) + "=" + Uri.EscapeDataString(x.Value)).ToArray());
            WebRequest webRequest = WebRequest.Create(TokenEndpoint);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = postData.Length;
            webRequest.Method = "POST";
            using (Stream requestStream = webRequest.GetRequestStream())
            {
                var streamWriter = new StreamWriter(requestStream);
                streamWriter.Write(postData);
                streamWriter.Flush();
            }
            using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
            {
                if (webResponse.StatusCode == HttpStatusCode.OK)
                {
                    using (Stream responseStream = webResponse.GetResponseStream())
                    {
                        var streamReader = new StreamReader(responseStream);
                        dynamic response = JsonConvert.DeserializeObject<dynamic>(streamReader.ReadToEnd());
                        return (string)response.access_token;
                    }
                }
            }

            return null;
        }

        public static void RewriteRequest()
        {
            var ctx = HttpContext.Current;

            var stateString = HttpUtility.UrlDecode(ctx.Request.QueryString["state"]);
            if (stateString == null || !stateString.Contains("__provider__=Google"))
                return;

            var q = HttpUtility.ParseQueryString(stateString);
            q.Add(ctx.Request.QueryString);
            q.Remove("state");

            ctx.RewritePath(ctx.Request.Path + "?" + q);
        }
    }
}<file_sep>using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;
using CMSSolutions.Websites.Extensions;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class FilmInfo : BaseEntity<long>
    {
        [DataMember]
        [DisplayName("FilmCode")]
        public string FilmCode { get; set; }

        [DataMember]
        [DisplayName("FilmNameEnglish")]
        public string FilmNameEnglish { get; set; }

        [DataMember]
        [DisplayName("FilmName")]
        public string FilmName { get; set; }
        
        [DataMember]
        [DisplayName("FilmAlias")]
        public string FilmAlias { get; set; }
        
        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }
        
        [DataMember]
        [DisplayName("SiteId")]
        public int SiteId { get; set; }
        
        [DataMember]
        [DisplayName("CategoryIds")]
        public string CategoryIds { get; set; }

        [NotMapped]
        [DisplayName("CategoryAlias")]
        public string CategoryAlias { get; set; }

        [NotMapped]
        [DisplayName("CategoryNames")]
        public string CategoryNames { get; set; }
        
        [DataMember]
        [DisplayName("FilmTypeIds")]
        public string FilmTypeIds { get; set; }

        [NotMapped]
        [DisplayName("FilmTypeNames")]
        public string FilmTypeNames { get; set; }

        [NotMapped]
        [DisplayName("EpisodeCount")]
        public int EpisodeCount { get; set; }
        
        [DataMember]
        [DisplayName("CountryId")]
        public int CountryId { get; set; }

        [NotMapped]
        [DisplayName("CountryName")]
        public string CountryName { get; set; }

        [DataMember]
        [DisplayName("DirectorId")]
        public int DirectorId { get; set; }

        [NotMapped]
        [DisplayName("DirectorName")]
        public string DirectorName { get; set; }

        [DataMember]
        [DisplayName("ActorIds")]
        public string ActorIds { get; set; }

        [NotMapped]
        [DisplayName("ActorNames")]
        public string ActorNames { get; set; }

        [DataMember]
        [DisplayName("CollectionId")]
        public int CollectionId { get; set; }

        [NotMapped]
        [DisplayName("CollectionName")]
        public string CollectionName { get; set; }

        [DataMember]
        [DisplayName("IsFilmRetail")]
        public bool IsFilmRetail { get; set; }

        [DataMember]
        [DisplayName("IsFilmLengthEpisodes")]
        public bool IsFilmLengthEpisodes { get; set; }

        [DataMember]
        [DisplayName("ArticlesId")]
        public int ArticlesId { get; set; }

        [DataMember]
        [DisplayName("Time")]
        public string Time { get; set; }

        [DataMember]
        [DisplayName("Capacity")]
        public string Capacity { get; set; }

        [DataMember]
        [DisplayName("ReleaseYear")]
        public int ReleaseYear { get; set; }

        [DataMember]
        [DisplayName("CommentCount")]
        public int CommentCount { get; set; }

        [DataMember]
        [DisplayName("ViewCount")]
        public int ViewCount { get; set; }

        [DataMember]
        [DisplayName("CreateByUserId")]
        public int CreateByUserId { get; set; }

        [NotMapped]
        [DisplayName("FullName")]
        public string FullName { get; set; }

        [DataMember]
        [DisplayName("CreateDate")]
        public DateTime CreateDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string DisplayDate { get { return Utilities.DateString(CreateDate); } }

        [DataMember]
        [DisplayName("Contents")]
        public string Contents { get; set; }

        [DataMember]
        [DisplayName("Summary")]
        public string Summary { get; set; }

        [DataMember]
        [DisplayName("Description")]
        public string Description { get; set; }

        [DataMember]
        [DisplayName("Tags")]
        public string Tags { get; set; }

        [DataMember]
        [DisplayName("IsPublished")]
        public bool IsPublished { get; set; }

        [DataMember]
        [DisplayName("PublishedDate")]
        public DateTime? PublishedDate { get; set; }

        [DataMember]
        [DisplayName("IsHot")]
        public bool IsHot { get; set; }
        
        [DataMember]
        [DisplayName("IsHome")]
        public bool IsHome { get; set; }
        
        [DataMember]
        [DisplayName("Prices")]
        public decimal Prices { get; set; }
        
        [DataMember]
        [DisplayName("HasCopyright")]
        public bool HasCopyright { get; set; }
        
        [DataMember]
        [DisplayName("StartDate")]
        public DateTime? StartDate { get; set; }
        
        [DataMember]
        [DisplayName("EndDate")]
        public DateTime? EndDate { get; set; }
        
        [DataMember]
        [DisplayName("ImageIcon")]
        public string ImageIcon { get; set; }
        
        [DataMember]
        [DisplayName("ImageThumb")]
        public string ImageThumb { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string EncodeImageThumb
        {
            get
            {
                if (!string.IsNullOrEmpty(ImageThumb))
                {
                    return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ImageThumb));
                }

                return string.Empty;
            }
        }
        
        [DataMember]
        [DisplayName("ServerId")]
        public int ServerId { get; set; }
        
        [DataMember]
        [DisplayName("ServerIP")]
        public string ServerIp { get; set; }

        [NotMapped]
        [DisplayName("ServerName")]
        public string ServerName { get; set; }

        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }

        [DataMember]
        [DisplayName("IsTheater")]
        public bool IsTheater { get; set; }

        [DataMember]
        [DisplayName("IsShow")]
        public bool IsShow { get; set; }

        [DataMember]
        [DisplayName("IsClip")]
        public bool IsClip { get; set; }

        [DataMember]
        [DisplayName("IsTrailer")]
        public bool IsTrailer { get; set; }

        [DataMember]
        [DisplayName("IsFilm")]
        public bool IsFilm { get; set; }

        #region Videos
        [NotMapped]
        [DisplayName("FullPath")]
        public string FullPath { get; set; }

        [NotMapped]
        [DisplayName("EpisodeId")]
        public int EpisodeId { get; set; }

        [NotMapped]
        [DisplayName("ImageIcon2")]
        public string ImageIcon2 { get; set; }

        [NotMapped]
        [DisplayName("HasTraller")]
        public bool HasTraller { get; set; }

        [NotMapped]
        [DisplayName("UrlSource")]
        public string UrlSource { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string EncodeSourceUrl
        {
            get
            {
                if (string.IsNullOrEmpty(UrlAlbum) && !string.IsNullOrEmpty(UrlSource))
                {
                    return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(UrlSource));
                    
                }

                return string.Empty;
            }
        }

        [NotMapped]
        [DisplayName("Subtitle")]
        public string Subtitle { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string EncodeSubtitle
        {
            get
            {
                if (!string.IsNullOrEmpty(Subtitle))
                {
                    return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Subtitle));
                }

                return string.Empty;
            }
        }

        [NotMapped]
        [DisplayName("StreamingUrl")]
        public string StreamingUrl { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string EncodeStreamingUrl
        {
            get
            {
                if (!string.IsNullOrEmpty(StreamingUrl))
                {
                    return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(StreamingUrl));
                }

                return string.Empty;
            }
        }

        [NotMapped]
        [DisplayName("BaseUrl")]
        public string BaseUrl { get; set; }

        [NotMapped]
        [DisplayName("UrlAlbum")]
        public string UrlAlbum { get; set; }

        [NotMapped]
        [DisplayName("EpisodeName")]
        public string EpisodeName { get; set; }

        [NotMapped]
        [DisplayName("EpisodeIndex")]
        public int EpisodeIndex { get; set; }
        #endregion
    }

    public class FilmMap : EntityTypeConfiguration<FilmInfo>, IEntityTypeConfiguration
    {
        public FilmMap()
        {
            ToTable("Modules_Film");
            HasKey(m => m.Id);
            Property(m => m.FilmCode).IsRequired().HasMaxLength(50);
            Property(m => m.FilmNameEnglish).HasMaxLength(250);
            Property(m => m.FilmName).IsRequired().HasMaxLength(250);
            Property(m => m.FilmAlias).IsRequired().HasMaxLength(250);
            Property(m => m.LanguageCode).IsRequired().HasMaxLength(50);
            Property(m => m.SiteId).IsRequired();
            Property(m => m.CategoryIds).HasMaxLength(250).IsRequired();
            Property(m => m.FilmTypeIds).HasMaxLength(250).IsRequired();
            Property(m => m.CountryId).IsRequired();
            Property(m => m.DirectorId).IsRequired();
            Property(m => m.ActorIds).IsRequired().HasMaxLength(250);
            Property(m => m.Time).IsRequired().HasMaxLength(50);
            Property(m => m.Capacity).IsRequired().HasMaxLength(50);
            Property(m => m.Contents).IsRequired();
            Property(m => m.Summary).IsRequired().HasMaxLength(400);
            Property(m => m.Description).IsRequired().HasMaxLength(400);
            Property(m => m.Tags).IsRequired().HasMaxLength(250);
            Property(m => m.ImageIcon).IsRequired().HasMaxLength(250);
            Property(m => m.ImageThumb).HasMaxLength(250);
            Property(m => m.ServerIp).IsRequired().HasMaxLength(50);
        }
    }
}
<file_sep>﻿using System;
using System.Text;
using System.Web.Mvc;
using CMSSolutions.ContentManagement.Widgets.Services;
using CMSSolutions.DisplayManagement;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Themes;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = false)]
    public class HomeNewsController : BaseHomeController
    {
        private readonly dynamic shapeFactory;
        public HomeNewsController(IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory)
            : base(workContextAccessor)
        {
            this.shapeFactory = shapeFactory;
            PageIndex = 1;
        }

        [Url("tintuc.html")]
        public ActionResult Index()
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            BuildNewsModules((int)FixCategories.AllNews, true);

            return View();
        }

        [Url("{alias}/nc{id}.html")]
        public ActionResult ViewNewsCategory(string alias, int id)
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            BuildNewsModules(id, true);

            return View();
        }

        [Url("tintuc/{alias}/n{id}.html")]
        public ActionResult ViewDetails(string alias, int id)
        {
            UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home");
            BuildNewsModules(id, false);

            return View();
        }

        private void BuildNewsModules(int id, bool isCategory)
        {
            var widget = WorkContext.Resolve<IWidgetService>();
            var viewRenderer = new ViewRenderer { Context = ControllerContext };
            if (!IsVip)
            {
                #region BannerRightFifth
                var bannerRightFifth = widget.GetWidget(HomeWidgets.BannerRightFifth.ToString());
                if (bannerRightFifth != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerRightFifth;
                    WorkContext.Layout.AdBannerRightFifth(widgetShape);
                }
                #endregion
            }
            else
            {
                #region BannerPageLeftVip
                var bannerPageLeftVip = widget.GetWidget(HomeWidgets.BannerPageLeftVip.ToString());
                if (bannerPageLeftVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageLeftVip;
                    WorkContext.Layout.AdBannerPageLeftVip(widgetShape);
                }
                #endregion

                #region BannerPageCenterVip
                var bannerPageCenterVip = widget.GetWidget(HomeWidgets.BannerPageCenterVip.ToString());
                if (bannerPageCenterVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageCenterVip;
                    WorkContext.Layout.AdBannerPageCenterVip(widgetShape);
                }
                #endregion

                #region BannerPageRightVip
                var bannerPageRightVip = widget.GetWidget(HomeWidgets.BannerPageRightVip.ToString());
                if (bannerPageRightVip != null)
                {
                    var widgetShape = shapeFactory.Widget();
                    widgetShape.Widget = bannerPageRightVip;
                    WorkContext.Layout.AdBannerPageRightVip(widgetShape);
                }
                #endregion
            }

            #region HomeFooterLogoInformation
            var homeFooterLogoInformation = widget.GetWidget(HomeWidgets.HomeFooterLogoInformation.ToString());
            if (homeFooterLogoInformation != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = homeFooterLogoInformation;
                WorkContext.Layout.FooterLogoInformation(widgetShape);
            }
            #endregion

            #region BannerRightFirst
            var view = viewRenderer.RenderPartialView(Extensions.Constants.DivDisplayFilePath, null);
            WorkContext.Layout.AdBannerRightFirst.Add(new MvcHtmlString(view));
            #endregion

            #region HomeFacebookFanpage
            var homeFacebookFanpage = widget.GetWidget(HomeWidgets.HomeFacebookFanpage.ToString());
            if (homeFacebookFanpage != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = homeFacebookFanpage;
                WorkContext.Layout.AdFacebookFanpage(widgetShape);
            }
            #endregion

            #region SocialNetwork
            var socialNetwork = widget.GetWidget(HomeWidgets.DisplaySocialNetwork.ToString());
            if (socialNetwork != null)
            {
                var widgetShape = shapeFactory.Widget();
                widgetShape.Widget = socialNetwork;
                WorkContext.Layout.DisplaySocialNetwork(widgetShape);
            }
            #endregion

            #region News
            var viewNews = viewRenderer.RenderPartialView(Extensions.Constants.NewsViewFilePath, null);
            WorkContext.Layout.DisplayNews.Add(new MvcHtmlString(viewNews));
            #endregion

            #region Tags
            var serviceTags = WorkContext.Resolve<ITagService>();
            var modelTags = new TagViewModel { ListTags = serviceTags.GetDisplayTags() };
            var viewTags = viewRenderer.RenderPartialView(Extensions.Constants.TagViewFilePath, modelTags);
            WorkContext.Layout.DisplayTags.Add(new MvcHtmlString(viewTags));
            #endregion

            #region CategoryContentFirst
            SiteId = (int)Site.Home;
            PageSize = 15;
            if (Request.QueryString["trang"] != null)
            {
                PageIndex = int.Parse(Request.QueryString["trang"]);
            }
            var serviceNews = WorkContext.Resolve<IArticlesService>();
            serviceNews.LanguageCode = WorkContext.CurrentCulture;
            serviceNews.SiteId = SiteId;
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.SiteId = SiteId;
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;
            var modelFirst = new DataViewCategoryModel();
            if (!isCategory)
            {
                var news = serviceNews.GetById(id);
                ViewData[Extensions.Constants.HeaderTitle] = news.Title;
                ViewData[Extensions.Constants.HeaderDescription] = news.Description;
                ViewData[Extensions.Constants.HeaderKeywords] = news.Tags;

                modelFirst.News = news;
                modelFirst.CurrentCategory = serviceCategory.GetByIdCache(news.CategoryId);

                var viewFilmFirst = viewRenderer.RenderPartialView(Extensions.Constants.NewsDetailsViewFilePath, modelFirst);
                WorkContext.Layout.CategoryContentLeftFirst.Add(new MvcHtmlString(viewFilmFirst));

                #region CategoryContentLeftSecond
                var viewModel = new DataViewCategoryModel();
                viewModel.UrlNext = "http://" + Extensions.Constants.HomeDomainName + Url.Action("ViewDetails", "HomeNews", new { @alias = news.Alias, @id = news.Id });

                var viewCommentFirst = viewRenderer.RenderPartialView(Extensions.Constants.FacebookCommentsFilePath, viewModel);
                WorkContext.Layout.CategoryContentLeftSecond.Add(new MvcHtmlString(viewCommentFirst));
                #endregion
            }
            else
            {
                var category = serviceCategory.GetByIdCache(id);
                ViewData[Extensions.Constants.HeaderTitle] = category.Name;
                ViewData[Extensions.Constants.HeaderDescription] = category.Description;
                ViewData[Extensions.Constants.HeaderKeywords] = category.Tags;

                modelFirst.Breadcrumb = BuildBreadcrumb(category);
                modelFirst.CurrentCategory = category;

                var cateId = category.Id;
                if (cateId == (int)FixCategories.AllNews)
                {
                    cateId = 0;
                }
                serviceNews.CategoryId = cateId;
                var totalRow = 0;
                modelFirst.ListArticles = serviceNews.GetByCategoryPaged(PageIndex, PageSize, out  totalRow);
                modelFirst.TotalRow = totalRow;
                modelFirst.PageIndex = PageIndex;
                modelFirst.PageSize = PageSize;

                var viewFilmFirst = viewRenderer.RenderPartialView(Extensions.Constants.NewsCategoryViewFilePath, modelFirst);
                WorkContext.Layout.CategoryContentLeftFirst.Add(new MvcHtmlString(viewFilmFirst));
            }
            #endregion
           
            #region DisplayStatistic1
            var modelStatistic1 = new DataViewCategoryModel
            {
                Type = (int)HomeDisplayFilmType.StatisticalFilmRetail,
                Title = "PHIM LẺ XEM NHIỀU NHẤT"
            };
            var viewStatistic1 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic1FilePath, modelStatistic1);
            WorkContext.Layout.DisplayStatistic1.Add(new MvcHtmlString(viewStatistic1));
            #endregion

            #region DisplayStatistic2
            var modelStatistic2 = new DataViewCategoryModel
            {
                Type = (int)HomeDisplayFilmType.StatisticalLengthEpisodes,
                Title = "PHIM BỘ XEM NHIỀU NHẤT"
            };
            var viewStatistic2 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic2FilePath, modelStatistic2);
            WorkContext.Layout.DisplayStatistic2.Add(new MvcHtmlString(viewStatistic2));
            #endregion
        }

        private string BuildBreadcrumb(CategoryInfo category)
        {
            var serviceCategory = WorkContext.Resolve<ICategoryService>();
            serviceCategory.LanguageCode = WorkContext.CurrentCulture;
            serviceCategory.SiteId = SiteId;

            var html = new StringBuilder();
            html.Append("<div class=\"mh-breadcrumb-dv\">");
            html.Append("<div>");
            html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span><img width=\"22\" src=\"/Images/themes/ico-home_trans.png\"></span></a>", "Dành cho víp", "/");
            html.Append("</div>/ ");
            if (category.ParentId > 0)
            {
                var parent = serviceCategory.GetByIdCache(category.ParentId);
                html.Append("<div>");
                html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span>{0}</span></a>", parent.ShortName, Url.Action("Index", "HomeCategory", new { @alias = parent.Alias, @id = parent.Id }));
                html.Append("</div>/ ");
            }
            html.Append("<div>");
            html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span>{0}</span></a>", category.ShortName, "#");
            html.Append("</div>");

            html.Append("</div>");
            return html.ToString();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminPromotionCustomersController : BaseAdminController
    {
        public AdminPromotionCustomersController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
            TableName = "tblPromotionCustomers";
        }

        [Url("admin/promotion-customer/apply/{promotionId}")]
        public ActionResult Index(int promotionId)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý đợt khuyến mãi"), Url = Url.Action("Index","AdminPromotion") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Áp dụng chương trình khuyến mãi"), Url = "#" });
           
            var promotionCustomers = WorkContext.Resolve<IPromotionCustomersService>().GetCode(promotionId, 0);
            var model = new PromotionCustomersModel();
            var promotion = WorkContext.Resolve<IPromotionService>().GetById(promotionId);
            if (promotion != null)
            {
                model.PromotionId = promotion.Id;
                model.PromotionName = promotion.Title;
                if (promotionCustomers != null)
                {
                    model.Code = promotionCustomers.Code;
                    model.Value = Convert.ToInt32(promotionCustomers.Value);
                }
            }

            var result = new ControlFormResult<PromotionCustomersModel>(model)
            {
                Title = T("Áp dụng chương trình khuyến mãi"),
                UpdateActionName = "Update",
                FormMethod = FormMethod.Post,
                SubmitButtonText = T("Lưu lại"),
                ShowBoxHeader = false,
                CancelButtonText = T("Trở về"),
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.MakeReadOnlyProperty(x => x.Code);
            result.MakeReadOnlyProperty(x => x.PromotionName);
            if (promotionCustomers != null)
            {
                result.MakeReadOnlyProperty(x => x.Value);
            }

            result.RegisterExternalDataSource(x => x.CustomerIds, y => BindCustomers(promotionId));
            result.AddAction().HasText(T("Gửi thông báo")).HasButtonStyle(ButtonStyle.Info).HasUrl("javascript: void(0);")
                .OnClientClick("$.ajax({ url: '" + Url.Action("Send", "AdminPromotionCustomers") + "', data: {\"promotionId\": " + promotionId + "}, type: 'POST', dataType: 'json', success: function (result) { alert(result.Data);}});");

            var result2 = new ControlGridFormResult<PromotionCustomerInfo>
            {
                Title = T("Khách hàng được khuyến mãi"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetPromotionCustomers,
                DefaultPageSize = WorkContext.DefaultPageSize,
                EnablePaginate = true,
                UpdateActionName = "Update",
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml,
                ClientId = TableName,
                ActionsColumnWidth = 100
            };

            result2.AddColumn(x => x.CustomerCode, T("Mã KH"));
            result2.AddColumn(x => x.FullName, T("Họ và Tên"));
            result2.AddColumn(x => x.Code, T("Mã KM"));
            result2.AddColumn(x => x.Value, T("Giá trị(VIPXU)"));
            result2.AddColumn(x => x.Description, T("Thông báo"));
            result2.AddColumn(x => x.IsUsed)
                .HasHeaderText(T("Sử dụng"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage();
            result2.AddColumn(x => x.IsSendMessages)
                .HasHeaderText(T("Gửi TB"))
                .AlignCenter()
                .HasWidth(100)
                .RenderAsStatusImage();

            result2.AddRowAction(true)
                .HasText(T("Xóa"))
                .HasName("Delete")
                .HasValue(x => x.Id)
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result2.AddCustomVar(Extensions.Constants.Id, promotionId);
            result2.AddReloadEvent("DELETE_ENTITY_COMPLETE");

            return new ControlFormsResult(result, result2);
        }

        [HttpPost, ValidateInput(false)]
        [Url("admin/promotion-customer/send")]
        public ActionResult Send()
        {
            var redirect = new DataViewerModel();
            var promotionId = Request.Form["promotionId"];
            if (string.IsNullOrEmpty(promotionId))
            {
                redirect.Status = true;
                redirect.Data = "Không tìm thấy ID đợt khuyến mãi.";
                return Json(redirect);
            }
            var id = int.Parse(promotionId);
            var promotion = WorkContext.Resolve<IPromotionService>().GetById(id);
            var customerHistoriesService = WorkContext.Resolve<ICustomerHistoriesService>();
            var service = WorkContext.Resolve<IPromotionCustomersService>();
            var listPromotionCustomers = service.GetByPromotion(id);
            foreach (var item in listPromotionCustomers)
            {
                if (item.IsSendMessages)
                {
                    continue;
                }

                var historyCustomer = new CustomerHistoriesInfo
                {
                    Type = (int)CustomerLogType.NapVipLogs,
                    CustomerId = item.CustomerId,
                    CreateDate = DateTime.Now,
                    Action = item.Title,
                    Description = string.Format("Bạn nhận được mã khuyến mãi {0} từ website VIPHD.VN. Vui lòng đăng nhập để kích hoạt khuyến mãi. Thời gian từ ngày {1} đến hết ngày {2}. Xin cảm ơn.",
                            item.Code,
                            promotion.FromDate.ToString(Extensions.Constants.DateTimeFomat),
                            promotion.ToDate.ToString(Extensions.Constants.DateTimeFomat)),
                    Status = (int)Status.Approved,
                    TransactionCode = item.Code
                };
                customerHistoriesService.Insert(historyCustomer);
                item.IsSendMessages = true;
                item.SendDate = DateTime.Now;
                service.Update(item);
            }
            redirect.Status = true;
            redirect.Data = "Đã gửi thông báo tới tất cả khách hàng có trong đợt khuyến mãi này.";

            return Json(redirect);
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/promotion-customer/update")]
        public ActionResult Update(PromotionCustomersModel model)
        {
            if (!ModelState.IsValid)
            {
                return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var service = WorkContext.Resolve<IPromotionCustomersService>();
            var customerService = WorkContext.Resolve<ICustomerService>();
            var promotion = WorkContext.Resolve<IPromotionService>().GetById(model.PromotionId);

            var listCustomerIds = model.CustomerIds;
            if (listCustomerIds.Contains(0))
            {
                var items = customerService.GetPromotions(model.PromotionId);
                listCustomerIds = items.Select(x => x.Id).ToArray();
            }

            for (int i = 0; i < listCustomerIds.Length; i++)
            {
                var customerId = listCustomerIds[i];
                var customer = customerService.GetById(customerId);
                var promotionCustomers = service.GetCode(promotion.Id, customer.Id);
                if (promotionCustomers != null && customerId != 0)
                {
                    continue;
                }

                var entity = new PromotionCustomerInfo
                {
                    PromotionId = model.PromotionId,
                    CustomerId = customer.Id,
                    CustomerCode = customer.CustomerCode,
                    CreateDate = DateTime.Now,
                    Code = model.Code,
                    Value = model.Value.ToString(),
                    Description = string.Format("Bạn nhận được mã khuyến mãi {0} từ website VIPHD.VN. Vui lòng đăng nhập để kích hoạt khuyến mãi. Thời gian từ ngày {1} đến hết ngày {2}. Xin cảm ơn.",
                        model.Code, promotion.FromDate.ToString(Extensions.Constants.DateTimeFomat), promotion.ToDate.ToString(Extensions.Constants.DateTimeFomat)),
                    IsUsed = false,
                    UsedDate = Utilities.DateNull(),
                    IsSendMessages = false,
                    SendDate = Utilities.DateNull()
                };

                service.Insert(entity);
            }

            return new AjaxResult()
                .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"))
                .Redirect(Url.Action("Index", new { @promotionId = model.PromotionId }));
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<IPromotionCustomersService>();
            var item = service.GetById(id);
            if (item.IsUsed)
            {
                return new AjaxResult().Alert("Dữ liệu này đã sử dụng bạn không thể xóa.");
            }
            service.Delete(item);
            return new AjaxResult()
                .NotifyMessage("DELETE_ENTITY_COMPLETE")
                .Redirect(Url.Action("Index", new { @promotionId = item.PromotionId }));
        }

        private ControlGridAjaxData<PromotionCustomerInfo> GetPromotionCustomers(ControlGridFormRequest options)
        {
            var promotionId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.Id]))
            {
                promotionId = Convert.ToInt32(Request.Form[Extensions.Constants.Id]);
            }

            var items = WorkContext.Resolve<IPromotionCustomersService>().GetByPromotion(promotionId);
            var result = new ControlGridAjaxData<PromotionCustomerInfo>(items);

            return result;
        }

        private IEnumerable<SelectListItem> BindCustomers(int promotionId)
        {
            var service = WorkContext.Resolve<ICustomerService>();
            var items = service.GetPromotions(promotionId);
            var result = new List<SelectListItem>();
            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.FullName,
                Value = item.Id.ToString()
            }));
            result.Insert(0, new SelectListItem {Text = "--- Áp dụng cho tất cả khách hàng ---", Value = "0"});

            return result;
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Extensions;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;

namespace CMSSolutions.Websites.Services
{
    public class APISmsService : DataContexService
    {
        public string Amount(string shortCode, out int totalDate, out DateTime? startDate, out DateTime? endDate)
        {
            startDate = Utilities.DateNull();
            endDate = Utilities.DateNull();
            totalDate = 0;
            string amount = "0";
            var code = EnumExtensions.Parse<ShortCode>(shortCode);
            switch (code)
            {
                case ShortCode.DauSo8076:
                    amount = "500";
                    break;
                case ShortCode.DauSo8176:
                    amount = "1000";
                    break;
                case ShortCode.DauSo8276:
                    amount = "2000";
                    break;
                case ShortCode.DauSo8376:
                    amount = "3000";
                    break;
                case ShortCode.DauSo8476:
                    amount = "4000";
                    break;
                case ShortCode.DauSo8576:
                    startDate = DateTime.Now;
                    endDate = DateTime.Now.AddDays(1);
                    totalDate = 1;
                    amount = "5000";
                    break;
                case ShortCode.DauSo8676:
                    startDate = DateTime.Now;
                    endDate = DateTime.Now.AddDays(3);
                    totalDate = 3;
                    amount = "10000";
                    break;
                case ShortCode.DauSo8776:
                    startDate = DateTime.Now;
                    endDate = DateTime.Now.AddDays(5);
                    totalDate = 5;
                    amount = "15000";
                    break;
            }

            return amount;
        }

        public CustomerInfo GetByCustomerCode(string customerCode)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@CustomerCode", customerCode),
            };

            return ExecuteReaderRecord<CustomerInfo>("sp_Customers_GetByCustomerCode", list.ToArray());
        }

        public int SmsProcessing(TransactionSmsInfo entity)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@PartnerId", entity.PartnerId),
                AddInputParameter("@MoId", entity.MoId),
                AddInputParameter("@UserId", entity.UserId),
                AddInputParameter("@ShortCode", entity.ShortCode),
                AddInputParameter("@Keyword", entity.Keyword),
                AddInputParameter("@Subkeyword", entity.Subkeyword),
                AddInputParameter("@Content", entity.Content),
                AddInputParameter("@TransDate", entity.TransDate),
                AddInputParameter("@CheckSum", entity.CheckSum),
                AddInputParameter("@Amount", entity.Amount),
                AddInputParameter("@CreateDate", entity.CreateDate),
                AddInputParameter("@Status", entity.Status),
                AddInputParameter("@Type", entity.Type),
                AddInputParameter("@MtId", entity.MtId),
                AddInputParameter("@CustomerCode", entity.CustomerCode),
                AddInputParameter("@TotalDay", entity.TotalDay),
                AddInputParameter("@StartDate", entity.StartDate),
                AddInputParameter("@EndDate", entity.EndDate),
                AddInputParameter("@TransactionCode", entity.TransactionCode),
                AddInputParameter("@IsLock", entity.IsLock)
            };

            return ExecuteNonQuery("sp_TransactionSms_SmsProcessing", list.ToArray());
        }

        public int InsertLog(LogInfo entity)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@CreateDate", entity.CreateDate),
                AddInputParameter("@Type", entity.Type),
                AddInputParameter("@Messages", entity.Messages),
                AddInputParameter("@Keyword", entity.Keyword),
                AddInputParameter("@Contents", entity.Contents),
                AddInputParameter("@Status", entity.Status)
            };

            return ExecuteNonQuery("sp_Logs_Insert", list.ToArray());
        }
    }
}<file_sep>﻿using System.Collections.Generic;
using System.Data;
using System.Web.Mvc;
using System.Xml;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminVastXmlController : BaseAdminController
    {
        public AdminVastXmlController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor)
        {

        }

        [Url("admin/vast/xml")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý nhóm quảng cáo"), Url = Url.Action("Index","AdminAdvertisementGroup") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Tạo vast xml"), Url = "#" });

            var model = new VastXmlModel();
            var result = new ControlFormResult<VastXmlModel>(model)
            {
                Title = T("Tạo vast xml"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Tạo Xml"),
                CancelButtonText = T("Trở về"),
                CancelButtonUrl = Url.Action("Index", "AdminAdvertisementGroup"),
                ShowBoxHeader = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.MakeReadOnlyProperty(x => x.Messages);

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/vast/xml/create")]
        public ActionResult Update(VastXmlModel model)
        {
            var service = WorkContext.Resolve<IAdvertisementGroupService>();
            var list = service.GetGroupGenerateXml(WorkContext.CurrentCulture);
            var data = service.GetDataGenerateXml(WorkContext.CurrentCulture).DefaultView;
            if (data.Count > 0)
            {
                foreach (var group in list)
                {
                    data.RowFilter = string.Format("Id IN ({0})", group.AdvertisementIds);
                    var listAds = new List<Ad>();
                    var doc = new XmlDocument();
                    foreach (DataRowView row in data)
                    {
                        var link = row["Link"].ToString();
                        if (link != "/")
                        {
                            continue;
                        }

                        var fileName = row["KeyCode"] + ".xml";
                        link = "/Media/Default/Advertisement/Vast/" + fileName;
                        var item = new Ad
                        {
                            Click = row["Click"].ToString(),
                            Duration = (int)row["Duration"],
                            Id = row["Id"].ToString(),
                            Link = link,
                            Position = (int)row["Position"],
                            Skip = (int)row["Skip"],
                            Type = row["Type"].ToString()
                        };
                        listAds.Add(item);

                        data.RowFilter = string.Format("AdId = {0}", item.Id);
                        foreach (DataRowView vast in data)
                        {
                            var dataVast = new Vast();
                            dataVast.ItemAds = new Ads
                            {
                                Id = int.Parse(item.Id),
                                ObjectInLine = new InLine
                                {
                                    ObjectAdSystem = new AdSystem
                                    {
                                        Version = vast["AdSystemVersion"].ToString(),
                                        Value = vast["AdSystemValue"].ToString()
                                    },
                                    AdTitle = vast["AdTitle"].ToString(),
                                    Error = vast["LinkError"].ToString(),
                                    Impression = vast["LinkImpression"].ToString(),
                                    Creatives = new Creatives
                                    {
                                        ListCreatives = new Creative[]
                                    {
                                        new Creative
                                        {
                                            ObjectLinear = new Linear
                                            {
                                                Skipoffset = vast["Skipoffset"].ToString(),
                                                Duration = vast["Duration"].ToString(),
                                                VideoClicks = new VideoClicks
                                                {
                                                    ClickThrough = vast["LinkClickThrough"].ToString()
                                                },
                                                TrackingEvents = new TrackingEvents
                                                {
                                                    LisTrackings = new Tracking[]
                                                    {
                                                        new Tracking { Event = vast["TrackingEvent1"].ToString(), Value = vast["TrackingValue1"].ToString()},
                                                        new Tracking { Event = vast["TrackingEvent2"].ToString(), Value = vast["TrackingValue2"].ToString()},
                                                        new Tracking { Event = vast["TrackingEvent3"].ToString(), Value = vast["TrackingValue3"].ToString()},
                                                        new Tracking { Event = vast["TrackingEvent4"].ToString(), Value = vast["TrackingValue4"].ToString()},
                                                        new Tracking { Event = vast["TrackingEvent5"].ToString(), Value = vast["TrackingValue5"].ToString()},
                                                        new Tracking { Event = vast["TrackingEvent6"].ToString(), Value = vast["TrackingValue6"].ToString()}
                                                    }
                                                },
                                                MediaFiles = new MediaFiles
                                                {
                                                    ListMediaFiles = new MediaFile[]
                                                    {
                                                        new MediaFile
                                                        {
                                                            Bitrate = (int)vast["MediaFileBitrate"],
                                                            Delivery = vast["MediaFileDelivery"].ToString(),
                                                            Height = (int)vast["MediaFileHeight"],
                                                            Width = (int)vast["MediaFileWidth"],
                                                            MaintainAspectRatio = bool.Parse(vast["MediaFileMaintainAspectRatio"].ToString()),
                                                            Scalable = bool.Parse(vast["MediaFileScalable"].ToString()),
                                                            Type = vast["MediaFileType"].ToString(),
                                                            Value = vast["MediaFileValue"].ToString()
                                                        } 
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    }
                                }
                            };

                            var xml = Utilities.SerializeXml<Vast>(dataVast);
                            doc = new XmlDocument();
                            doc.LoadXml(xml);
                            doc.Save(Server.MapPath(link));
                        }
                    }

                    if (listAds.Count > 0)
                    {
                        var ads = new Vplugin
                        {
                            ListAds = listAds.ToArray()
                        };

                        var name = group.Code + ".xml";
                        var path = "/Media/Default/Advertisement/";

                        var rootXml = Utilities.SerializeXml<Vplugin>(ads);
                        doc = new XmlDocument();
                        doc.LoadXml(rootXml);
                        doc.Save(Server.MapPath(path + name));

                        var obj = service.GetById(group.Id);
                        obj.IsGenerate = true;
                        obj.FolderPath = path;
                        obj.FileName = name;
                        obj.FullPath = path + name;
                        service.Update(obj);
                    }
                }   
            }

            return new AjaxResult()
                .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(string.Format(T("Đã tạo thành công các file vast xml!")));
        }
    }
}
<file_sep>﻿using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface ISiteService : IGenericService<SiteInfo, int>, IDependency
    {

    }

    public class SiteService : GenericService<SiteInfo, int>, ISiteService
    {
        public SiteService(IRepository<SiteInfo, int> repository,
            IEventBus eventBus)
            : base(repository, eventBus)
        {

        }
    }
}
<file_sep>using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;
using CMSSolutions.Websites.Extensions;

namespace CMSSolutions.Websites.Entities
{ 
    [DataContract]
    public class FilmFilesInfo : BaseEntity<long>
    {
        [DataMember]
        [DisplayName("FileCode")]
        public string FileCode { get; set; }

        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }

        [DataMember]
        [DisplayName("SiteId")]
        public int SiteId { get; set; }

        [DataMember]
        [DisplayName("ServerId")]
        public int ServerId { get; set; }

        [NotMapped]
        [DisplayName("ServerName")]
        public string ServerName { get; set; }

        [DataMember]
        [DisplayName("Name")]
        public string Name { get; set; }

        [DataMember]
        [DisplayName("FolderRoot")]
        public string FolderRoot { get; set; }

        [DataMember]
        [DisplayName("FolderName")]
        public string FolderName { get; set; }

        [DataMember]
        [DisplayName("FolderDay")]
        public string FolderDay { get; set; }

        [DataMember]
        [DisplayName("FolderPath")]
        public string FolderPath { get; set; }

        [DataMember]
        [DisplayName("FileName")]
        public string FileName { get; set; }

        [DataMember]
        [DisplayName("Extentions")]
        public string Extentions { get; set; }

        [DataMember]
        [DisplayName("FullPath")]
        public string FullPath { get; set; }

        [DataMember]
        [DisplayName("Size")]
        public string Size { get; set; }

        [DataMember]
        [DisplayName("CreateDate")]
        public System.DateTime CreateDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string DisplayDate { get { return Utilities.DateString(CreateDate); } }

        [DataMember]
        [DisplayName("HasUse")]
        public bool HasUse { get; set; }
    }

    public class FilmFilesMap : EntityTypeConfiguration<FilmFilesInfo>, IEntityTypeConfiguration
    {
        public FilmFilesMap()
        {
            ToTable("Modules_FilmFiles");
            HasKey(m => m.Id);
            Property(m => m.FileCode).IsRequired().HasMaxLength(50);
            Property(m => m.LanguageCode).HasMaxLength(50);
            Property(m => m.Name).IsRequired().HasMaxLength(250);
            Property(m => m.FolderRoot).HasMaxLength(250);
            Property(m => m.FolderName).HasMaxLength(100);
            Property(m => m.FolderPath).IsRequired().HasMaxLength(300);
            Property(m => m.FileName).IsRequired().HasMaxLength(100);
            Property(m => m.Extentions).HasMaxLength(50);
            Property(m => m.FullPath).IsRequired().HasMaxLength(500);
            Property(m => m.CreateDate).IsRequired();
            Property(m => m.HasUse).IsRequired();
            Property(m => m.Size).HasMaxLength(250);
            Property(m => m.ServerId).IsRequired();
            Property(m => m.FolderDay).HasMaxLength(100);
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using CMSSolutions.Extensions;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminSupportController : BaseAdminController
    {
        public AdminSupportController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {
            TableName = "tblSupports";
        }

        [Url("admin/supports")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Hỗ trợ hỏi đáp"), Url = "#" });

            var result = new ControlGridFormResult<SupportInfo>
            {
                Title = T("Hỗ trợ hỏi đáp"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetSupports,
                UpdateActionName = "Update",
                ActionsColumnWidth = 100,
                ClientId = TableName,
                DefaultPageSize = WorkContext.DefaultPageSize,
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml
            };

            result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true);
            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true);

            result.AddColumn(x => x.Title, T("Câu hỏi"));
            result.AddColumn(x => x.Messages, T("Trả lời"));
            result.AddColumn(x => EnumExtensions.GetDisplayName((Status)x.Status), T("Trạng thái"));


            result.AddAction().HasText(T("Thêm mới"))
               .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
               .HasButtonStyle(ButtonStyle.Primary)
               .HasBoxButton(false)
               .HasCssClass(Constants.RowLeft)
               .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildSites(false, string.Empty))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
                .HasText(T("Sửa"))
                .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                .HasButtonStyle(ButtonStyle.Default)
                .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddRowAction(true)
                .HasText(T("Xóa"))
                .HasName("Delete")
                .HasValue(x => x.Id)
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");
            return result;
        }

        private ControlGridAjaxData<SupportInfo> GetSupports(ControlGridFormRequest options)
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var searchText = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText]))
            {
                searchText = Request.Form[Extensions.Constants.SearchText];
            }

            var statusId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId]))
            {
                statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]);
            }

            var total = 0;
            var service = WorkContext.Resolve<ISupportService>();
            service.SiteId = siteId;
            service.LanguageCode = languageCode;
            var items = service.GetPaged(searchText, 0, statusId, options.PageIndex, options.PageSize, out total);
            var result = new ControlGridAjaxData<SupportInfo>(items, total);
            return result;
        }

        [Url("admin/supports/edit/{id}")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Hỗ trợ hỏi đáp"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin hỏi đáp"), Url = "#" });

            var model = new SupportModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<ISupportService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<SupportModel>(model)
            {
                Title = T("Thông tin hỏi đáp"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                CancelButtonText = T("Trở về"),
                ShowBoxHeader = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages());
            result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage"));
            result.RegisterCascadingDropDownDataSource(x => x.ParentId, Url.Action("GetSupportBySite"));
            result.RegisterExternalDataSource(x => x.Status, y => BindStatus());

            result.AddAction().HasText(T("Làm mới"))
                .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
                .HasCssClass("btn btn-success");

            return result;
        }

        [Url("admin/supports/get--support-by-site")]
        public ActionResult GetSupportBySite()
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var service = WorkContext.Resolve<ISupportService>();
            service.LanguageCode = languageCode;
            service.SiteId = siteId;
            var items = service.GetRecords(x=> x.SiteId == siteId && x.LanguageCode == languageCode && x.IsGroup).ToList();
            var result = new List<SelectListItem>();

            result.AddRange(items.Select(item => new SelectListItem
            {
                Text = item.Title,
                Value = item.Id.ToString()
            }));

            result.Insert(0, new SelectListItem { Text = T("--- Không chọn ---"), Value = "0" });

            return Json(result);
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/supports/update")]
        public ActionResult Update(SupportModel model)
        {
            if (!ModelState.IsValid)
            {
                return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var service = WorkContext.Resolve<ISupportService>();
            SupportInfo item = model.Id == 0 ? new SupportInfo() : service.GetById(model.Id);

            item.LanguageCode = model.LanguageCode;
            item.SiteId = model.SiteId;
            item.ParentId = model.ParentId;
            item.OrderBy = model.OrderBy;
            item.Title = model.Title;
            item.Messages = model.Messages;
            item.IsGroup = model.IsGroup;
            item.Status = model.Status;
            service.Save(item);

            return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"));
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<ISupportService>();
            var item = service.GetById(id);
            service.Delete(item);

            return new AjaxResult()
                .NotifyMessage("DELETE_ENTITY_COMPLETE")
                .Alert(T("Xóa dữ liệu thành công!"));
        }
    }
}<file_sep>﻿namespace CMSSolutions.Websites.Payments
{
    public class APIBankCardService
    {
        public string SenderKey
        {
            get { return System.Configuration.ConfigurationManager.AppSettings["SenderKey"]; }
        }

        public string ReceiverKey
        {
            get { return System.Configuration.ConfigurationManager.AppSettings["ReceiverKey"]; }
        }

        public string MerchantId = "88000072";
        public string ReponseUrl { get; set; }
    }
}<file_sep>﻿using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using CMSSolutions.Websites.Extensions;

namespace CMSSolutions.Websites.Payments
{
    public class APISms
    {
        public string PartnerId = ConfigurationManager.AppSettings["PartnerId"];
        public string Password = ConfigurationManager.AppSettings["PartnerPassword"];
        public string UrlSMSMT = ConfigurationManager.AppSettings["UrlSMSMT"];

        public string Md5(string source_str)
        {
            MD5 encrypter = new MD5CryptoServiceProvider();
            Byte[] original_bytes = ASCIIEncoding.Default.GetBytes(source_str);
            Byte[] encoded_bytes = encrypter.ComputeHash(original_bytes);
            return BitConverter.ToString(encoded_bytes).Replace("-", "").ToLower();
        }

        public int SentMT(string moid, string shortcode, 
            string keyword, string mobinumber, string contentmt, ref string url_)
        {
            url_ = CreatUrlMT(moid, shortcode, keyword, mobinumber, HttpUtility.UrlEncode(contentmt));
            LogFiles.WriteLogSms(string.Format("MT URL: {0}", url_));
            return SendRequest(url_);

        }

        private string CreatUrlMT(string moid, 
            string shortcode, string keyword, string mobinumber, string contentmt)
        {
            var mtid = CreateMTId();
            var transdate = DateTime.Now.ToString("yyyyMMddHHmmss");
            string and = "&";
            string url_ = UrlSMSMT;
            url_ += "partnerid=" + PartnerId + and;
            url_ += "moid=" + moid + and;
            url_ += "mtid=" + mtid + and;
            url_ += "userid=" + mobinumber + and;
            url_ += "shortcode=" + shortcode + and;
            url_ += "keyword=" + keyword + and;
            url_ += "content=" + contentmt + and;
            url_ += "messagetype=1" + and;
            url_ += "totalmessage=1" + and;
            url_ += "messageindex=1" + and;
            url_ += "ismore=0" + and;
            url_ += "contenttype=0" + and;
            url_ += "transdate=" + transdate + and;
            string checkSum = CreateCheckSumMT(transdate, contentmt, keyword, shortcode, moid, mtid);
            url_ += "checksum=" + checkSum;

            return url_;
        }

        public string CreateMTId()
        {
            var ran = new Random();
            string kqran = ran.Next(0, 99999).ToString();
            return PartnerId + DateTime.Now.ToString("yyyyMMddHHmmss") + kqran;
        }

        public string CreateCheckSumMT(string transdate, string Content, 
            string Keyword, string ShortCode, string MoId, string mtId)
        {
            return Md5(mtId + MoId + ShortCode + Keyword + Content + transdate + Password);
        }

        public int SendRequest(string url)
        {
            try
            {
                var myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "GET";
                WebResponse myResponse = myRequest.GetResponse();
                var sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
                string result = sr.ReadToEnd();
                sr.Close();
                myResponse.Close();
                string[] s = result.Split('=');
                LogFiles.WriteLogSms(string.Format("MT: RESULT {0}", result));
                if (result == "requeststatus=200")
                {
                    return 200;
                }

                if (result == "requeststatus=17")
                {
                    return 17;
                }
                LogFiles.WriteLogSms(string.Format("MT: SEND {0}", result));
                return int.Parse(s[1]);

            }
            catch (Exception ex)
            {
                LogFiles.WriteLogSms(string.Format("MT: SEND ERROR {0}", ex.InnerException.Message));
                throw ex;
            }
        }
    }
}<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class CardTypeModel
    {
        [ControlHidden()]
        public int Id { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Mã loại thẻ", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public string Code { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Tên loại thẻ", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public string Name { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Có serial", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)]
        public bool HasSerial { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 3)]
        public int Status { get; set; }
        
        public static implicit operator CardTypeModel(CardTypeInfo entity)
        {
            return new CardTypeModel
            {
                Id = entity.Id,
                Code = entity.Code,
                Name = entity.Name,
                HasSerial = entity.HasSerial,
                Status = entity.Status
            };
        }
    }
}
<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class SmsMessageModel
    {
        [ControlHidden]
        public int Id { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public string LanguageCode { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Mã", PlaceHolder = "Tối đa 50 ký tự", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)]
        public string Code { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Thông báo", PlaceHolder = "Tối đa 250 ký tự", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)]
        public string Messages { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Loại tin", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public bool IsEvent { get; set; }

        public static implicit operator SmsMessageModel(SmsMessageInfo entity)
        {
            return new SmsMessageModel
            {
                Id = entity.Id,
                LanguageCode = entity.LanguageCode,
                Code = entity.Code,
                Messages = entity.Message,
                IsEvent = entity.IsEvent
            };
        }
    }
}<file_sep>﻿using System;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class PromotionModel
    {
        public PromotionModel()
        {
            FromDate = DateTime.Now.Date;
            ToDate = DateTime.Now.AddMonths(1).Date;
        }

        [ControlHidden]
        public int Id { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Tiêu đề", PlaceHolder = "Tối đa 250 ký tự", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 0)]
        public string Title { get; set; }

        [ControlText(LabelText = "Nội dung thông báo", Required = true, Type = ControlText.RichText, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)]
        public string Contents { get; set; }

        [ControlDatePicker(LabelText = "Ngày bắt đầu", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)]
        public DateTime FromDate { get; set; }

        [ControlDatePicker(LabelText = "Ngày kết thúc", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)]
        public DateTime ToDate { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)]
        public int Status { get; set; }

        public static implicit operator PromotionModel(PromotionInfo entity)
        {
            return new PromotionModel
            {
                Id = entity.Id,
                Title = entity.Title,
                Contents = entity.Contents,
                FromDate = entity.FromDate,
                ToDate = entity.ToDate,
                Status = entity.Status
            };
        }
    }
}<file_sep>﻿using System;
using System.Globalization;
using System.Web.Mvc;
using CMSSolutions.Extensions;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminEpisodeController : BaseAdminController
    {
        public AdminEpisodeController(IWorkContextAccessor workContextAccessor) : 
                base(workContextAccessor)
        {
            TableName = "tblEpisodes";
        }

        [Url("admin/episodes")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý các tập phim"), Url = "#" });

            var result = new ControlGridFormResult<EpisodeInfo>
            {
                Title = T("Quản lý các tập phim"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetEpisodes,
                DefaultPageSize = WorkContext.DefaultPageSize,
                EnablePaginate = true,
                UpdateActionName = "Update",
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml,
                ClientId = TableName,
                ActionsColumnWidth = 100
            };

            result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true);
            result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true);

            result.AddColumn(x => x.EpisodeName, T("Tên tập phim"));
            result.AddColumn(x => x.OrderBy, T("Thứ tự")).AlignCenter().HasWidth(150);
            result.AddColumn(x => EnumExtensions.GetDisplayName((Status)x.Status), T("Trạng thái"));

            result.AddAction().HasText(T("Thêm mới"))
                .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
                .HasButtonStyle(ButtonStyle.Primary)
                .HasBoxButton(false)
                .HasRow(false)
                .HasCssClass(Constants.RowLeft)
                .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildSites(false, string.Empty))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3);

            result.AddRowAction()
                .HasText(T("Sửa"))
                .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
                .HasButtonStyle(ButtonStyle.Default)
                .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddRowAction(true)
                .HasText(T("Xóa"))
                .HasName("Delete")
                .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString()))
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");
            return result;
        }

        private ControlGridAjaxData<EpisodeInfo> GetEpisodes(ControlGridFormRequest options)
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var searchText = string.Empty;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText]))
            {
                searchText = Request.Form[Extensions.Constants.SearchText];
            }

            var statusId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId]))
            {
                statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]);
            }

            int totals;
            var items = WorkContext.Resolve<IEpisodesService>().GetPaged(languageCode, siteId, searchText, statusId, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<EpisodeInfo>(items, totals);

            return result;
        }

        [Url("admin/episodes/edit/{id}")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý các tập phim"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin các tập phim"), Url = "#" });

            var model = new EpisodeModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<IEpisodesService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<EpisodeModel>(model)
            {
                Title = T("Thông tin các tập phim"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                CancelButtonText = T("Đóng"),
                ShowBoxHeader = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages());
            result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage"));
            result.RegisterExternalDataSource(x => x.Status, y => BindStatus());

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/episodes/update")]
        public ActionResult Update(EpisodeModel model)
        {
            if (!ModelState.IsValid)
            {
				return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var service = WorkContext.Resolve<IEpisodesService>();
            EpisodeInfo item = model.Id == 0 ? new EpisodeInfo() : service.GetById(model.Id);

            if (service.CheckExist(model.Id, model.EpisodeName))
            {
                return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Tên tập phim đã tồn tại."));
            }

            item.LanguageCode = model.LanguageCode;
            item.SiteId = model.SiteId;
            item.EpisodeName = model.EpisodeName;
            item.OrderBy = model.OrderBy;
            item.Description = model.Description;
            item.Status = model.Status;
            service.Save(item);

            return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"));
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<IEpisodesService>();
            var item = service.GetById(id);
            item.Status = (int)Status.Deleted;
            service.Update(item);

            return new AjaxResult()
                .NotifyMessage("DELETE_ENTITY_COMPLETE")
                .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!"));
        }
    }
}
<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;

namespace CMSSolutions.Websites.Models
{
    public class ActorModel
    {
        [ControlHidden]
        public int Id { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "<NAME>", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 0)]
        public string FullName { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)]
        public int Status { get; set; }

        [ControlText(Type = ControlText.MultiText, Rows = 3, MaxLength = 2000, LabelText = "Giới thiệu", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 2)]
        public string Description { get; set; }

        public static implicit operator ActorModel(ActorInfo entity)
        {
            return new ActorModel
            {
                Id = entity.Id,
                FullName = entity.FullName,
                Description = entity.Description,
                Status = entity.Status
            };
        }
    }
}
<file_sep>﻿using System;
using System.Text;
using System.Web.Mvc;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Routing;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminVastController : BaseAdminController
    {
        public AdminVastController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor)
        {
            TableName = "tblVast";
        }

        [Url("admin/vast")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý vast"), Url = "#" });

            var result = new ControlGridFormResult<VastInfo>
            {
                Title = T("Quản lý vast"),
                CssClass = "table table-bordered table-striped",
                IsAjaxSupported = true,
                FetchAjaxSource = GetVast,
                UpdateActionName = "Update",
                ActionsColumnWidth = 100,
                ClientId = TableName,
                EnablePaginate = true,
                DefaultPageSize = WorkContext.DefaultPageSize,
                GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml,
                GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml
            };

            result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true);
            result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true);
            result.AddCustomVar(Extensions.Constants.AdId, "$('#" + Extensions.Constants.AdId + "').val();", true);

            result.AddColumn(x => x.KeyCode, T("Mã Vast"));
            result.AddColumn(x => x.AdTitle, T("Tiêu đề"));
            result.AddColumn(x => x.AdName, T("Tên quảng cáo"));
            result.AddColumn(x => x.MediaFileValue, T("Đường dẫn file"));
            result.AddColumn(x => x.MediaFileType, T("Loại file"));

            result.AddAction().HasText(T("Thêm mới"))
              .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 })))
              .HasButtonStyle(ButtonStyle.Primary)
              .HasBoxButton(false)
              .HasCssClass(Constants.RowLeft)
              .HasRow(true);

            result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(() => BuildSiteAds(true, Extensions.Constants.AdId))).HasParentClass(Constants.ContainerCssClassCol3);
            result.AddAction(new ControlFormHtmlAction(BuildAds)).HasParentClass(Constants.ContainerCssClassCol3).HasRow(true);
            
            result.AddRowAction()
               .HasText(T("Sửa"))
               .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id })))
               .HasButtonStyle(ButtonStyle.Default)
               .HasButtonSize(ButtonSize.ExtraSmall);

            result.AddRowAction(true)
                .HasText(T("Xóa"))
                .HasName("Delete")
                .HasValue(x => x.Id)
                .HasButtonStyle(ButtonStyle.Danger)
                .HasButtonSize(ButtonSize.ExtraSmall)
                .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text);

            result.AddReloadEvent("UPDATE_ENTITY_COMPLETE");
            result.AddReloadEvent("DELETE_ENTITY_COMPLETE");

            return result;
        }

        private string BuildAds()
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var service = WorkContext.Resolve<IAdvertisementService>();
            var sb = new StringBuilder();
            sb.AppendFormat(T("Chuyên mục") + " <select id=\"" + Extensions.Constants.CategoryId + "\" name=\"" + Extensions.Constants.CategoryId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">");
            var list = service.GetRecords(x => x.LanguageCode == languageCode && x.SiteId == siteId);
            foreach (var cate in list)
            {
                sb.AppendFormat("<option value=\"{1}\">{0}</option>", cate.Title, cate.Id);
            }

            sb.Append("</select>");

            return sb.ToString();
        }

        private ControlGridAjaxData<VastInfo> GetVast(ControlGridFormRequest options)
        {
            var languageCode = WorkContext.CurrentCulture;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode]))
            {
                languageCode = Request.Form[Extensions.Constants.LanguageCode];
            }

            var siteId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId]))
            {
                siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]);
            }

            var adId = 0;
            if (Utilities.IsNotNull(Request.Form[Extensions.Constants.AdId]))
            {
                adId = Convert.ToInt32(Request.Form[Extensions.Constants.AdId]);
            }

            int totals;
            var items = WorkContext.Resolve<IVastService>().SearchPaged(languageCode, siteId, adId, options.PageIndex, options.PageSize, out totals);
            var result = new ControlGridAjaxData<VastInfo>(items, totals);

            return result;
        }

        [Url("admin/vast/edit/{id}")]
        public ActionResult Edit(int id)
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý vast"), Url = Url.Action("Index") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin vast"), Url = "#" });

            var model = new VastModel();
            if (id > 0)
            {
                var service = WorkContext.Resolve<IVastService>();
                model = service.GetById(id);
            }

            var result = new ControlFormResult<VastModel>(model)
            {
                Title = T("Thông tin vast"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Lưu lại"),
                ShowCancelButton = true,
                ShowBoxHeader = false,
                CancelButtonText = T("Đóng"),
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };

            result.MakeReadOnlyProperty(x => x.KeyCode);
            result.MakeReadOnlyProperty(x => x.AdSystemVersion);
            result.MakeReadOnlyProperty(x => x.MediaFileDelivery);
            result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages());
            result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage"));
            result.RegisterCascadingDropDownDataSource(x => x.AdId, Url.Action("GetAdBySite"));

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/vast/update")]
        public ActionResult Update(VastModel model)
        {
            if (!ModelState.IsValid)
            {
                return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            var service = WorkContext.Resolve<IVastService>();
            VastInfo item = model.Id == 0 ? new VastInfo() : service.GetById(model.Id);

            item.LanguageCode = model.LanguageCode;
            item.SiteId = model.SiteId;
            item.KeyCode = model.KeyCode;
            item.AdId = model.AdId;
            item.AdSystemVersion = model.AdSystemVersion;
            item.AdSystemValue = model.AdSystemValue;
            item.AdTitle = model.AdTitle;
            item.LinkError = model.LinkError;
            item.LinkImpression = model.LinkImpression;
            item.Skipoffset = model.Skipoffset;
            item.Duration = model.Duration;
            item.LinkClickThrough = model.LinkClickThrough;
            item.TrackingEvent1 = "start";
            item.TrackingValue1 = model.TrackingValue1;
            item.TrackingEvent2 = "firstQuartile";
            item.TrackingValue2 = model.TrackingValue2;
            item.TrackingEvent3 = "midpoint";
            item.TrackingValue3 = model.TrackingValue3;
            item.TrackingEvent4 = "thirdQuartile";
            item.TrackingValue4 = model.TrackingValue4;
            item.TrackingEvent5 = "complete";
            item.TrackingValue5 = model.TrackingValue5;
            item.TrackingEvent6 = "creativeView";
            item.TrackingValue6 = model.TrackingValue6;
            item.MediaFileBitrate = model.MediaFileBitrate;
            item.MediaFileDelivery = model.MediaFileDelivery;
            item.MediaFileHeight = model.MediaFileHeight;
            item.MediaFileWidth = model.MediaFileWidth;
            item.MediaFileMaintainAspectRatio = model.MediaFileMaintainAspectRatio;
            item.MediaFileScalable = model.MediaFileScalable;
            item.MediaFileType = model.MediaFileType;
            item.MediaFileValue = model.MediaFileValue;
            service.Save(item);

            return new AjaxResult()
                .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(T("Cập nhật thành công!"))
                .CloseModalDialog();
        }

        [FormButton("Delete")]
        [HttpPost, ActionName("Update")]
        public ActionResult Delete(int id)
        {
            var service = WorkContext.Resolve<IVastService>();
            var item = service.GetById(id);
            service.Delete(item);

            return new AjaxResult()
                .NotifyMessage("DELETE_ENTITY_COMPLETE")
                .Alert(T("Dữ liệu đã xóa khỏi hệ thống!"));
        }
    }
}
<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class EpisodeModel
    {
        [ControlHidden]
        public int Id { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public string LanguageCode { get; set; }

        [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public int SiteId { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 50, LabelText = "Tên tập phim", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)]
        public string EpisodeName { get; set; }

        [ControlNumeric(LabelText = "Thư tự", Required = true, MaxLength = 15, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 3)]
        public int OrderBy { get; set; }

        [ControlChoice(ControlChoice.DropDownList, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 4)]
        public int Status { get; set; }

        [ControlText(Type = ControlText.MultiText, Rows = 2, MaxLength = 2000, LabelText = "Giới thiệu", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 5)]
        public string Description { get; set; }

        public static implicit operator EpisodeModel(EpisodeInfo entity)
        {
            return new EpisodeModel
            {
                Id = entity.Id,
                LanguageCode = entity.LanguageCode,
                SiteId = entity.SiteId,
                EpisodeName = entity.EpisodeName,
                OrderBy = entity.OrderBy,
                Description = entity.Description,
                Status = entity.Status
            };
        }

    }
}
<file_sep>﻿using System.Collections.Generic;
using System.Web.Mvc;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class DataViewCategoryModel
    {
        public int Type { get; set; }

        public string Title { get; set; }

        public string TextNext { get; set; }

        public string UrlNext { get; set; }

        public string SliderName { get; set; }

        public int PageIndex { get; set; }

        public int PageSize { get; set; }

        public int TotalRow { get; set; }

        public int TotalPage
        {
            get
            {
                if (TotalRow <= PageSize)
                {
                    return 1;
                }

                var count = TotalRow % PageSize;
                if ((count == 0))
                {
                    return TotalRow / PageSize;
                }

                return ((TotalRow - count) / PageSize) + 1;
            }
        }

        public string HtmlData { get; set; }

        public string HtmlFilmHot { get; set; }

        public string HtmlFilmRetail { get; set; }

        public string HtmlFilmLengthEpisodes { get; set; }

        public string HtmlFilmJJChannelIntroduce { get; set; }

        public string HtmlFilmTheater { get; set; }

        public string HtmlTVShow { get; set; }

        public string HtmlClip { get; set; }

        public string Data { get; set; }

        public string Breadcrumb { get; set; }

        public CategoryInfo CurrentCategory { get; set; }

        public List<FilmTypesInfo> ListFilmTypes { get; set; }

        public int SelectedFilmTypes { get; set; }

        public List<CountryInfo> ListCountries { get; set; }

        public int SelectedCountry { get; set; }

        public List<SelectListItem> SearchOrderBy { get; set; }

        public string SelectedOrderBy { get; set; }

        public int SelectedSortBy { get; set; }

        public IList<FilmInfo> ListFilms { get; set; }

        public ArticlesInfo News { get; set; }

        public IList<SupportInfo> ListSupportParents { get; set; }

        public IList<SupportInfo> ListSupportChildren { get; set; }

        public IList<ArticlesInfo> ListArticles { get; set; }

        public string Keyword { get; set; }

        public IList<SearchInfo> ListSearchFilms { get; set; }

        public IList<SearchInfo> ListSearchClip { get; set; }

        public IList<SearchInfo> ListSearchShow { get; set; }

        public IList<SearchInfo> ListSearchTrailer { get; set; }

        public FilmInfo FilmDetails { get; set; }
    }
}<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class VIPCardModel
    {
        public VIPCardModel()
        {
            VIPValue = 0;
        }

        [ControlHidden]
        public int Id { get; set; }

        [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.ServerId + "').empty();")]
        public string LanguageCode { get; set; }

        [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 1)]
        public int SiteId { get; set; }

        [ControlCascadingDropDown(LabelText = "Máy chủ", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 2)]
        public int ServerId { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Mã thẻ VIP", PlaceHolder = "Tối đa 50 ký tự", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 3)]
        public string VIPCode { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Tên thẻ VIP", PlaceHolder = "Tối đa 250 ký tự", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 4)]
        public string VIPName { get; set; }

        [ControlNumeric(LabelText = "Định mức giá trị thẻ VIP", Required = true, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 5)]
        public decimal VIPValue { get; set; }

        public static implicit operator VIPCardModel(VIPCardInfo entity)
        {
            return new VIPCardModel
            {
                Id = entity.Id,
                LanguageCode = entity.LanguageCode,
                SiteId = entity.SiteId,
                ServerId = entity.ServerId,
                VIPCode =  entity.VIPCode,
                VIPName = entity.VIPName,
                VIPValue = entity.VIPValue
            };
        }
    }
}
<file_sep>using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IVIPCardService : IGenericService<VIPCardInfo, int>, IDependency
    {
        bool CheckVipCode(int id, string vipCode);

        List<VIPCardInfo> SearchPaged(
            string searchText,
            string languageCode,
            int siteId,
            int serverId,
            int pageIndex,
            int pageSize,
            out int totalRecord);
    }

    public class VIPCardService : GenericService<VIPCardInfo, int>, IVIPCardService
    {
        public VIPCardService(IRepository<VIPCardInfo, int> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public bool CheckVipCode(int id, string vipCode)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@VIPCode", vipCode),
                AddInputParameter("@Id", id)
            };

            var result = (int)ExecuteReaderResult("sp_VIPCards_CheckAlias", list.ToArray());
            return result > 0;
        }

        public List<VIPCardInfo> SearchPaged(string searchText, string languageCode, int siteId, int serverId, int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@LanguageCode", languageCode),
                AddInputParameter("@SiteId", siteId),
                AddInputParameter("@ServerId", serverId),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<VIPCardInfo>("sp_VIPCards_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }
    }
}
<file_sep>﻿using System.Collections.Generic;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class PaymentModel
    {
        public List<BankCardInfo> ListBankCards { get; set; }

        public List<CardTypeInfo> ListCardTypes { get; set; }

        public string CustomerCode { get; set; }

        public string CustomerName { get; set; }

        public string VipXu { get; set; }

        public string Messages { get; set; }

        public string Amount { get; set; }

        public bool Status { get; set; }

        public string Url { get; set; }

        public int PageName { get; set; }

        public List<NapVipCustomerLogs> CustomerNapVipHistories { get; set; }

        public List<TransactioCustomerLogs> CustomerDoiXuHistories { get; set; }
    }
}<file_sep>﻿using System.Configuration;
using Microsoft.Web.WebPages.OAuth;

namespace CMSSolutions.Websites.Extensions
{
    public static class AuthConfig
    {
        public static string FacebookAppId = ConfigurationManager.AppSettings["FacebookAppId"];
        public static string FacebookAppSecret = ConfigurationManager.AppSettings["FacebookAppSecret"];

        public static string GoogleAppId = ConfigurationManager.AppSettings["GoogleAppId"];
        public static string GoogleAppSecret = ConfigurationManager.AppSettings["GoogleAppSecret"];

        public static void RegisterAuth()
        {
            OAuthWebSecurity.RegisterFacebookClient(FacebookAppId, FacebookAppSecret);
            OAuthWebSecurity.RegisterClient(new GoogleClient(GoogleAppId, GoogleAppSecret), "Google", null);
        }
    }
}<file_sep>﻿using System.ComponentModel;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    /// <summary>
    /// Đạo diễn
    /// </summary>
    [DataContract]
    public class DirectorInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("FullName")]
        public string FullName { get; set; }
        
        [DataMember]
        [DisplayName("Description")]
        public string Description { get; set; }
        
        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }
    }
    
    public class DirectorMap : EntityTypeConfiguration<DirectorInfo>, IEntityTypeConfiguration
    {
        
        public DirectorMap()
        {
            ToTable("Modules_Directors");
            HasKey(m => m.Id);
            Property(m => m.FullName).IsRequired().HasMaxLength(250);
            Property(m => m.Description).HasMaxLength(2000);
        }
    }
}
<file_sep>using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface IDirectorService : IGenericService<DirectorInfo, int>, IDependency
    {
        bool CheckExist(int id, string keyword);

        List<DirectorInfo> SearchPaged(
            string searchText,
            int status,
            int pageIndex,
            int pageSize,
            out int totalRecord);
    }

    public class DirectorService : GenericService<DirectorInfo, int>, IDirectorService
    {
        public DirectorService(IRepository<DirectorInfo, int> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public bool CheckExist(int id, string keyword)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Id", id),
                AddInputParameter("@Keyword", keyword)
            };
            var result = (int)ExecuteReaderResult("sp_Directors_CheckName", list.ToArray());

            return result > 0;
        }

        public List<DirectorInfo> SearchPaged(string searchText, int status, int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Keyword", searchText),
                AddInputParameter("@Status", status),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<DirectorInfo>("sp_Directors_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }
    }
}
<file_sep>﻿using CMSSolutions.Web.UI.ControlForms;

namespace CMSSolutions.Websites.Models
{
    public class VastXmlModel
    {
        public VastXmlModel()
        {
            Messages = "Chú ý: Khi bạn click vào nút Tạo Xml hệ thống sẽ tự động tìm tất cả những nhóm quảng cáo nào đã có quảng cáo và có nội dung quảng cáo để tạo thành các file xml theo chuẩn VAST 3.0.";
        }

        [ControlText(Type = ControlText.MultiText, Rows = 3, LabelText = "Ghi chú", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 0)]
        public string Messages { get; set; }
    }
}<file_sep>﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class AdvertisementInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("SiteId")]
        public int SiteId { get; set; }

        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }

        [DataMember]
        [DisplayName("KeyCode")]
        public string KeyCode { get; set; }

        [DataMember]
        [DisplayName("Title")]
        public string Title { get; set; }

        [DataMember]
        [DisplayName("Price")]
        public decimal Price { get; set; }

        [DataMember]
        [DisplayName("Code")]
        public string Code { get; set; }

        [DataMember]
        [DisplayName("Link")]
        public string Link { get; set; }

        [DataMember]
        [DisplayName("Type")]
        public string Type { get; set; }

        [DataMember]
        [DisplayName("Click")]
        public string Click { get; set; }

        [DataMember]
        [DisplayName("Duration")]
        public int Duration { get; set; }

        [DataMember]
        [DisplayName("Position")]
        public int Position { get; set; }

        [DataMember]
        [DisplayName("Skip")]
        public int Skip { get; set; }

        [DataMember]
        [DisplayName("IsBlock")]
        public bool IsBlock { get; set; }
    }

    public class AdvertisementMap : EntityTypeConfiguration<AdvertisementInfo>, IEntityTypeConfiguration
    {
        public AdvertisementMap()
        {
            ToTable("Modules_Advertisement");
            HasKey(m => m.Id);
            Property(m => m.LanguageCode).HasMaxLength(50);
            Property(m => m.KeyCode).IsRequired().HasMaxLength(50);
            Property(m => m.Title).IsRequired().HasMaxLength(250);
            Property(m => m.Code).IsRequired().HasMaxLength(50);
            Property(m => m.Link).IsRequired().HasMaxLength(500);
            Property(m => m.Type).IsRequired().HasMaxLength(50);
            Property(m => m.Click).HasMaxLength(500);
            Property(m => m.Duration).IsRequired();
            Property(m => m.Position).IsRequired();
            Property(m => m.Skip).IsRequired();
        }
    }
}<file_sep>﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class TransactioCustomerLogs
    {
        [DataMember]
        [DisplayName("CreateDate")]
        public DateTime CreateDate { get; set; }

        [DataMember]
        [DisplayName("Amount")]
        public string Amount { get; set; }

        [DataMember]
        [DisplayName("Type")]
        public string Type { get; set; }

        [DataMember]
        [DisplayName("TransactionCode")]
        public string TransactionCode { get; set; }
    }

    public class NapVipCustomerLogs
    {
        [DataMember]
        [DisplayName("CreateDate")]
        public DateTime CreateDate { get; set; }

        [DataMember]
        [DisplayName("Amount")]
        public string Amount { get; set; }

        [DataMember]
        [DisplayName("TotalDay")]
        public string TotalDay { get; set; }

        [DataMember]
        [DisplayName("Package")]
        public string Package { get; set; }

        [DataMember]
        [DisplayName("StartDate")]
        public DateTime StartDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextStartDate
        {
            get
            {
                return StartDate.ToString(Extensions.Constants.DateTimeFomatFull);
            }
        }

        [DataMember]
        [DisplayName("EndDate")]
        public DateTime EndDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextEndDate
        {
            get
            {
                return EndDate.ToString(Extensions.Constants.DateTimeFomatFull);
            }
        }
    }
}<file_sep>﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class CategoryInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("SiteId")]
        public int SiteId { get; set; }

        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }

        [DataMember]
        [DisplayName("ParentId")]
        public int ParentId { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string ParentName { get; set; }

        [DataMember]
        [DisplayName("ShortName")]
        public string ShortName { get; set; }

        [DataMember]
        [DisplayName("Name")]
        public string Name { get; set; }

        [DataMember]
        [DisplayName("Alias")]
        public string Alias { get; set; }

        [DataMember]
        [DisplayName("IsHome")]
        public bool IsHome { get; set; }

        [DataMember]
        [DisplayName("HasChilden")]
        public bool HasChilden { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string ChildenName { get; set; }

        [DataMember]
        [DisplayName("CreateDate")]
        public DateTime CreateDate { get; set; }

        [DataMember]
        [DisplayName("Description")]
        public string Description { get; set; }

        [DataMember]
        [DisplayName("Tags")]
        public string Tags { get; set; }
        
        [DataMember]
        [DisplayName("Url")]
        public string Url { get; set; }

        [DataMember]
        [DisplayName("IsDisplay")]
        public bool IsActived { get; set; }

        [DataMember]
        [DisplayName("OrderBy")]
        public int OrderBy { get; set; }

        [DataMember]
        [DisplayName("IsDeleted")]
        public bool IsDeleted { get; set; }
    }

    public class CategoryMap : EntityTypeConfiguration<CategoryInfo>, IEntityTypeConfiguration
    {
        public CategoryMap()
        {
            ToTable("Modules_Categories");
            HasKey(x => x.Id);
            Property(x => x.SiteId).IsRequired();
            Property(x => x.ParentId);
            Property(x => x.LanguageCode).HasMaxLength(50);
            Property(x => x.ShortName).IsRequired().HasMaxLength(250);
            Property(x => x.Name).IsRequired().HasMaxLength(400);
            Property(x => x.Alias).IsRequired().HasMaxLength(400);
            Property(x => x.CreateDate).IsRequired();
            Property(x => x.Description).HasMaxLength(2000).IsRequired();
            Property(x => x.Tags).HasMaxLength(2000).IsRequired();
            Property(x => x.Url).IsRequired();
            Property(x => x.IsActived).IsRequired();
            Property(x => x.OrderBy).IsRequired();
            Property(x => x.IsDeleted).IsRequired();
            Property(x => x.IsHome).IsRequired();
            Property(x => x.HasChilden).IsRequired();
        }
    }
}<file_sep>﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using CMSSolutions.Websites.Extensions;
using CMSSolutions.Websites.VipHDCardServices;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;

namespace CMSSolutions.Websites.Payments
{
    public class APICardCharging
    {
        public APICardCharging()
        {
            Password = System.Configuration.ConfigurationManager.AppSettings["Password"];
            TransactionId = int.Parse(System.Configuration.ConfigurationManager.AppSettings["TransactionId"]);
            MPin = System.Configuration.ConfigurationManager.AppSettings["MPin"];
            CardList = System.Configuration.ConfigurationManager.AppSettings["CardList"];
            CardData = System.Configuration.ConfigurationManager.AppSettings["CardData"];
        }

        private string UserName
        {
            get { return System.Configuration.ConfigurationManager.AppSettings["UserName"]; }
        }

        private string Password { get; set; }

        private string PartnerId
        {
            get { return System.Configuration.ConfigurationManager.AppSettings["CardPartnerId"]; }
        }

        private int TransactionId { get; set; }

        private string MPin { get; set; }

        public string CardList { get; set; }

        public string CardData { get; set; }

        public string EncryptDataRSA(string origData, string publicKey)
        {
            byte[] plaintext = Encoding.ASCII.GetBytes(origData);
            byte[] bKey = JavaScience.opensslkey.DecodePkcs8EncPrivateKey(publicKey);
            RSACryptoServiceProvider myrsa = JavaScience.opensslkey.DecodeX509PublicKey(bKey);
            byte[] encrypt = myrsa.Encrypt(plaintext, false);
            string enStr = Convert.ToBase64String(encrypt);
            return enStr;
        }

        public string DecryptDataRSA(string deData, string privateKey)
        {
            try
            {
                byte[] Databyte = Convert.FromBase64String(deData);
                byte[] privatebKEY = JavaScience.opensslkey.DecodeOpenSSLPrivateKey(privateKey);
                RSACryptoServiceProvider rsa = JavaScience.opensslkey.DecodeRSAPrivateKey(privatebKEY);
                string dataDecript = Encoding.ASCII.GetString(rsa.Decrypt(Databyte, false));
                return dataDecript;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string EncryptDataTripdesPKCS7(string origData, string key)
        {
            byte[] tripkey = Encrypt.hexa.hexatobyte(key);
            byte[] entrip = TripleDES_Encrypt_Byte(tripkey, Encoding.UTF8.GetBytes(origData));
            return ByteArrayToHexString(entrip);
        }

        public string EncryptDataTripdes(string origData, string key)
        {
            byte[] tripkey = Encrypt.hexa.hexatobyte(key);
            string erro = "";
            string entrip = Encrypt.Encrypt._EncryptTripleDes(origData, tripkey, ref erro);

            return entrip;
        }

        public string DecryptDataTripdes(string deData, string key)
        {
            byte[] tripkey = Encrypt.hexa.hexatobyte(key);
            string error = "";
            string detrip = Encrypt.Encrypt._DecryptTripleDes(deData, tripkey, ref error);
            return detrip;
        }

        private String GetLocal()
        {
            String local = System.Web.HttpContext.Current.Request.MapPath("~");
            return local;
        }

        public string Login(out string tokenKey)
        {
            try
            {
                var keyDir = GetLocal() + "\\RsaKeys\\";    
                var websv = new ServicesService();
                var loginRes = new LoginResponse();
                string publicKey = keyDir + "epay_public_key.pem";
                string encryptPass = Encrypt2(publicKey, Password);
                loginRes = websv.login(UserName, encryptPass, PartnerId);
                if ((ErrorMessages)Convert.ToInt32(loginRes.status) == ErrorMessages.Success)
                {
                    string privateKey = keyDir + "private_key.pem";
                    tokenKey = Decrypt2(privateKey, loginRes.sessionid);
                    return Utilities.GetMessages(Convert.ToInt32(loginRes.status));
                }

                tokenKey = string.Empty;
                return Utilities.GetMessages(Convert.ToInt32(loginRes.status));
            }
            catch (Exception ex)
            {
                tokenKey = string.Empty;
                return ex.Message;
            }
        }

        public string Logout(string sessionid)
        {
            var websv = new ServicesService();
            string md5hex2str = HashWithMD5(sessionid);
            byte[] cvmd52 = Convert.FromBase64String(md5hex2str);
            string md5sess = ByteArrayToHexString(cvmd52);
            var logoutres = new LogoutResponse();
            logoutres = websv.logout(UserName, PartnerId, md5sess);

            var message = Utilities.GetMessages(Convert.ToInt32(logoutres.status));
            return message + "-" + message;
        }

        public string ChangeMpin(string sessionid, string newPassword)
        {
            string datetime = GetDateTime();
            string strTransID = PartnerId.Trim() + "_" + UserName.Trim() + "_" + datetime.Trim() + "_" + TransactionId;
            TransactionId++;
            if (newPassword.Length == 0)
            {
                return "Mật khẩu nhập không đúng.";
            }

            if (newPassword.Equals(MPin))
            {
                return "Mật khẩu trùng với mật khẩu cũ.";
            }

            string ensess = HashWithMD5(sessionid);
            byte[] cvmd52 = Convert.FromBase64String(ensess);
            string md5sess = ByteArrayToHexString(cvmd52);
            var websv = new ServicesService();
            string enoldpin = EncryptDataTripdes(MPin, sessionid);
            string ennewpin = EncryptDataTripdes(newPassword, sessionid);
            var changeRes = new ChangeResponse();
            changeRes = websv.changeMPIN(strTransID, UserName, PartnerId, enoldpin, ennewpin, md5sess);
            var message = Utilities.GetMessages(Convert.ToInt32(changeRes.status));
            if ((ErrorMessages)Convert.ToInt32(changeRes.status) == ErrorMessages.Success)
            {
                MPin = newPassword;
            }

            return message;
        }

        public string GetDateTime()
        {
            return DateTime.Now.ToString("yyyyMMddHHmmss");
        }

        public string ChangePassword(string sessionid, string newPassword)
        {
            string datetime = GetDateTime();
            string strTransID = PartnerId.Trim() + "_" + UserName.Trim() + "_" + datetime.Trim() + "_" + TransactionId;
            TransactionId++;
            if (newPassword.Length == 0)
            {
                return "Mật khẩu nhập không đúng";
            }
            if (newPassword.Equals(Password))
            {
                return "Mật khẩu trùng với mật khẩu cũ.";
            }

            string ensess = HashWithMD5(sessionid);
            byte[] cvmd52 = Convert.FromBase64String(ensess);
            string md5sess = ByteArrayToHexString(cvmd52);
            var websv = new ServicesService();
            string enoldpass = EncryptDataTripdes(Password, sessionid);
            string ennewpass = EncryptDataTripdes(newPassword, sessionid);
            var changeRes = new ChangeResponse();
            changeRes = websv.changePassword(strTransID, UserName, PartnerId, enoldpass, ennewpass, md5sess);
            var message = Utilities.GetMessages(Convert.ToInt32(changeRes.status));
            if ((ErrorMessages)Convert.ToInt32(changeRes.status) == ErrorMessages.Success)
            {
                Password = <PASSWORD>;
            }

            return message;
        }

        public string CheckTrain(string sessionid, string tranid)
        {
            if (string.IsNullOrEmpty(tranid))
            {
                return "Mã không để trống.";
            }

            string ensess = HashWithMD5(sessionid);
            byte[] cvmd52 = Convert.FromBase64String(ensess);
            string md5sess = ByteArrayToHexString(cvmd52);
            var websv = new ServicesService();
            var chargres = new ChargeReponse();
            chargres = websv.getTransactionStatus(tranid, UserName, PartnerId, md5sess);

            return Utilities.GetMessages(Convert.ToInt32(chargres.status));

        }

        public string CardCharging(string sessionid, int seed, string carddata, string transID, string target, out string amount)
        {
            string mapin = EncryptDataTripdesPKCS7(MPin, sessionid);
            string enCard = EncryptDataTripdesPKCS7(carddata, sessionid);
            string md5hex2str = HashWithMD5(sessionid);
            byte[] cvmd52 = Convert.FromBase64String(md5hex2str);
            string md5sess = ByteArrayToHexString(cvmd52);
            var chargeRes = new ChargeReponse();
            var message = string.Empty;
            amount = "0";
            try
            {
                var websv = new ServicesService();
                chargeRes = websv.cardCharging(transID, UserName, PartnerId, mapin, target, enCard, md5sess);
                if ((ErrorMessages)Convert.ToInt32(chargeRes.status) == ErrorMessages.Success)
                {
                    message = Utilities.GetMessages((int)ErrorMessages.Success);
                    amount = DecryptDataTripdesPKCS7(chargeRes.responseamount, sessionid);
                }
                else
                {
                    message = Utilities.GetMessages(Convert.ToInt32(chargeRes.status));
                }
            }
            catch
            {
                message = Utilities.GetMessages((int)ErrorMessages.SystemBusy);
            }

            return message;
        }

        public ErrorMessages CardCharging(string sessionid, string carddata, string target, out string amount)
        {
            string datetime = GetDateTime();
            var ran = new Random();
            string kqran = ran.Next(10000, 99999).ToString();
            string strTransID = System.Configuration.ConfigurationManager.AppSettings["TransactionId"] + "_" + datetime + "_" + kqran;
            string mapin = EncryptDataTripdesPKCS7(MPin, sessionid);
            string enCard = EncryptDataTripdesPKCS7(carddata, sessionid);
            string md5hex2str = HashWithMD5(sessionid);
            byte[] cvmd52 = Convert.FromBase64String(md5hex2str);
            string md5sess = ByteArrayToHexString(cvmd52);
            var chargeRes = new ChargeReponse();
            amount = "0";
            try
            {
                var websv = new ServicesService();
                chargeRes = websv.cardCharging(strTransID, UserName, PartnerId, mapin, target, enCard, md5sess);
                var status = (ErrorMessages) Convert.ToInt32(chargeRes.status);
                if (status == ErrorMessages.Success)
                {
                    amount = DecryptDataTripdesPKCS7(chargeRes.responseamount, sessionid);
                }

                return status;
            }
            catch
            {
                return ErrorMessages.Fail;
            }
        }

        public static string HashWithMD5(string text)
        {
            var hashAlgorithm = new MD5CryptoServiceProvider();
            return HashString(text, hashAlgorithm);
        }

        public static string HashString(string stringToHash, HashAlgorithm algo)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(stringToHash);
            bytes = algo.ComputeHash(bytes);
            return Convert.ToBase64String(bytes);
        }

        private static string ByteArrayToHexString(byte[] Bytes)
        {
            var Result = new StringBuilder();
            string HexAlphabet = "0123456789ABCDEF";
            foreach (byte B in Bytes)
            {
                Result.Append(HexAlphabet[(int)(B >> 4)]);
                Result.Append(HexAlphabet[(int)(B & 0xF)]);
            }

            return Result.ToString();
        }

        public string DecryptDataTripdesPKCS7(string origData, string key)
        {
            byte[] tripkey = Encrypt.hexa.hexatobyte(key);
            string erro = "";
            byte[] entrip = TripleDES_Decrypt_Byte(tripkey, Encrypt.hexa.hexatobyte(origData));//Encrypt.Encrypt._EncryptTripleDes(origData, tripkey, ref erro);
            return Encoding.UTF8.GetString(entrip);
        }

        private byte[] TripleDES_Encrypt_Byte(byte[] Keys, byte[] clearText)
        {
            try
            {
                byte[] IVs = new byte[8];
                var des = new TripleDESCryptoServiceProvider
                {
                    IV = IVs, 
                    KeySize = 192, 
                    Key = Keys,
                    Mode = CipherMode.ECB,
                    Padding = PaddingMode.PKCS7
                };

                byte[] cipherText = des.CreateEncryptor().TransformFinalBlock(clearText, 0, clearText.Length);
                return cipherText;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private byte[] TripleDES_Decrypt_Byte(byte[] Keys, byte[] clearText)
        {
            try
            {
                byte[] IVs = new byte[8];
                var des = new TripleDESCryptoServiceProvider();
                des.IV = IVs;
                des.KeySize = 192;             
                des.Key = Keys;
                des.Mode = CipherMode.ECB;
                des.Padding = PaddingMode.PKCS7;
                byte[] cipherText = des.CreateDecryptor().TransformFinalBlock(clearText, 0, clearText.Length);
                return cipherText;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public AsymmetricCipherKeyPair GetPrivateKey(string privateKey)
        {
            try
            {
                var sr = new StreamReader(privateKey);
                var pr = new Org.BouncyCastle.OpenSsl.PemReader(sr);
                var KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject();
                sr.Close();
                return KeyPair;
            }
            catch (Exception ex)
            {
                throw new Exception("Exception:", ex);
            }
        }

        public AsymmetricKeyParameter GetPublicKey(string publicKey)
        {
            try
            {
                var sr = new StreamReader(publicKey);
                var pr = new Org.BouncyCastle.OpenSsl.PemReader(sr);
                var KeyPair = (AsymmetricKeyParameter)pr.ReadObject();
                sr.Close();
                return KeyPair;
            }
            catch (Exception ex)
            {
                throw new Exception("Exception:", ex);
            }
        }

        public string Decrypt2(string privateKeyFileName, string encryptString)
        {
            try
            {
                AsymmetricCipherKeyPair keyPair = GetPrivateKey(privateKeyFileName);
                IAsymmetricBlockCipher cipher = new RsaEngine();
                cipher.Init(false, keyPair.Private);
                byte[] encryptByte = Convert.FromBase64String(encryptString);
                byte[] cipheredBytes = cipher.ProcessBlock(encryptByte, 0, encryptByte.Length);
                String decryptString = Encoding.UTF8.GetString(cipheredBytes);
                return decryptString;
            }
            catch (Exception ex)
            {
                throw new Exception("Exception encrypting file:", ex);
            }
        }

        public string Encrypt2(string publicKeyFileName, string inputMessage)
        {
            try
            {
                AsymmetricKeyParameter keyPair = GetPublicKey(publicKeyFileName);
                var utf8enc = new UTF8Encoding();
                byte[] inputBytes = utf8enc.GetBytes(inputMessage);
                AsymmetricKeyParameter publicKey = keyPair;
                IAsymmetricBlockCipher cipher = new RsaEngine();
                cipher.Init(true, publicKey);
                byte[] cipheredBytes = cipher.ProcessBlock(inputBytes, 0, inputMessage.Length);
                String encrypt = Convert.ToBase64String(cipheredBytes);
                return encrypt;
            }
            catch (Exception ex)
            {
                throw new Exception("Encrypt string fail:", ex);
            }
        }
    }
}<file_sep>using System.ComponentModel;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class FilmTypesInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("LanguageCode")]
        public string LanguageCode { get; set; }
        
        [DataMember]
        [DisplayName("SiteId")]
        public int SiteId { get; set; }
        
        [DataMember]
        [DisplayName("Name")]
        public string Name { get; set; }
        
        [DataMember]
        [DisplayName("Description")]
        public string Description { get; set; }
        
        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }

        [DataMember]
        [DisplayName("IsFilm")]
        public bool IsFilm { get; set; }

        [DataMember]
        [DisplayName("IsShow")]
        public bool IsShow { get; set; }

        [DataMember]
        [DisplayName("IsClip")]
        public bool IsClip { get; set; }

        [DataMember]
        [DisplayName("IsJJFilm")]
        public bool IsJJFilm { get; set; }
    }

    public class FilmTypeMap : EntityTypeConfiguration<FilmTypesInfo>, IEntityTypeConfiguration
    {

        public FilmTypeMap()
        {
           ToTable("Modules_FilmTypes");
           HasKey(m => m.Id);
           Property(m => m.LanguageCode).IsRequired().HasMaxLength(50);
           Property(m => m.SiteId).IsRequired();
           Property(m => m.Name).IsRequired().HasMaxLength(250);
           Property(m => m.Description).HasMaxLength(200);
           Property(m => m.Status);
        }
    }
}
<file_sep>using System.Collections.Generic;
using System.Data.SqlClient;
using CMSSolutions.Data;
using CMSSolutions.Events;
using CMSSolutions.Services;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Services
{
    public interface ICountryService : IGenericService<CountryInfo, int>, IDependency
    {
        bool CheckExist(int id, string keyword);

        List<CountryInfo> SearchPaged(
            string searchText,
            int pageIndex,
            int pageSize,
            out int totalRecord);
    }

    public class CountryService : GenericService<CountryInfo, int>, ICountryService
    {
        public CountryService(IRepository<CountryInfo, int> repository, IEventBus eventBus) 
            : base(repository, eventBus)
        {

        }

        public bool CheckExist(int id, string keyword)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Id", id),
                AddInputParameter("@Keyword", keyword)
            };
            var result = (int)ExecuteReaderResult("sp_Countries_CheckName", list.ToArray());

            return result > 0;
        }

        public List<CountryInfo> SearchPaged(string searchText, int pageIndex, int pageSize, out int totalRecord)
        {
            var list = new List<SqlParameter>
            {
                AddInputParameter("@Keyword", searchText),
                AddInputParameter("@PageIndex", pageIndex),
                AddInputParameter("@PageSize", pageSize)
            };

            return ExecuteReader<CountryInfo>("sp_Countries_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray());
        }
    }
}
<file_sep>﻿using System.Collections.Generic;
using CMSSolutions.Web.Security.Permissions;

namespace CMSSolutions.Websites.Permissions
{
    public class AdminPermissions : IPermissionProvider
    {
        public static readonly Permission ManagerSlider = new Permission
        {
            Name = "ManagerSlider",
            Category = "Management",
            Description = "Quản lý slider"
        };

        public static readonly Permission ManagerFilms = new Permission
        {
            Name = "ManagerFilms",
            Category = "Management",
            Description = "Quản lý phim"
        };

        public static readonly Permission ManagerFilmTypes = new Permission
        {
            Name = "ManagerFilmTypes",
            Category = "Management",
            Description = "Quản lý thể loại phim"
        };

        public static readonly Permission ManagerServerFilms = new Permission
        {
            Name = "ManagerServerFilms",
            Category = "Management",
            Description = "Quản lý máy chủ phim"
        };

        public static readonly Permission ManagerEpisodes = new Permission
        {
            Name = "ManagerEpisodes",
            Category = "Management",
            Description = "Quản lý các tập phim"
        };

        public static readonly Permission ManagerDirectors = new Permission
        {
            Name = "ManagerDirectors",
            Category = "Management",
            Description = "Quản lý đạo diễn phim"
        };

        public static readonly Permission ManagerCountries = new Permission
        {
            Name = "ManagerCountries",
            Category = "Management",
            Description = "Quản lý nước sản xuất phim"
        };

        public static readonly Permission ManagerCollections = new Permission
        {
            Name = "ManagerCollections",
            Category = "Management",
            Description = "Quản lý các bộ phim"
        };

        public static readonly Permission ManagerActors = new Permission
        {
            Name = "ManagerActors",
            Category = "Management",
            Description = "Quản lý diễn viên"
        };

        public static readonly Permission ManagerTags = new Permission
        {
            Name = "ManagerTags",
            Category = "Management",
            Description = "Quản lý tags"
        };

        public static readonly Permission ManagerArticles = new Permission
        {
            Name = "ManagerArticles",
            Category = "Management",
            Description = "Quản lý tin tức"
        };
        public static readonly Permission ManagerDownloadGames = new Permission
        {
            Name = "ManagerDownloadGames",
            Category = "Management",
            Description = "Quản lý sự kiện đào xu"
        };
        public static readonly Permission ManagerSites = new Permission
        {
            Name = "ManagerSites",
            Category = "Management",
            Description = "Quản lý các site"
        };

        public static readonly Permission ManagerCategories = new Permission
        {
            Name = "ManagerCategories",
            Category = "Management",
            Description = "Quản lý chuyên mục"
        };

        public static readonly Permission ManagerAdvertisementGroup = new Permission
        {
            Name = "ManagerAdvertisementGroup",
            Category = "Management",
            Description = "Quản lý nhóm quảng cáo"
        };

        public static readonly Permission ManagerAdvertisement = new Permission
        {
            Name = "ManagerAdvertisement",
            Category = "Management",
            Description = "Quản lý quảng cáo"
        };
        
        public static readonly Permission ManagerVast = new Permission
        {
            Name = "ManagerVast",
            Category = "Management",
            Description = "Quản lý Vast"
        };

        public static readonly Permission ManagerSupports = new Permission
        {
            Name = "ManagerSupports",
            Category = "Management",
            Description = "Hỏi đáp"
        };

        public static readonly Permission ManagerRates = new Permission
        {
            Name = "ManagerRates",
            Category = "Management",
            Description = "Đánh giá và báo lỗi"
        };
        
        public static readonly Permission ManagerAdmin = new Permission
        {
            Name = "ManagerAdmin",
            Category = "Management",
            Description = "Bảng điều khiển"
        };

        public static readonly Permission ManagerBankCards = new Permission
        {
            Name = "ManagerBankCards",
            Category = "Management",
            Description = "Quản lý dịch vụ thẻ ngân hàng"
        };

        public static readonly Permission ManagerCardTypes = new Permission
        {
            Name = "ManagerCardTypes",
            Category = "Management",
            Description = "Quản lý loại thẻ cào"
        };

        public static readonly  Permission ManagerVipCards = new Permission
        {
            Name = "ManagerVipCards",
            Category = "Management",
            Description = "Quản lý thẻ VIP"
        };

        public static readonly Permission ManagerPromotions = new Permission
        {
            Name = "ManagerPromotions",
            Category = "Management",
            Description = "Quản lý khuyến mãi"
        };

        public static readonly Permission ManagerCustomers = new Permission
        {
            Name = "ManagerCustomers",
            Category = "Management",
            Description = "Quản lý khách hàng"
        };

        public static readonly Permission ManagerFilmFiles  = new Permission
        {
            Name = "ManagerFilmFiles",
            Category = "Management",
            Description = "Quản lý video files"
        };

        public static readonly Permission ManagerSystemLogs = new Permission
        {
            Name = "ManagerSystemLogs",
            Category = "Management",
            Description = "Quản lý logs hệ thống"
        };

        public static readonly Permission ManagerAdminReportSms = new Permission
        {
            Name = "ManagerAdminReportSms",
            Category = "Management",
            Description = "Đối soát SMS"
        };

        public static readonly Permission ManagerAdminReportAtm = new Permission
        {
            Name = "ManagerAdminReportAtm",
            Category = "Management",
            Description = "Đối soát ATM"
        };

        public static readonly Permission ManagerAdminReportCard = new Permission
        {
            Name = "ManagerAdminReportCard",
            Category = "Management",
            Description = "Đối soát thẻ cào"
        };

        public IEnumerable<Permission> GetPermissions()
        {
            yield return ManagerAdmin;
            yield return ManagerCategories;
            yield return ManagerSites;
            yield return ManagerArticles;
            yield return ManagerDirectors;
            yield return ManagerCountries;
            yield return ManagerCollections;
            yield return ManagerActors;
            yield return ManagerEpisodes;
            yield return ManagerServerFilms;
            yield return ManagerFilmTypes;
            yield return ManagerFilms;
            yield return ManagerVipCards;
            yield return ManagerCustomers;
            yield return ManagerFilmFiles;
            yield return ManagerSystemLogs;
            yield return ManagerPromotions;
            yield return ManagerAdminReportSms;
            yield return ManagerAdminReportAtm;
            yield return ManagerAdminReportCard;
            yield return ManagerSupports;
            yield return ManagerAdvertisementGroup;
            yield return ManagerAdvertisement;
            yield return ManagerVast;
            yield return ManagerRates;
            yield return ManagerDownloadGames;
            yield return ManagerSlider;
            yield return ManagerTags;
        }   
    }
}<file_sep>﻿using System;
using System.IO;

namespace CMSSolutions.Websites.Extensions
{
    public class LogFiles
    {
        public static void WriteLogSms(string msg)
        {
            try
            {
                var logFile = string.Format(@"{0}\{1}_{2}.txt", Constants.SmsLogFiles, "SMS", DateTime.Now.ToString("dd-MM-yyyy"));
                using (var sw = new StreamWriter(logFile, true))
                {
                    sw.WriteLine(DateTime.Now.ToShortTimeString() + ": " + msg);
                    sw.Close();
                }
            }
            catch (Exception)
            {
                
            }
        }
    }
}<file_sep>﻿using System;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;
using CMSSolutions.Websites.Extensions;

namespace CMSSolutions.Websites.Models
{
    public class CustomerModel
    {
        public CustomerModel()
        {
            Birthday = DateTime.Now.AddYears(-10);
            ImageIcon = "/Images/avatars/avatar-no-image.png";
        }

        [ControlHidden]
        public int Id { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Mã khách hàng", PlaceHolder = "Tự động sinh mã", MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public string CutomerCode { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Tài khoản đăng nhập", PlaceHolder = "Nhập ký tự không dấu, email, sđt.", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public string UserName { get; set; }

        [ControlText(Type = ControlText.Password, LabelText = "Mật <NAME>", PlaceHolder = "Mật khẩu chứa ký tự Hoa, Thường, Số, 1 ký tự đặc biệt.", Required = true, MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public string Password { get; set; }

        [ControlText(Type = ControlText.Email, LabelText = "Email", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)]
        public string Email { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "<NAME>", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public string FullName { get; set; }

        [ControlDatePicker(LabelText = "Ngày sinh", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public DateTime Birthday { get; set; }

        [ControlChoice(ControlChoice.DropDownList, LabelText = "Giới tính", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public int Sex { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Số điện thoại", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)]
        public string PhoneNumber { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Khóa tài khoản", ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 2)]
        public bool IsBlock { get; set; }

        [ControlNumeric(LabelText = "VIP Xu", Required = true, ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 2)]
        public decimal VipXu { get; set; }

        [ControlNumeric(LabelText = "Tổng tiền", Required = true, ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 2)]
        public decimal TotalMoney { get; set; }

        [ControlNumeric(LabelText = "Tổng số ngày", Required = true, ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 2)]
        public int TotalDay { get; set; }

        [ControlText(Type = ControlText.TextBox, ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 2)]
        public string StartDate { get; set; }

        [ControlText(Type = ControlText.TextBox, ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 2)]
        public string EndDate { get; set; }

        [ControlFileUpload(EnableFineUploader = true, Required = true, LabelText = "Ảnh đại diện", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 3, ShowThumbnail = true)]
        public string ImageIcon { get; set; }

        [ControlChoice(ControlChoice.DropDownList, LabelText = "Quận huyện/Thành phố", ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 3)]
        public string CityId { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Địa chỉ", MaxLength = 2000, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 3)]
        public string Address { get; set; }

        [ControlChoice(ControlChoice.DropDownList, AllowMultiple = true, CssClass = Extensions.Constants.CssControlCustom, EnableChosen = true, Required = true, LabelText = "Thể loại phim", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 4)]
        public int[] FilmTypeIds { get; set; }

        [ControlChoice(ControlChoice.DropDownList, AllowMultiple = true, CssClass = Extensions.Constants.CssControlCustom, EnableChosen = true, Required = true, LabelText = "Nước sản xuất", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 4)]
        public int[] CountryIds { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Facebook", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 6)]
        public string Facebook { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Skype", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 6)]
        public string Skype { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Zing Me", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 6)]
        public string ZingMe { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Google", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 7)]
        public string Google { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Yahoo", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 7)]
        public string Yahoo { get; set; }

        [ControlChoice(ControlChoice.DropDownList, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 7)]
        public int Status { get; set; }

        [ControlText(Type = ControlText.MultiText, Rows = 3, MaxLength = 2000, LabelText = "Giới thiệu", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 8)]
        public string Description { get; set; }

        public static implicit operator CustomerModel(CustomerInfo entity)
        {
            return new CustomerModel
            {
                Id = entity.Id,
                CutomerCode = entity.CustomerCode,
                UserName = entity.UserName,
                Password = <PASSWORD>,
                FullName = entity.FullName,
                Email = entity.Email,
                Address = entity.Address,
                PhoneNumber = entity.PhoneNumber,
                CityId = entity.CityId,
                Birthday = entity.Birthday,
                Sex = entity.Sex,
                ImageIcon = entity.ImageIcon,
                FilmTypeIds = Utilities.ParseListInt(entity.FilmTypeIds),
                CountryIds = Utilities.ParseListInt(entity.CountryIds),
                Skype = entity.Skype,
                ZingMe = entity.ZingMe,
                Facebook = entity.Facebook,
                Google = entity.Google,
                Yahoo = entity.Yahoo,
                VipXu = entity.VipXu,
                TotalMoney = entity.TotalMoney,
                IsBlock = entity.IsBlock,
                Status = entity.Status,
                Description = entity.Description,
                TotalDay = entity.TotalDay,
                StartDate = entity.TextStartDate,
                EndDate = entity.TextEndDate
            };
        }
    }
}
<file_sep>﻿using System;
using System.Web.Mvc;
using CMSSolutions.Web.Mvc;
using CMSSolutions.Web.Themes;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Web.UI.Navigation;
using CMSSolutions.Websites.Models;
using CMSSolutions.Websites.Services;

namespace CMSSolutions.Websites.Controllers
{
    [Themed(IsDashboard = true), Authorize]
    public class AdminClosedBankController : BaseAdminController
    {
        public AdminClosedBankController(IWorkContextAccessor workContextAccessor) 
            : base(workContextAccessor)
        {

        }

        [Url("admin/bank/close")]
        public ActionResult Index()
        {
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Báo cáo ATM"), Url = Url.Action("Index","AdminReportBank") });
            WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Chốt sổ đối soát ATM"), Url = "#" });

            var model = new BankCloseModel();
            var result = new ControlFormResult<BankCloseModel>(model)
            {
                Title = T("Chốt sổ đối soát ATM"),
                FormMethod = FormMethod.Post,
                UpdateActionName = "Update",
                SubmitButtonText = T("Chốt"),
                CancelButtonText = T("Trở về"),
                CancelButtonUrl = Url.Action("Index", "AdminReportBank"),
                ShowBoxHeader = false,
                FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml,
                FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml
            };
            result.MakeReadOnlyProperty(x => x.Messages);

            return result;
        }

        [HttpPost, ValidateInput(false), FormButton("Save")]
        [Url("admin/bank/close/update")]
        public ActionResult Update(BankCloseModel model)
        {
            if (!ModelState.IsValid)
            {
                return new AjaxResult().Alert(T(Constants.Messages.InvalidModel));
            }

            if (model.EndDate > DateTime.Now)
            {
                return new AjaxResult().Alert(T("Thời gian bạn chọn chưa phát sinh giao dịch mới!"));
            }

            WorkContext.Resolve<ITransactionBankService>().ATMClosed(model.EndDate);

            return new AjaxResult()
                .NotifyMessage("UPDATE_ENTITY_COMPLETE")
                .Alert(string.Format(T("Đã chốt sổ đối soát đến hết ngày {0} thành công!"),
                model.EndDate.ToString(Extensions.Constants.DateTimeFomat)));
        }
    }
}
<file_sep>﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class PromotionInfo : BaseEntity<int>
    {
        [DataMember]
        [DisplayName("Title")]
        public string Title { get; set; }

        [DataMember]
        [DisplayName("Contents")]
        public string Contents { get; set; }

        [DataMember]
        [DisplayName("FromDate")]
        public DateTime FromDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextFromDate
        {
            get
            {
                return FromDate.ToString(Extensions.Constants.DateTimeFomat);
            }
        }

        [DataMember]
        [DisplayName("ToDate")]
        public DateTime ToDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextToDate
        {
            get
            {
                return ToDate.ToString(Extensions.Constants.DateTimeFomat);
            }
        }

        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }
    }

    public class PromotionMap : EntityTypeConfiguration<PromotionInfo>, IEntityTypeConfiguration
    {
        public PromotionMap()
        {
            ToTable("Modules_Promotions");
            HasKey(m => m.Id);
            Property(m => m.Title).IsRequired().HasMaxLength(250);
            Property(m => m.Contents).IsRequired();
            Property(m => m.FromDate).IsRequired();
            Property(m => m.ToDate).IsRequired();
        }
    }
}<file_sep>﻿using System;
using CMSSolutions.Web.UI.ControlForms;
using CMSSolutions.Websites.Entities;

namespace CMSSolutions.Websites.Models
{
    public class DownloadGameModel
    {
        public DownloadGameModel()
        {
            Code = Guid.NewGuid().ToString().Replace("-", string.Empty);
        }

        [ControlHidden]
        public int Id { get; set; }

        [ControlText(Type = ControlText.TextBox, LabelText = "Mã sự kiện", Required = true, MaxLength = 100, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public string Code { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Tên sự kiện", ContainerCssClass = Constants.ContainerCssClassCol8, ContainerRowIndex = 0)]
        public string Title { get; set; }

        [ControlFileUpload(EnableFineUploader = true, LabelText = "Logo", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 1, Required = true, ShowThumbnail = true)]
        public string Logo { get; set; }

        [ControlFileUpload(EnableFineUploader = true, LabelText = "Banner", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 1, Required = true, ShowThumbnail = true)]
        public string UrlBanner { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 500, LabelText = "Đường dẫn tới game", ContainerCssClass = Constants.ContainerCssClassCol8, ContainerRowIndex = 2)]
        public string GooglePlayUrl { get; set; }

        [ControlNumeric(LabelText = "VIPXU", Required = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)]
        public int VipXu { get; set; }

        [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 500, LabelText = "Đường dẫn tới website", ContainerCssClass = Constants.ContainerCssClassCol8, ContainerRowIndex = 3)]
        public string WebsiteUrl { get; set; }

        [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Hiện trên trang chủ", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 3)]
        public bool IsActived { get; set; }

        public static implicit operator DownloadGameModel(DownloadGameInfo entity)
        {
            var item = new DownloadGameModel
            {
                Id = entity.Id,
                IsActived = entity.IsActived,
                Code = entity.Code,
                UrlBanner = entity.UrlBanner,
                Logo = entity.Logo,
                Title = entity.Title,
                GooglePlayUrl = entity.GooglePlayUrl,
                WebsiteUrl = entity.WebsiteUrl,
                VipXu = entity.VipXu
            };
            
            return item;
        }
    }
}<file_sep>using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using CMSSolutions.Data;
using CMSSolutions.Data.Entity;
using CMSSolutions.Websites.Extensions;

namespace CMSSolutions.Websites.Entities
{
    [DataContract]
    public class CustomerHistoriesInfo : BaseEntity<long>
    {
        [DataMember]
        [DisplayName("CustomerId")]
        public int CustomerId { get; set; }
        
        [DataMember]
        [DisplayName("CreateDate")]
        public System.DateTime CreateDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextCreateDate
        {
            get
            {
                return CreateDate.ToString(Extensions.Constants.DateTimeFomatFull);
            }
        }
        
        [DataMember]
        [DisplayName("Action")]
        public string Action { get; set; }
        
        [DataMember]
        [DisplayName("Description")]
        public string Description { get; set; }
        
        [DataMember]
        [DisplayName("Status")]
        public int Status { get; set; }

        [DataMember]
        [DisplayName("Type")]
        public int Type { get; set; }

        [DataMember]
        [DisplayName("TransactionCode")]
        public string TransactionCode { get; set; }

        [DataMember]
        [DisplayName("Package")]
        public string Package { get; set; }
        
        [DataMember]
        [DisplayName("Amount")]
        public string Amount { get; set; }

        [DataMember]
        [DisplayName("TotalDay")]
        public string TotalDay { get; set; }
        
        [DataMember]
        [DisplayName("StartDate")]
        public DateTime? StartDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextStartDate
        {
            get
            {
                if (StartDate == null)
                {
                    return "";
                }

                return StartDate.Value.ToString(Extensions.Constants.DateTimeFomatFull);
            }
        }

        [DataMember]
        [DisplayName("EndDate")]
        public DateTime? EndDate { get; set; }

        [NotMapped]
        [DisplayName(Constants.NotMapped)]
        public string TextEndDate
        {
            get
            {
                if (EndDate == null)
                {
                    return "";
                }

                return EndDate.Value.ToString(Extensions.Constants.DateTimeFomatFull);
            }
        }
    }

    public class CustomerHistoriesMap : EntityTypeConfiguration<CustomerHistoriesInfo>, IEntityTypeConfiguration
    {

        public CustomerHistoriesMap()
        {
            ToTable("Modules_CustomerHistories");
            HasKey(m => m.Id);
            Property(m => m.CustomerId).IsRequired();
            Property(m => m.CreateDate).IsRequired();
            Property(m => m.Action).IsRequired().HasMaxLength(250);
            Property(m => m.Description).IsRequired().HasMaxLength(2000);
            Property(m => m.TransactionCode).HasMaxLength(50);
            Property(m => m.Package).HasMaxLength(250);
            Property(m => m.Amount).HasMaxLength(50);
            Property(m => m.TotalDay).HasMaxLength(50);
        }
    }
}
<file_sep>﻿using System;
using CMSSolutions.Web.UI.ControlForms;

namespace CMSSolutions.Websites.Models
{
    public class CardCloseModel
    {
        public CardCloseModel()
        {
            EndDate = DateTime.Now;
            Messages = "Bạn chắc chắn đã xuất dữ liệu chưa đối soát? Hãy lưu lại nó vì nếu bạn chốt sẽ rồi sẽ không lấy lại được dữ liệu chưa đối soát.";
        }

        [ControlText(Type = ControlText.MultiText,Rows = 3, LabelText = "Ghi chú", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)]
        public string Messages { get; set; }

        [ControlDatePicker(LabelText = "Tính đến hết ngày", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)]
        public DateTime EndDate { get; set; }
    }
}