public async Task <ActionResult <JObject> > Details(string viewType, int?id)
        {
            string msg = string.Empty;

            switch (viewType)
            {
            case "portal":
                if (id.HasValue)
                {
                    Expression <Func <SioPage, bool> > predicate = model => model.Id == id && model.Specificulture == _lang;
                    var portalResult = await base.GetSingleAsync <UpdateViewModel>($"{viewType}_{id}", predicate);

                    if (portalResult.IsSucceed)
                    {
                        portalResult.Data.DetailsUrl = SioCmsHelper.GetRouterUrl("Page", new { portalResult.Data.SeoName }, Request, Url);
                    }

                    return(Ok(JObject.FromObject(portalResult)));
                }
                else
                {
                    var model = new SioPage()
                    {
                        Specificulture = _lang,
                        Status         = SioService.GetConfig <int>("DefaultStatus"),
                        PageSize       = 20
                        ,
                        Priority = UpdateViewModel.Repository.Max(a => a.Priority).Data + 1
                    };

                    RepositoryResponse <UpdateViewModel> result = await base.GetSingleAsync <UpdateViewModel>($"{viewType}_default", null, model);

                    return(Ok(JObject.FromObject(result)));
                }

            default:
                if (id.HasValue)
                {
                    var beResult = await ReadMvcViewModel.Repository.GetSingleModelAsync(model => model.Id == id && model.Specificulture == _lang).ConfigureAwait(false);

                    if (beResult.IsSucceed)
                    {
                        beResult.Data.DetailsUrl = SioCmsHelper.GetRouterUrl("Page", new { beResult.Data.SeoName }, Request, Url);
                    }
                    return(Ok(JObject.FromObject(beResult)));
                }
                else
                {
                    var model = new SioPage();
                    RepositoryResponse <ReadMvcViewModel> result = new RepositoryResponse <ReadMvcViewModel>()
                    {
                        IsSucceed = true,
                        Data      = new ReadMvcViewModel(model)
                        {
                            Specificulture = _lang,
                            Status         = SioContentStatus.Preview,
                            PageSize       = 20
                        }
                    };
                    return(Ok(JObject.FromObject(result)));
                }
            }
        }
Example #2
0
        /// <summary>
        /// Gets the language.
        /// </summary>
        protected void GetLanguage()
        {
            _lang           = RouteData?.Values["culture"] != null ? RouteData.Values["culture"].ToString() : SioService.GetConfig <string>("Language");
            ViewBag.culture = _lang;

            _domain = string.Format("{0}://{1}", Request.Scheme, Request.Host);
        }
Example #3
0
        public override async Task <RepositoryResponse <bool> > SaveSubModelsAsync(SioTheme parent, SioCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            RepositoryResponse <bool> result = new RepositoryResponse <bool>()
            {
                IsSucceed = true
            };

            try
            {
                // Clone Default templates
                Name = SeoHelper.GetSEOString(Title);
                string defaultTemplateFolder = $"{SioService.GetConfig<string>(SioConstants.ConfigurationKeyword.DefaultTemplateFolder) }";
                bool   copyResult            = FileRepository.Instance.CopyDirectory(defaultTemplateFolder, TemplateFolder);
                string defaultAssetsFolder   = CommonHelper.GetFullPath(new string[] {
                    SioConstants.Folder.WebRootPath,
                    "assets",
                    SioConstants.Folder.TemplatesAssetFolder,
                    "default"
                });
                copyResult = FileRepository.Instance.CopyDirectory(defaultAssetsFolder, AssetFolder);

                var files = FileRepository.Instance.GetFilesWithContent(TemplateFolder);
                //TODO: Create default asset
                int id = 0;
                foreach (var file in files)
                {
                    id++;
                    string content = file.Content.Replace("/assets/templates/default", $"/{ SioConstants.Folder.FileFolder}/{SioConstants.Folder.TemplatesAssetFolder}/{Name}");
                    SioTemplates.InitViewModel template = new SioTemplates.InitViewModel(
                        new SioTemplate()
                    {
                        Id              = id,
                        FileFolder      = file.FileFolder,
                        FileName        = file.Filename,
                        Content         = content,
                        Extension       = file.Extension,
                        CreatedDateTime = DateTime.UtcNow,
                        LastModified    = DateTime.UtcNow,
                        ThemeId         = Model.Id,
                        ThemeName       = Model.Name,
                        FolderType      = file.FolderName,
                        ModifiedBy      = CreatedBy
                    }, _context, _transaction);
                    var saveResult = await template.SaveModelAsync(true, _context, _transaction);

                    result.IsSucceed = result.IsSucceed && saveResult.IsSucceed;
                    if (!saveResult.IsSucceed)
                    {
                        result.Exception = saveResult.Exception;
                        result.Errors.AddRange(saveResult.Errors);
                        break;
                    }
                }
                return(result);
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Errors.Add(ex.Message);
                result.Exception = ex;
                return(result);
            }
        }
Example #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <SioCmsContext>();
            services.AddDbContext <SioDbContext>();

            // Enforce Request using https schema
            if (_env.IsDevelopment())
            {
                if (SioService.GetConfig <bool>("IsHttps"))
                {
                    services.AddHttpsRedirection(options =>
                    {
                        options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
                        options.HttpsPort          = 5001;
                    });
                }
            }
            else
            {
                if (SioService.GetConfig <bool>("IsHttps"))
                {
                    services.AddHttpsRedirection(options =>
                    {
                        options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
                        options.HttpsPort          = 443;
                    });
                }
            }

            // Config cookie options
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            //services.TryAddSingleton<IApiDescriptionGroupCollectionProvider, ApiDescriptionGroupCollectionProvider>();
            //services.TryAddEnumerable(
            //    ServiceDescriptor.Transient<IApiDescriptionProvider, DefaultApiDescriptionProvider>());

            // Config Authenticate
            // App_Start/Startup.Auth.cs
            ConfigAuthorization(services, Configuration);


            //When View Page Source That changes only the HTML encoder, leaving the JavaScript and URL encoders with their (ASCII) defaults.
            services.Configure <WebEncoderOptions>(options => options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All));

            // add application services.
            services.AddTransient <IEmailSender, AuthEmailMessageSender>();
            services.AddTransient <ISmsSender, AuthSmsMessageSender>();
            services.AddSingleton <SioService>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            // add signalr
            services.AddSignalR();

            // Config server caching
            services.AddMvc(options =>
            {
                options.CacheProfiles.Add("Default",
                                          new CacheProfile()
                {
                    Duration = 60
                });
                options.CacheProfiles.Add("Never",
                                          new CacheProfile()
                {
                    Location = ResponseCacheLocation.None,
                    NoStore  = true
                });
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddMemoryCache();
        }
 public void SendMail([FromBody] JObject model)
 {
     SioService.SendMail(model.Value <string>("subject"), model.Value <string>("body"), SioService.GetConfig <string>("ContactEmail", _lang));
 }
        public override RepositoryResponse <bool> SaveSubModels(SioTheme parent, SioCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            RepositoryResponse <bool> result = new RepositoryResponse <bool>()
            {
                IsSucceed = true
            };

            // import templates  + assets
            if (TemplateAsset.Content != null || TemplateAsset.FileStream != null)
            {
                result = ImportTheme(_context, _transaction);
            }

            // Create default template if create new without import template assets
            if (result.IsSucceed && Id == 0 && TemplateAsset.Content == null)
            {
                string defaultFolder = CommonHelper.GetFullPath(new string[] { SioConstants.Folder.TemplatesFolder, Name == "Default" ? "Default" :
                                                                               SioService.GetConfig <string>(SioConstants.ConfigurationKeyword.DefaultTemplateFolder) });
                bool copyResult = FileRepository.Instance.CopyDirectory(defaultFolder, TemplateFolder);
                var  files      = copyResult ? FileRepository.Instance.GetFilesWithContent(TemplateFolder) : new List <FileViewModel>();
                //TODO: Create default asset
                foreach (var file in files)
                {
                    SioTemplates.InitViewModel template = new SioTemplates.InitViewModel(
                        new SioTemplate()
                    {
                        FileFolder      = file.FileFolder,
                        FileName        = file.Filename,
                        Content         = file.Content,
                        Extension       = file.Extension,
                        CreatedDateTime = DateTime.UtcNow,
                        LastModified    = DateTime.UtcNow,
                        ThemeId         = Model.Id,
                        ThemeName       = Model.Name,
                        FolderType      = file.FolderName,
                        ModifiedBy      = CreatedBy
                    }, _context, _transaction);
                    var saveResult = template.SaveModel(true, _context, _transaction);
                    result.IsSucceed = result.IsSucceed && saveResult.IsSucceed;
                    if (!saveResult.IsSucceed)
                    {
                        result.Exception = saveResult.Exception;
                        result.Errors.AddRange(saveResult.Errors);
                        break;
                    }
                }
            }

            // Actived Theme
            if (result.IsSucceed && IsActived)
            {
                SystemConfigurationViewModel config = (SystemConfigurationViewModel.Repository.GetSingleModel(
                                                           c => c.Keyword == SioConstants.ConfigurationKeyword.ThemeName && c.Specificulture == Specificulture
                                                           , _context, _transaction)).Data;

                if (config == null)
                {
                    config = new SystemConfigurationViewModel(new SioConfiguration()
                    {
                        Keyword        = SioConstants.ConfigurationKeyword.ThemeName,
                        Specificulture = Specificulture,
                        Category       = "Site",
                        DataType       = (int)DataType.Text,
                        Description    = "Cms Theme",
                        Value          = Name
                    }, _context, _transaction)
                    ;
                }
                else
                {
                    config.Value = Name;
                }

                var saveConfigResult = config.SaveModel(false, _context, _transaction);
                if (!saveConfigResult.IsSucceed)
                {
                    Errors.AddRange(saveConfigResult.Errors);
                }
                else
                {
                    //SioCmsService.Instance.RefreshConfigurations(_context, _transaction);
                }
                result.IsSucceed = result.IsSucceed && saveConfigResult.IsSucceed;

                SystemConfigurationViewModel configId = (SystemConfigurationViewModel.Repository.GetSingleModel(
                                                             c => c.Keyword == SioConstants.ConfigurationKeyword.ThemeId && c.Specificulture == Specificulture, _context, _transaction)).Data;
                if (configId == null)
                {
                    configId = new SystemConfigurationViewModel(new SioConfiguration()
                    {
                        Keyword        = SioConstants.ConfigurationKeyword.ThemeId,
                        Specificulture = Specificulture,
                        Category       = "Site",
                        DataType       = (int)DataType.Text,
                        Description    = "Cms Theme Id",
                        Value          = Model.Id.ToString()
                    }, _context, _transaction)
                    ;
                }
                else
                {
                    configId.Value = Model.Id.ToString();
                }
                var saveResult = configId.SaveModel(false, _context, _transaction);
                if (!saveResult.IsSucceed)
                {
                    Errors.AddRange(saveResult.Errors);
                }
                else
                {
                    //SioCmsService.Instance.RefreshConfigurations(_context, _transaction);
                }
                result.IsSucceed = result.IsSucceed && saveResult.IsSucceed;
            }


            if (result.IsSucceed && TemplateAsset.Content != null || TemplateAsset.FileStream != null)
            {
                var           files     = FileRepository.Instance.GetWebFiles(AssetFolder);
                StringBuilder strStyles = new StringBuilder();

                foreach (var css in files.Where(f => f.Extension == ".css"))
                {
                    strStyles.Append($"   <link href='{css.FileFolder}/{css.Filename}{css.Extension}' rel='stylesheet'/>");
                }
                StringBuilder strScripts = new StringBuilder();
                foreach (var js in files.Where(f => f.Extension == ".js"))
                {
                    strScripts.Append($"  <script src='{js.FileFolder}/{js.Filename}{js.Extension}'></script>");
                }
                var layout = SioTemplates.InitViewModel.Repository.GetSingleModel(
                    t => t.FileName == "_Layout" && t.ThemeId == Model.Id
                    , _context, _transaction);
                layout.Data.Content = layout.Data.Content.Replace("<!--[STYLES]-->"
                                                                  , string.Format(@"{0}"
                                                                                  , strStyles));
                layout.Data.Content = layout.Data.Content.Replace("<!--[SCRIPTS]-->"
                                                                  , string.Format(@"{0}"
                                                                                  , strScripts));

                layout.Data.SaveModel(true, _context, _transaction);
            }

            return(result);
        }
Example #7
0
 public static string GetAssetFolder(string culture)
 {
     return($"/{SioConstants.Folder.FileFolder}/{SioConstants.Folder.TemplatesAssetFolder}/{SioService.GetConfig<string>(SioConstants.ConfigurationKeyword.ThemeFolder, culture)}");
 }
Example #8
0
        public override async Task <RepositoryResponse <bool> > SaveSubModelsAsync(SioTheme parent, SioCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            RepositoryResponse <bool> result = new RepositoryResponse <bool>()
            {
                IsSucceed = true
            };

            if (TemplateAsset.Content != null || TemplateAsset.FileStream != null)
            {
                TemplateAsset.FileFolder = $"Import/Themes/{DateTime.UtcNow.ToShortDateString()}/{Name}";
                ImportTheme(_context, _transaction);
            }
            if (Asset.Content != null || Asset.FileStream != null)
            {
                Asset.FileFolder = AssetFolder;
                Asset.Filename   = "assets";
                string fullPath = CommonHelper.GetFullPath(new string[] {
                    SioConstants.Folder.WebRootPath,
                    Asset.FileFolder
                });
                FileRepository.Instance.EmptyFolder(fullPath);
                var isSaved = FileRepository.Instance.SaveWebFile(Asset);
                result.IsSucceed = isSaved;
                if (isSaved)
                {
                    result.IsSucceed = FileRepository.Instance.UnZipFile(Asset);
                    if (!result.IsSucceed)
                    {
                        result.Errors.Add("Cannot unzip file");
                    }
                }
                else
                {
                    result.Errors.Add("Cannot saved asset file");
                }
            }
            if (Id == 0 && (TemplateAsset.Content == null && TemplateAsset.FileStream == null))
            {
                string defaultFolder = CommonHelper.GetFullPath(new string[] {
                    SioConstants.Folder.TemplatesFolder,
                    SioService.GetConfig <string>(SioConstants.ConfigurationKeyword.DefaultTemplateFolder)
                });
                bool copyResult = FileRepository.Instance.CopyDirectory(defaultFolder, TemplateFolder);

                var files = FileRepository.Instance.GetFilesWithContent(TemplateFolder);
                //TODO: Create default asset
                foreach (var file in files)
                {
                    SioTemplates.InitViewModel template = new SioTemplates.InitViewModel(
                        new SioTemplate()
                    {
                        FileFolder      = file.FileFolder,
                        FileName        = file.Filename,
                        Content         = file.Content,
                        Extension       = file.Extension,
                        CreatedDateTime = DateTime.UtcNow,
                        LastModified    = DateTime.UtcNow,
                        ThemeId         = Model.Id,
                        ThemeName       = Model.Name,
                        FolderType      = file.FolderName,
                        ModifiedBy      = CreatedBy
                    }, _context, _transaction);
                    var saveResult = template.SaveModel(true, _context, _transaction);
                    result.IsSucceed = result.IsSucceed && saveResult.IsSucceed;
                    if (!saveResult.IsSucceed)
                    {
                        result.Exception = saveResult.Exception;
                        result.Errors.AddRange(saveResult.Errors);
                        break;
                    }
                }
            }

            // Actived Theme
            if (IsActived)
            {
                SystemConfigurationViewModel config = (await SystemConfigurationViewModel.Repository.GetSingleModelAsync(
                                                           c => c.Keyword == SioConstants.ConfigurationKeyword.ThemeName && c.Specificulture == Specificulture
                                                           , _context, _transaction)).Data;
                if (config == null)
                {
                    config = new SystemConfigurationViewModel()
                    {
                        Keyword        = SioConstants.ConfigurationKeyword.ThemeName,
                        Specificulture = Specificulture,
                        Category       = "Site",
                        DataType       = SioDataType.Text,
                        Description    = "Cms Theme",
                        Value          = Name
                    };
                }
                else
                {
                    config.Value = Name;
                }

                var saveConfigResult = await config.SaveModelAsync(false, _context, _transaction);

                if (!saveConfigResult.IsSucceed)
                {
                    Errors.AddRange(saveConfigResult.Errors);
                }
                result.IsSucceed = result.IsSucceed && saveConfigResult.IsSucceed;

                SystemConfigurationViewModel configId = (await SystemConfigurationViewModel.Repository.GetSingleModelAsync(
                                                             c => c.Keyword == SioConstants.ConfigurationKeyword.ThemeId && c.Specificulture == Specificulture, _context, _transaction)).Data;
                if (configId == null)
                {
                    configId = new SystemConfigurationViewModel()
                    {
                        Keyword        = SioConstants.ConfigurationKeyword.ThemeId,
                        Specificulture = Specificulture,
                        Category       = "Site",
                        DataType       = SioDataType.Text,
                        Description    = "Cms Theme Id",
                        Value          = Model.Id.ToString()
                    };
                }
                else
                {
                    configId.Value = Model.Id.ToString();
                }
                var saveResult = await configId.SaveModelAsync(false, _context, _transaction);

                if (!saveResult.IsSucceed)
                {
                    Errors.AddRange(saveResult.Errors);
                }
                result.IsSucceed = result.IsSucceed && saveResult.IsSucceed;
            }

            if (Asset.Content != null || Asset.FileStream != null)
            {
                var           files     = FileRepository.Instance.GetWebFiles(AssetFolder);
                StringBuilder strStyles = new StringBuilder();

                foreach (var css in files.Where(f => f.Extension == ".css"))
                {
                    strStyles.Append($"   <link href='{css.FileFolder}/{css.Filename}{css.Extension}' rel='stylesheet'/>");
                }
                StringBuilder strScripts = new StringBuilder();
                foreach (var js in files.Where(f => f.Extension == ".js"))
                {
                    strScripts.Append($"  <script src='{js.FileFolder}/{js.Filename}{js.Extension}'></script>");
                }
                var layout = SioTemplates.InitViewModel.Repository.GetSingleModel(
                    t => t.FileName == "_Layout" && t.ThemeId == Model.Id
                    , _context, _transaction);
                layout.Data.Content = layout.Data.Content.Replace("<!--[STYLES]-->"
                                                                  , string.Format(@"{0}"
                                                                                  , strStyles));
                layout.Data.Content = layout.Data.Content.Replace("<!--[SCRIPTS]-->"
                                                                  , string.Format(@"{0}"
                                                                                  , strScripts));

                await layout.Data.SaveModelAsync(true, _context, _transaction);
            }

            return(result);
        }
        public override void ExpandView(SioCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            this.View = SioTemplates.ReadViewModel.GetTemplateByPath(Template, Specificulture, _context, _transaction).Data;

            var getDataResult = SioModuleDatas.ReadViewModel.Repository
                                .GetModelListBy(m => m.ModuleId == Id && m.Specificulture == Specificulture
                                                , SioService.GetConfig <string>(SioConstants.ConfigurationKeyword.OrderBy), 0
                                                , null, null
                                                , _context, _transaction);

            if (getDataResult.IsSucceed)
            {
                getDataResult.Data.JsonItems = new List <JObject>();
                getDataResult.Data.Items.ForEach(d => getDataResult.Data.JsonItems.Add(d.JItem));
                Data = getDataResult.Data;
            }

            var getArticles = SioModuleArticles.ReadViewModel.Repository.GetModelListBy(n => n.ModuleId == Id && n.Specificulture == Specificulture
                                                                                        , SioService.GetConfig <string>(SioConstants.ConfigurationKeyword.OrderBy), 0
                                                                                        , 4, 0
                                                                                        , _context: _context, _transaction: _transaction
                                                                                        );

            if (getArticles.IsSucceed)
            {
                Articles = getArticles.Data;
            }

            var getProducts = SioModuleProducts.ReadViewModel.Repository.GetModelListBy(
                m => m.ModuleId == Id && m.Specificulture == Specificulture
                , SioService.GetConfig <string>(SioConstants.ConfigurationKeyword.OrderBy), 0
                , null, null
                , _context: _context, _transaction: _transaction
                );

            if (getProducts.IsSucceed)
            {
                Products = getProducts.Data;
            }
        }
Example #10
0
        public override void ExpandView(SioCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            if (Id == 0)
            {
                ExtraFields = SioService.GetConfig <string>("DefaultArticleAttr");
            }
            Cultures   = LoadCultures(Specificulture, _context, _transaction);
            UrlAliases = GetAliases(_context, _transaction);
            if (!string.IsNullOrEmpty(this.Tags))
            {
                ListTag = JArray.Parse(this.Tags);
            }

            // Parsing Extra Properties fields
            Columns = new List <ModuleFieldViewModel>();
            JArray arrField = !string.IsNullOrEmpty(ExtraFields) ? JArray.Parse(ExtraFields) : new JArray();

            foreach (var field in arrField)
            {
                ModuleFieldViewModel thisField = new ModuleFieldViewModel()
                {
                    Name       = CommonHelper.ParseJsonPropertyName(field["name"].ToString()),
                    Title      = field["title"]?.ToString(),
                    Options    = field["options"] != null ? field["options"].Value <JArray>() : new JArray(),
                    Priority   = field["priority"] != null ? field["priority"].Value <int>() : 0,
                    DataType   = (SioDataType)(int)field["dataType"],
                    Width      = field["width"] != null ? field["width"].Value <int>() : 3,
                    IsUnique   = field["isUnique"] != null ? field["isUnique"].Value <bool>() : true,
                    IsRequired = field["isRequired"] != null ? field["isRequired"].Value <bool>() : true,
                    IsDisplay  = field["isDisplay"] != null ? field["isDisplay"].Value <bool>() : true,
                    IsSelect   = field["isSelect"] != null ? field["isSelect"].Value <bool>() : false,
                    IsGroupBy  = field["isGroupBy"] != null ? field["isGroupBy"].Value <bool>() : false,
                };
                Columns.Add(thisField);
            }

            // Parsing Extra Properties value
            Properties = new List <ExtraProperty>();

            if (!string.IsNullOrEmpty(ExtraProperties))
            {
                JArray arr = JArray.Parse(ExtraProperties);
                foreach (JToken item in arr)
                {
                    Properties.Add(item.ToObject <ExtraProperty>());
                }
            }
            //Get Templates
            this.Templates = this.Templates ?? SioTemplates.UpdateViewModel.Repository.GetModelListBy(
                t => t.Theme.Id == ActivedTheme && t.FolderType == this.TemplateFolderType).Data;
            View = SioTemplates.UpdateViewModel.GetTemplateByPath(Template, Specificulture, SioEnums.EnumTemplateFolder.Articles, _context, _transaction);

            this.Template = CommonHelper.GetFullPath(new string[]
            {
                this.View?.FileFolder
                , this.View?.FileName
            });

            var getPageArticle = SioPageArticles.ReadViewModel.GetPageArticleNavAsync(Id, Specificulture, _context, _transaction);

            if (getPageArticle.IsSucceed)
            {
                this.Pages = getPageArticle.Data;
                this.Pages.ForEach(c =>
                {
                    c.IsActived = SioPageArticles.ReadViewModel.Repository.CheckIsExists(n => n.CategoryId == c.CategoryId && n.ArticleId == Id, _context, _transaction);
                });
            }

            var getModuleArticle = SioModuleArticles.ReadViewModel.GetModuleArticleNavAsync(Id, Specificulture, _context, _transaction);

            if (getModuleArticle.IsSucceed)
            {
                this.Modules = getModuleArticle.Data;
                this.Modules.ForEach(c =>
                {
                    c.IsActived = SioModuleArticles.ReadViewModel.Repository.CheckIsExists(n => n.ModuleId == c.ModuleId && n.ArticleId == Id, _context, _transaction);
                });
            }
            var otherModules = SioModules.ReadListItemViewModel.Repository.GetModelListBy(
                m => (m.Type == (int)SioEnums.SioModuleType.Content || m.Type == (int)SioEnums.SioModuleType.ListArticle) &&
                m.Specificulture == Specificulture &&
                !Modules.Any(n => n.ModuleId == m.Id && n.Specificulture == m.Specificulture)
                , "CreatedDateTime", 1, null, 0, _context, _transaction);

            foreach (var item in otherModules.Data.Items)
            {
                Modules.Add(new SioModuleArticles.ReadViewModel()
                {
                    ModuleId    = item.Id,
                    Image       = item.Image,
                    ArticleId   = Id,
                    Description = Title
                });
            }

            // Medias
            var getArticleMedia = SioArticleMedias.ReadViewModel.Repository.GetModelListBy(n => n.ArticleId == Id && n.Specificulture == Specificulture, _context, _transaction);

            if (getArticleMedia.IsSucceed)
            {
                MediaNavs = getArticleMedia.Data.OrderBy(p => p.Priority).ToList();
                MediaNavs.ForEach(n => n.IsActived = true);
            }
            // Modules
            var getArticleModule = SioArticleModules.ReadViewModel.Repository.GetModelListBy(
                n => n.ArticleId == Id && n.Specificulture == Specificulture, _context, _transaction);

            if (getArticleModule.IsSucceed)
            {
                ModuleNavs = getArticleModule.Data.OrderBy(p => p.Priority).ToList();
                foreach (var item in ModuleNavs)
                {
                    item.IsActived = true;
                    item.Module.LoadData(articleId: Id, _context: _context, _transaction: _transaction);
                }
            }
            var otherModuleNavs = SioModules.ReadMvcViewModel.Repository.GetModelListBy(
                m => (m.Type == (int)SioEnums.SioModuleType.SubArticle) && m.Specificulture == Specificulture &&
                !ModuleNavs.Any(n => n.ModuleId == m.Id), "CreatedDateTime", 1, null, 0, _context, _transaction);

            foreach (var item in otherModuleNavs.Data.Items)
            {
                item.LoadData(articleId: Id, _context: _context, _transaction: _transaction);
                ModuleNavs.Add(new SioArticleModules.ReadViewModel()
                {
                    ModuleId    = item.Id,
                    Image       = item.Image,
                    ArticleId   = Id,
                    Description = item.Title,
                    Module      = item
                });
            }

            // Related Articles
            ArticleNavs = GetRelated(_context, _transaction);
            var otherArticles = SioArticles.ReadListItemViewModel.Repository.GetModelListBy(
                m => m.Id != Id && m.Specificulture == Specificulture &&
                !ArticleNavs.Any(n => n.SourceId == Id)
                , "CreatedDateTime", 1, 10, 0, _context, _transaction);

            foreach (var item in otherArticles.Data.Items)
            {
                ArticleNavs.Add(new SioArticleArticles.ReadViewModel()
                {
                    SourceId      = Id,
                    Image         = item.ImageUrl,
                    DestinationId = item.Id,
                    Description   = item.Title
                });
            }
        }
Example #11
0
        public void LoadData(int?pageSize             = null, int?pageIndex = null
                             , SioCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            UnitOfWorkHelper <SioCmsContext> .InitTransaction(_context, _transaction, out SioCmsContext context, out IDbContextTransaction transaction, out bool isRoot);

            try
            {
                pageSize  = pageSize > 0 ? pageSize : PageSize;
                pageIndex = pageIndex ?? 0;
                Expression <Func <SioPageModule, bool> >  dataExp    = null;
                Expression <Func <SioPageArticle, bool> > articleExp = null;
                Expression <Func <SioPageProduct, bool> > productExp = null;
                foreach (var item in Modules)
                {
                    item.Module.LoadData(pageSize: pageSize, pageIndex: pageIndex, _context: context, _transaction: transaction);
                }
                switch (Type)
                {
                case SioPageType.ListArticle:
                    articleExp = n => n.CategoryId == Id && n.Specificulture == Specificulture;
                    break;

                case SioPageType.ListProduct:
                    productExp = n => n.CategoryId == Id && n.Specificulture == Specificulture;
                    break;

                default:
                    dataExp    = m => m.CategoryId == Id && m.Specificulture == Specificulture;
                    articleExp = n => n.CategoryId == Id && n.Specificulture == Specificulture;
                    productExp = m => m.CategoryId == Id && m.Specificulture == Specificulture;
                    break;
                }

                if (articleExp != null)
                {
                    var getArticles = SioPageArticles.ReadViewModel.Repository
                                      .GetModelListBy(articleExp
                                                      , SioService.GetConfig <string>(SioConstants.ConfigurationKeyword.OrderBy), 0
                                                      , pageSize, pageIndex
                                                      , _context: context, _transaction: transaction);
                    if (getArticles.IsSucceed)
                    {
                        Articles = getArticles.Data;
                    }
                }
                if (productExp != null)
                {
                    var getProducts = SioPageProducts.ReadViewModel.Repository
                                      .GetModelListBy(productExp
                                                      , SioService.GetConfig <string>(SioConstants.ConfigurationKeyword.OrderBy), 0
                                                      , pageSize, pageIndex
                                                      , _context: context, _transaction: transaction);
                    if (getProducts.IsSucceed)
                    {
                        Products = getProducts.Data;
                    }
                }
            }
            catch (Exception ex)
            {
                UnitOfWorkHelper <SioCmsContext> .HandleException <PaginationModel <ReadMvcViewModel> >(ex, isRoot, transaction);
            }
            finally
            {
                if (isRoot)
                {
                    //if current Context is Root
                    context.Dispose();
                }
            }
        }
Example #12
0
        public void LoadData(int?articleId            = null, int?productId = null, int?categoryId = null
                             , int?pageSize           = null, int?pageIndex = 0
                             , SioCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            UnitOfWorkHelper <SioCmsContext> .InitTransaction(_context, _transaction, out SioCmsContext context, out IDbContextTransaction transaction, out bool isRoot);

            try
            {
                pageSize  = pageSize > 0 ? PageSize : PageSize;
                pageIndex = pageIndex ?? 0;
                Expression <Func <SioModuleData, bool> >    dataExp    = null;
                Expression <Func <SioModuleArticle, bool> > articleExp = null;
                Expression <Func <SioModuleProduct, bool> > productExp = null;
                switch (Type)
                {
                case SioModuleType.Content:
                case SioModuleType.Data:
                    dataExp = m => m.ModuleId == Id && m.Specificulture == Specificulture;
                    //articleExp = n => n.ModuleId == Id && n.Specificulture == Specificulture;
                    //productExp = m => m.ModuleId == Id && m.Specificulture == Specificulture;
                    break;

                case SioModuleType.SubPage:
                    dataExp    = m => m.ModuleId == Id && m.Specificulture == Specificulture && (m.CategoryId == categoryId);
                    articleExp = n => n.ModuleId == Id && n.Specificulture == Specificulture;
                    productExp = m => m.ModuleId == Id && m.Specificulture == Specificulture;
                    break;

                case SioModuleType.SubArticle:
                    dataExp = m => m.ModuleId == Id && m.Specificulture == Specificulture && (m.ArticleId == articleId);
                    break;

                case SioModuleType.SubProduct:
                    dataExp = m => m.ModuleId == Id && m.Specificulture == Specificulture && (m.ProductId == productId);
                    break;

                case SioModuleType.ListArticle:
                    articleExp = n => n.ModuleId == Id && n.Specificulture == Specificulture;
                    break;

                case SioModuleType.ListProduct:
                    productExp = n => n.ModuleId == Id && n.Specificulture == Specificulture;
                    break;

                default:
                    dataExp    = m => m.ModuleId == Id && m.Specificulture == Specificulture;
                    articleExp = n => n.ModuleId == Id && n.Specificulture == Specificulture;
                    productExp = m => m.ModuleId == Id && m.Specificulture == Specificulture;
                    break;
                }

                if (dataExp != null)
                {
                    var getDataResult = SioModuleDatas.ReadViewModel.Repository
                                        .GetModelListBy(
                        dataExp
                        , SioService.GetConfig <string>(SioConstants.ConfigurationKeyword.OrderBy), 0
                        , pageSize, pageIndex
                        , _context: context, _transaction: transaction);
                    if (getDataResult.IsSucceed)
                    {
                        getDataResult.Data.JsonItems = new List <JObject>();
                        getDataResult.Data.Items.ForEach(d => getDataResult.Data.JsonItems.Add(d.JItem));
                        Data = getDataResult.Data;
                    }
                }
                if (articleExp != null)
                {
                    var getArticles = SioModuleArticles.ReadViewModel.Repository
                                      .GetModelListBy(articleExp
                                                      , SioService.GetConfig <string>(SioConstants.ConfigurationKeyword.OrderBy), 0
                                                      , pageSize, pageIndex
                                                      , _context: context, _transaction: transaction);
                    if (getArticles.IsSucceed)
                    {
                        Articles = getArticles.Data;
                    }
                }
                if (productExp != null)
                {
                    var getProducts = SioModuleProducts.ReadViewModel.Repository
                                      .GetModelListBy(productExp
                                                      , SioService.GetConfig <string>(SioConstants.ConfigurationKeyword.OrderBy), 0
                                                      , PageSize, pageIndex
                                                      , _context: context, _transaction: transaction);
                    if (getProducts.IsSucceed)
                    {
                        Products = getProducts.Data;
                    }
                }
            }
            catch (Exception ex)
            {
                UnitOfWorkHelper <SioCmsContext> .HandleException <PaginationModel <ReadMvcViewModel> >(ex, isRoot, transaction);
            }
            finally
            {
                if (isRoot)
                {
                    //if current Context is Root
                    context.Dispose();
                }
            }
        }
Example #13
0
        async System.Threading.Tasks.Task <IActionResult> ArticleViewAsync(int id, string seoName)
        {
            ViewData["TopPages"]    = GetCategory(CatePosition.Nav, seoName);
            ViewData["HeaderPages"] = GetCategory(CatePosition.Top, seoName);
            ViewData["FooterPages"] = GetCategory(CatePosition.Footer, seoName);
            ViewData["LeftPages"]   = GetCategory(CatePosition.Left, seoName);
            var getArticle = new RepositoryResponse <Lib.ViewModels.SioArticles.ReadMvcViewModel>();

            var cacheKey = $"article_{_culture}_{seoName}";

            var data = _memoryCache.Get <Lib.ViewModels.SioArticles.ReadMvcViewModel>(cacheKey);

            if (data != null && SioService.GetConfig <bool>("IsCache"))
            {
                getArticle.IsSucceed = true;
                getArticle.Data      = data;
            }
            else
            {
                Expression <Func <SioArticle, bool> > predicate;
                if (string.IsNullOrEmpty(seoName))
                {
                    predicate = p =>
                                p.Type == (int)SioPageType.Home &&
                                p.Status == (int)SioContentStatus.Published && p.Specificulture == _culture;
                }
                else
                {
                    predicate = p =>
                                p.Id == id &&
                                p.Status == (int)SioContentStatus.Published &&
                                p.Specificulture == _culture;
                }

                getArticle = await Lib.ViewModels.SioArticles.ReadMvcViewModel.Repository.GetSingleModelAsync(predicate);

                if (getArticle.IsSucceed)
                {
                    getArticle.Data.DetailsUrl = GenerateDetailsUrl("Article", new { id = getArticle.Data.Id, seoName = getArticle.Data.SeoName });
                    //Generate details url for related articles
                    if (getArticle.Data.ArticleNavs != null && getArticle.Data.ArticleNavs.Count > 0)
                    {
                        getArticle.Data.ArticleNavs.ForEach(n => n.RelatedArticle.DetailsUrl = GenerateDetailsUrl("Article", new { id = n.RelatedArticle.Id, seoName = n.RelatedArticle.SeoName }));
                    }
                    _memoryCache.Set(cacheKey, getArticle.Data);
                }
                if (!SioConstants.cachedKeys.Contains(cacheKey))
                {
                    SioConstants.cachedKeys.Add(cacheKey);
                }
            }

            if (getArticle.IsSucceed)
            {
                ViewData["Title"]                  = getArticle.Data.SeoTitle;
                ViewData["Description"]            = getArticle.Data.SeoDescription;
                ViewData["Keywords"]               = getArticle.Data.SeoKeywords;
                ViewData["Image"]                  = getArticle.Data.ImageUrl;
                getArticle.LastUpdateConfiguration = SioService.GetConfig <DateTime?>("LastUpdateConfiguration");
                return(View(getArticle.Data));
            }
            else
            {
                return(Redirect($"/error/404"));
            }
        }
Example #14
0
        async System.Threading.Tasks.Task <IActionResult> SearchAsync(string keyword)
        {
            string seoName = "search";

            ViewData["TopPages"]    = GetCategory(CatePosition.Nav, seoName);
            ViewData["HeaderPages"] = GetCategory(CatePosition.Top, seoName);
            ViewData["FooterPages"] = GetCategory(CatePosition.Footer, seoName);
            ViewData["LeftPages"]   = GetCategory(CatePosition.Left, seoName);

            int?   pageSize       = SioService.GetConfig <int?>("SearchPageSize");
            string orderBy        = SioService.GetConfig <string>("OrderBy");
            int    orderDirection = SioService.GetConfig <int>("OrderDirection");

            int.TryParse(Request.Query["pageIndex"], out int pageIndex);
            var getPage  = new RepositoryResponse <Lib.ViewModels.SioPages.ReadMvcViewModel>();
            var cacheKey = $"search_{_culture}_{keyword}_{pageSize}_{pageIndex}";
            var data     = _memoryCache.Get <Lib.ViewModels.SioPages.ReadMvcViewModel>(cacheKey);

            if (data != null && SioService.GetConfig <bool>("IsCache"))
            {
                getPage.IsSucceed = true;
                getPage.Data      = data;
            }
            else
            {
                Expression <Func <SioPage, bool> > predicate;

                predicate = p =>
                            p.SeoName == "search" &&
                            p.Status == (int)SioContentStatus.Published && p.Specificulture == _culture;

                getPage = await Lib.ViewModels.SioPages.ReadMvcViewModel.Repository.GetSingleModelAsync(predicate);

                if (getPage.Data != null)
                {
                    getPage.Data.LoadDataByKeyword(keyword, orderBy, orderDirection, pageIndex: pageIndex, pageSize: pageSize);
                }
                _memoryCache.Set(cacheKey, getPage.Data);
                if (!SioConstants.cachedKeys.Contains(cacheKey))
                {
                    SioConstants.cachedKeys.Add(cacheKey);
                }
            }

            if (getPage.IsSucceed)// && getPage.Data.View != null
            {
                GeneratePageDetailsUrls(getPage.Data);
                if (!SioConstants.cachedKeys.Contains(cacheKey))
                {
                    SioConstants.cachedKeys.Add(cacheKey);
                }
                ViewData["Title"]               = getPage.Data.SeoTitle;
                ViewData["Description"]         = getPage.Data.SeoDescription;
                ViewData["Keywords"]            = getPage.Data.SeoKeywords;
                ViewData["Image"]               = getPage.Data.ImageUrl;
                ViewData["PageClass"]           = getPage.Data.CssClass;
                getPage.LastUpdateConfiguration = SioService.GetConfig <DateTime?>("LastUpdateConfiguration");
                return(View(getPage.Data));
            }
            else
            {
                return(Redirect($"/error/404"));
            }
        }
Example #15
0
        public override async Task <RepositoryResponse <bool> > SaveSubModelsAsync(SioCulture parent, SioCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            var result = new RepositoryResponse <bool>()
            {
                IsSucceed = true
            };

            if (Id == 0)
            {
                var getPages = await SioPages.ReadViewModel.Repository.GetModelListByAsync(c => c.Specificulture == SioService.GetConfig <string>(SioConstants.ConfigurationKeyword.DefaultCulture), _context, _transaction);

                if (getPages.IsSucceed)
                {
                    foreach (var p in getPages.Data)
                    {
                        var page = new SioPage()
                        {
                            Specificulture  = Specificulture,
                            Id              = p.Id,
                            Content         = p.Content,
                            CreatedBy       = p.CreatedBy,
                            CreatedDateTime = DateTime.UtcNow,
                            Layout          = p.Layout,
                            CssClass        = p.CssClass,
                            Excerpt         = p.Excerpt,
                            Icon            = p.Icon,
                            Image           = p.Image,
                            Level           = p.Level,
                            ModifiedBy      = p.ModifiedBy,
                            PageSize        = p.PageSize,
                            Priority        = p.Priority,
                            SeoDescription  = p.SeoDescription,
                            SeoKeywords     = p.SeoKeywords,
                            SeoName         = p.SeoName,
                            SeoTitle        = p.SeoTitle,
                            StaticUrl       = p.StaticUrl,
                            Status          = (int)p.Status,
                            Tags            = p.Tags,
                            Template        = p.Template,
                            Title           = p.Title,
                            Type            = (int)p.Type,
                        };
                        _context.Entry(page).State = Microsoft.EntityFrameworkCore.EntityState.Added;
                    }
                }
                var getConfigurations = await SioConfigurations.ReadMvcViewModel.Repository.GetModelListByAsync(c => c.Specificulture == SioService.GetConfig <string>(SioConstants.ConfigurationKeyword.DefaultCulture), _context, _transaction);

                if (getConfigurations.IsSucceed)
                {
                    foreach (var c in getConfigurations.Data)
                    {
                        var cnf = new SioConfiguration()
                        {
                            Keyword        = c.Keyword,
                            Specificulture = Specificulture,
                            Category       = c.Category,
                            DataType       = (int)c.DataType,
                            Description    = c.Description,
                            Priority       = c.Priority,
                            Status         = (int)c.Status,
                            Value          = c.Value
                        };
                        _context.Entry(cnf).State = Microsoft.EntityFrameworkCore.EntityState.Added;
                    }
                }

                var getLanguages = await SioLanguages.ReadMvcViewModel.Repository.GetModelListByAsync(c => c.Specificulture == SioService.GetConfig <string>(SioConstants.ConfigurationKeyword.DefaultCulture), _context, _transaction);

                if (getLanguages.IsSucceed)
                {
                    foreach (var c in getLanguages.Data)
                    {
                        var cnf = new SioLanguage()
                        {
                            Keyword        = c.Keyword,
                            Specificulture = Specificulture,
                            Category       = c.Category,
                            DataType       = (int)c.DataType,
                            Description    = c.Description,
                            Priority       = c.Priority,
                            Status         = (int)c.Status,
                            DefaultValue   = c.DefaultValue
                        };
                        _context.Entry(cnf).State = Microsoft.EntityFrameworkCore.EntityState.Added;
                    }
                }
                _context.SaveChanges();
            }
            return(result);
        }