예제 #1
0
        protected override void ValidateRequest()
        {
            base.ValidateRequest();

            // If this site has not been inited yet
            if (MixService.GetConfig <bool>(MixAppSettingKeywords.IsInit))
            {
                isValid = false;
                if (string.IsNullOrEmpty(MixService.GetConnectionString(MixConstants.CONST_CMS_CONNECTION)))
                {
                    _redirectUrl = $"Init";
                }
                else
                {
                    var status = MixService.GetConfig <string>("InitStatus");
                    _redirectUrl = $"/init/step{status}";
                }
            }
        }
예제 #2
0
 public void LoadPostData(int postId, string specificulture, int? pageSize = null, int? pageIndex = 0
     , MixCmsContext _context = null, IDbContextTransaction _transaction = null)
 {
     var getData = MixRelatedAttributeDatas.UpdateViewModel.Repository
     .GetModelListBy(
         m => m.ParentId == postId.ToString() && m.ParentType == (int)MixEnums.MixAttributeSetDataType.Post && m.Specificulture == specificulture 
         , MixService.GetConfig<string>(MixConstants.ConfigurationKeyword.OrderBy), 0
         , pageSize, pageIndex
         , _context: _context, _transaction: _transaction);
     if (!getData.IsSucceed || getData.Data == null || getData.Data.Items.Count == 0)
     {
         PostData = new PaginationModel<MixRelatedAttributeDatas.UpdateViewModel>() { TotalItems = 1 };
         //PostData.Items.Add(new MixPostAttributeDatas.UpdateViewModel(Id, Attributes));
     }
     else
     {
         PostData = getData.Data;
     }
 }
예제 #3
0
        protected async System.Threading.Tasks.Task <IActionResult> Page(int pageId)
        {
            // Home Page
            int?   pageSize       = MixService.GetConfig <int?>("TagPageSize");
            string orderBy        = MixService.GetConfig <string>("OrderBy");
            int    orderDirection = MixService.GetConfig <int>("OrderDirection");

            int.TryParse(Request.Query["page"], out int page);
            RepositoryResponse <Lib.ViewModels.MixPages.ReadMvcViewModel> getPage = null;

            Expression <Func <MixPage, bool> > predicate;

            predicate = p =>
                        p.Id == pageId &&
                        p.Status == MixContentStatus.Published && p.Specificulture == culture;

            getPage = await Lib.ViewModels.MixPages.ReadMvcViewModel.Repository.GetFirstModelAsync(predicate);

            if (getPage.IsSucceed)
            {
                getPage.Data.LoadData(pageIndex: page - 1, pageSize: pageSize);
                GeneratePageDetailsUrls(getPage.Data);
            }

            if (getPage.IsSucceed)
            {
                ViewData["Title"]       = getPage.Data.SeoTitle;
                ViewData["Description"] = getPage.Data.SeoDescription;
                ViewData["Keywords"]    = getPage.Data.SeoKeywords;
                ViewData["Image"]       = getPage.Data.ImageUrl;
                ViewData["Layout"]      = getPage.Data.Layout ?? "Masters/_Layout";
                ViewData["BodyClass"]   = getPage.Data.CssClass;
                ViewData["ViewMode"]    = MixMvcViewMode.Page;

                ViewBag.viewMode = MixMvcViewMode.Page;
                getPage.LastUpdateConfiguration = MixService.GetConfig <DateTime?>("LastUpdateConfiguration");
                return(View(getPage.Data));
            }
            else
            {
                return(Redirect($"/{culture}/404"));
            }
        }
예제 #4
0
        public static async System.Threading.Tasks.Task <RepositoryResponse <PaginationModel <MixPostAttributeDatas.UpdateViewModel> > > LoadPostDataAsync(int postId, string specificulture, int?pageSize = null, int?pageIndex = 0
                                                                                                                                                           , MixCmsContext _context = null, IDbContextTransaction _transaction   = null)
        {
            Expression <Func <MixPostAttributeData, bool> > dataExp = null;

            dataExp = m => m.PostId == postId && m.Specificulture == specificulture && (m.PostId == postId);
            var getDataResult = await MixPostAttributeDatas.UpdateViewModel.Repository
                                .GetModelListByAsync(
                dataExp
                , MixService.GetConfig <string>(MixConstants.ConfigurationKeyword.OrderBy), 0
                , pageSize, pageIndex, null, null
                , _context : _context, _transaction : _transaction);

            if (getDataResult.Data.TotalItems == 0)
            {
                getDataResult.Data.Items.Add(new MixPostAttributeDatas.UpdateViewModel());
            }
            return(getDataResult);
        }
예제 #5
0
 public async System.Threading.Tasks.Task <IActionResult> Index(string culture, string seoName)
 {
     if (MixService.GetConfig <bool>("IsInit"))
     {
         //Go to landing page
         return(await PageAsync(seoName));
     }
     else
     {
         if (string.IsNullOrEmpty(MixService.GetConnectionString(MixConstants.CONST_CMS_CONNECTION)))
         {
             return(Redirect("Init"));
         }
         else
         {
             return(Redirect($"/init/step2"));
         }
     }
 }
예제 #6
0
        private async Task <AccessTokenViewModel> GenerateAccessTokenAsync(ApplicationUser user, bool isRemember)
        {
            var    dtIssued              = DateTime.UtcNow;
            var    dtExpired             = dtIssued.AddMinutes(MixService.GetAuthConfig <int>("CookieExpiration"));
            var    dtRefreshTokenExpired = dtIssued.AddMinutes(MixService.GetAuthConfig <int>("RefreshTokenExpiration"));
            string refreshTokenId        = string.Empty;
            string refreshToken          = string.Empty;

            if (isRemember)
            {
                refreshToken = Guid.NewGuid().ToString();
                RefreshTokenViewModel vmRefreshToken = new RefreshTokenViewModel(
                    new RefreshTokens()
                {
                    Id        = refreshToken,
                    Email     = user.Email,
                    IssuedUtc = dtIssued,
                    ClientId  = MixService.GetAuthConfig <string>("Audience"),
                    Username  = user.UserName,
                    //Subject = SWCmsConstants.AuthConfiguration.Audience,
                    ExpiresUtc = dtRefreshTokenExpired
                });

                var saveRefreshTokenResult = await vmRefreshToken.SaveModelAsync();

                refreshTokenId = saveRefreshTokenResult.Data?.Id;
            }

            AccessTokenViewModel token = new AccessTokenViewModel()
            {
                Access_token  = await GenerateTokenAsync(user, dtExpired, refreshToken),
                Refresh_token = refreshTokenId,
                Token_type    = MixService.GetAuthConfig <string>("TokenType"),
                Expires_in    = MixService.GetAuthConfig <int>("CookieExpiration"),
                //UserData = user,
                Issued  = dtIssued,
                Expires = dtExpired,
                LastUpdateConfiguration = MixService.GetConfig <DateTime?>("LastUpdateConfiguration")
            };

            return(token);
        }
예제 #7
0
        public static IApplicationBuilder UseMixRoutes(this IApplicationBuilder app)
        {
            if (MixService.GetConfig <bool>("IsRewrite"))
            {
                using (StreamReader apacheModRewriteStreamReader =
                           File.OpenText("ApacheModRewrite.txt"))
                    using (StreamReader iisUrlRewriteStreamReader =
                               File.OpenText("IISUrlRewrite.xml"))
                    {
                        var options = new RewriteOptions()
                                      .AddRedirect("redirect-rule/(.*)", "redirected/$1")
                                      .AddRewrite(@"^rewrite-rule/(\d+)/(\d+)", "rewritten?var1=$1&var2=$2",
                                                  skipRemainingRules: true)
                                      .AddApacheModRewrite(apacheModRewriteStreamReader)
                                      .AddIISUrlRewrite(iisUrlRewriteStreamReader)
                                      .Add(MethodRules.RedirectXMLRequests);
                        //.Add(new RedirectImageRequests(".png", "/png-images"))
                        //.Add(new RedirectImageRequests(".jpg", "/jpg-images"));

                        app.UseRewriter(options);
                    }
                //    app.Run(context => context.Response.WriteAsync(
                //$"Rewritten or Redirected Url: " +
                //$"{context.Request.Path + context.Request.QueryString}"));
            }
            app.UseEndpoints(routes =>
            {
                routes.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{alias}");
                routes.MapControllerRoute(
                    name: "page",
                    pattern: "{controller=Page}/{culture=" + MixService.GetConfig <string>(MixConstants.ConfigurationKeyword.DefaultCulture) + "}/{seoName}");
                routes.MapControllerRoute(
                    name: "file",
                    pattern: "{culture=" + MixService.GetConfig <string>(MixConstants.ConfigurationKeyword.DefaultCulture) + "}/portal/file");
                routes.MapControllerRoute(
                    name: "post",
                    pattern: "{culture=" + MixService.GetConfig <string>(MixConstants.ConfigurationKeyword.DefaultCulture) + "}/post/{id}/{seoName}");
            });
            return(app);
        }
예제 #8
0
        public async System.Threading.Tasks.Task <IActionResult> Page(
            string culture, string seoName)
        {
            if (_forbidden)
            {
                return(Redirect($"/error/403"));
            }
            if (MixService.GetConfig <bool>("IsMaintenance"))
            {
                return(await PageAsync("maintenance"));
            }

            if (MixService.GetConfig <bool>("IsInit"))
            {
                //Go to landing page
                return(await PageAsync(seoName));
            }
            else
            {
                var initStatus = MixService.GetConfig <int>("InitStatus");
                switch (initStatus)
                {
                case 0:
                    return(Redirect("Init"));

                case 1:
                    return(Redirect($"/init/step2"));

                case 2:
                    return(Redirect($"/init/step3"));

                case 3:
                    return(Redirect($"/init/step4"));

                case 4:
                    return(Redirect($"/init/step5"));

                default:
                    return(Error());
                }
            }
        }
예제 #9
0
        public static IServiceCollection AddMixScheduler(this IServiceCollection services, IConfiguration configuration)
        {
            // base configuration from appsettings.json
            services.Configure <QuartzOptions>(configuration.GetSection("Quartz"));

            services.AddQuartz(q =>
            {
                // we could leave DI configuration intact and then jobs need
                // to have public no-arg constructor
                // the MS DI is expected to produce transient job instances
                // this WONT'T work with scoped services like EF Core's DbContext
                q.UseMicrosoftDependencyInjectionJobFactory(options =>
                {
                    // if we don't have the job in DI, allow fallback
                    // to configure via default constructor
                    options.AllowDefaultConstructor = true;
                });

                // or for scoped service support like EF Core DbContext
                q.UseMicrosoftDependencyInjectionScopedJobFactory();

                // these are the defaults
                q.UseSimpleTypeLoader();
                q.UseInMemoryStore();
                q.UseDefaultThreadPool(tp =>
                {
                    tp.MaxConcurrency = 10;
                });

                if (!MixService.GetConfig <bool>(MixAppSettingKeywords.IsInit))
                {
                    q.AddMixJobsAsync().GetAwaiter().GetResult();
                }
            });
            // ASP.NET Core hosting
            services.AddQuartzServer(options =>
            {
                // when shutting down we want jobs to complete gracefully
                options.WaitForJobsToComplete = true;
            });
            return(services);
        }
예제 #10
0
        protected async System.Threading.Tasks.Task <IActionResult> Module(int id)
        {
            // Home Page
            int?   pageSize       = MixService.GetConfig <int?>("TagPageSize");
            string orderBy        = MixService.GetConfig <string>("OrderBy");
            int    orderDirection = MixService.GetConfig <int>("OrderDirection");

            int.TryParse(Request.Query["page"], out int page);
            RepositoryResponse <Lib.ViewModels.MixModules.ReadMvcViewModel> getData = null;

            Expression <Func <MixModule, bool> > predicate;

            predicate = p =>
                        p.Id == id &&
                        p.Status == MixContentStatus.Published && p.Specificulture == culture;

            getData = await Lib.ViewModels.MixModules.ReadMvcViewModel.Repository.GetFirstModelAsync(predicate);

            if (getData.IsSucceed)
            {
                getData.Data.LoadData(pageIndex: page - 1, pageSize: pageSize);
                getData.Data.DetailsUrl = GenerateDetailsUrl(
                    new { culture = culture, seoName = getData.Data.Name }
                    );
                GenerateDetailsUrls(getData.Data);
                //_ = MixCacheService.SetAsync(cacheKey, getPage);
            }

            if (getData.IsSucceed)
            {
                ViewData["Title"]               = getData.Data.Title;
                ViewData["Description"]         = getData.Data.Description;
                ViewData["Keywords"]            = getData.Data.Title;
                ViewData["Image"]               = getData.Data.ImageUrl;
                getData.LastUpdateConfiguration = MixService.GetConfig <DateTime?>("LastUpdateConfiguration");
                return(View(getData.Data));
            }
            else
            {
                return(await Page("404"));
            }
        }
예제 #11
0
        protected async Task <RepositoryResponse <PaginationModel <TView> > > GetListAsync <TView>(string key, RequestPaging request, Expression <Func <TModel, bool> > predicate = null, TModel model = null)
            where TView : ViewModelBase <TDbContext, TModel, TView>
        {
            RepositoryResponse <PaginationModel <TView> > data = null;

            if (data == null)
            {
                if (predicate != null)
                {
                    data = await DefaultRepository <TDbContext, TModel, TView> .Instance.GetModelListByAsync(
                        predicate, request.OrderBy, request.Direction, request.PageSize, request.PageIndex, null, null);
                }
                else
                {
                    data = await DefaultRepository <TDbContext, TModel, TView> .Instance.GetModelListAsync(request.OrderBy, request.Direction, request.PageSize, request.PageIndex, null, null).ConfigureAwait(false);
                }
            }
            data.LastUpdateConfiguration = MixService.GetConfig <DateTime?>("LastUpdateConfiguration");
            return(data);
        }
예제 #12
0
        //Ref https://github.com/dotnet/efcore/issues/10169
        public override void Dispose()
        {
            var provider = System.Enum.Parse <MixEnums.DatabaseProvider>(MixService.GetConfig <string>(MixConstants.CONST_SETTING_DATABASE_PROVIDER));

            switch (provider)
            {
            case MixEnums.DatabaseProvider.MSSQL:
                SqlConnection.ClearPool((SqlConnection)Database.GetDbConnection());
                break;

            case MixEnums.DatabaseProvider.MySQL:
                MySqlConnection.ClearPool((MySqlConnection)Database.GetDbConnection());
                break;

            case MixEnums.DatabaseProvider.PostgreSQL:
                Npgsql.NpgsqlConnection.ClearPool((Npgsql.NpgsqlConnection)Database.GetDbConnection());
                break;
            }
            base.Dispose();
        }
예제 #13
0
		public override void ExpandView(MixCmsContext _context = null, IDbContextTransaction _transaction = null)
		{
			if (this.get_Id() == 0)
			{
				this.set_ExtraFields(MixService.GetConfig<string>("DefaultPostAttr"));
			}
			this.set_Cultures(this.LoadCultures(this.get_Specificulture(), _context, _transaction));
			this.set_UrlAliases(this.GetAliases(_context, _transaction));
			if (!string.IsNullOrEmpty(this.get_Tags()))
			{
				this.set_ListTag(JArray.Parse(this.get_Tags()));
			}
			this.LoadAttributes(_context, _transaction);
			this.LoadTemplates(_context, _transaction);
			this.LoadParentPage(_context, _transaction);
			this.LoadParentModules(_context, _transaction);
			this.LoadMedias(_context, _transaction);
			this.LoadRelatedPost(_context, _transaction);
			return;
		}
예제 #14
0
 public override MixCmsUser ParseModel(MixCmsContext _context = null, IDbContextTransaction _transaction = null)
 {
     if (MediaFile.FileStream != null)
     {
         MediaFile.FileFolder = CommonHelper.GetFullPath(new[] {
             MixService.GetConfig <string>("UploadFolder"),
             DateTime.UtcNow.ToString("MMM-yyyy")
         });;
         var isSaved = FileRepository.Instance.SaveWebFile(MediaFile);
         if (isSaved)
         {
             Avatar = MediaFile.FullPath;
         }
         else
         {
             IsValid = false;
         }
     }
     return(base.ParseModel(_context, _transaction));
 }
예제 #15
0
        public RepositoryResponse <GlobalSettingsViewModel> Settings()
        {
            var cultures = CommonRepository.Instance.LoadCultures();
            var culture  = cultures.FirstOrDefault(c => c.Specificulture == _lang);
            GlobalSettingsViewModel settings = new GlobalSettingsViewModel()
            {
                Lang      = _lang,
                ThemeId   = MixService.GetConfig <int>(MixConstants.ConfigurationKeyword.ThemeId, _lang),
                Cultures  = cultures,
                PageTypes = Enum.GetNames(typeof(MixPageType)).ToList(),
                Statuses  = Enum.GetNames(typeof(MixContentStatus)).ToList()
            };

            settings.LangIcon = culture?.Icon ?? MixService.GetConfig <string>("Language");
            return(new RepositoryResponse <GlobalSettingsViewModel>()
            {
                IsSucceed = true,
                Data = settings
            });
        }
예제 #16
0
        public static async System.Threading.Tasks.Task <ViewModels.MixPages.ReadMvcViewModel> GetPageAsync(int id, string culture)
        {
            var cacheKey = $"vm_{culture}_page_{id}_mvc";
            RepositoryResponse <ViewModels.MixPages.ReadMvcViewModel> getPage = null;

            if (MixService.GetConfig <bool>("IsCache"))
            {
                getPage = await MixCacheService.GetAsync <RepositoryResponse <ViewModels.MixPages.ReadMvcViewModel> >(cacheKey);
            }
            if (getPage == null)
            {
                getPage = ViewModels.MixPages.ReadMvcViewModel.Repository.GetSingleModel(m => m.Id == id && m.Specificulture == culture);
                if (getPage.IsSucceed)
                {
                    await MixCacheService.SetAsync(cacheKey, getPage);
                }
            }

            return(getPage.Data);
        }
예제 #17
0
        public static async Task <RepositoryResponse <PaginationModel <TView> > > GetPostListByPageId <TView>(
            int pageId
            , string keyword             = null
            , string culture             = null
            , string orderByPropertyName = "CreatedDateTime"
            , Heart.Enums.MixHeartEnums.DisplayDirection direction = Heart.Enums.MixHeartEnums.DisplayDirection.Desc
            , int?pageSize           = null, int?pageIndex = null
            , MixCmsContext _context = null, IDbContextTransaction _transaction = null)
            where TView : ViewModelBase <MixCmsContext, MixPagePost, TView>
        {
            UnitOfWorkHelper <MixCmsContext> .InitTransaction(_context, _transaction, out MixCmsContext context, out IDbContextTransaction transaction, out bool isRoot);

            try
            {
                culture = culture ?? MixService.GetConfig <string>("DefaultCulture");
                var result = await DefaultRepository <MixCmsContext, MixPagePost, TView> .Instance.GetModelListByAsync(
                    m => m.Specificulture == culture && m.PageId == pageId &&
                    (string.IsNullOrEmpty(keyword) ||
                     (EF.Functions.Like(m.MixPost.Title, $"%{keyword}%")) ||
                     (EF.Functions.Like(m.MixPost.Excerpt, $"%{keyword}%")) ||
                     (EF.Functions.Like(m.MixPost.Content, $"%{keyword}%"))
                    )
                    , orderByPropertyName, direction, pageSize, pageIndex
                    , _context : context, _transaction : transaction
                    );

                return(result);
            }
            catch (Exception ex)
            {
                return(UnitOfWorkHelper <MixCmsContext> .HandleException <PaginationModel <TView> >(ex, isRoot, transaction));
            }
            finally
            {
                if (isRoot)
                {
                    //if current Context is Root
                    UnitOfWorkHelper <MixCmsContext> .CloseDbContext(ref context, ref transaction);
                }
            }
        }
예제 #18
0
        /// <summary>
        /// Gets the template by path.
        /// </summary>
        /// <param name="path">The path.</param> Ex: "Pages/_Home"
        /// <returns></returns>
        public static RepositoryResponse <UpdateViewModel> GetTemplateByPath(string path, string culture
                                                                             , MixCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            RepositoryResponse <UpdateViewModel> result = new RepositoryResponse <UpdateViewModel>();

            string[] temp = path?.Split('/');
            if (temp == null || temp.Length < 2)
            {
                result.IsSucceed = false;
                result.Errors.Add("Template Not Found");
            }
            else
            {
                int activeThemeId = MixService.GetConfig <int>(
                    MixAppSettingKeywords.ThemeId, culture);
                string name = temp[1].Split('.')[0];
                result = Repository.GetSingleModel(t => t.FolderType == temp[0] && t.FileName == name && t.ThemeId == activeThemeId
                                                   , _context, _transaction);
            }
            return(result);
        }
예제 #19
0
        public async static Task <RepositoryResponse <PaginationModel <TView> > > GetPostlistByMeta <TView>(

            HttpContext context
            , string culture, string type = MixConstants.AttributeSetName.SYSTEM_TAG
            , string orderByPropertyName  = "CreatedDateTime", Heart.Enums.MixHeartEnums.DisplayDirection direction = MixHeartEnums.DisplayDirection.Desc
            , MixCmsContext _context      = null, IDbContextTransaction _transaction = null)
            where TView : ViewModelBase <MixCmsContext, MixPost, TView>
        {
            int    maxPageSize    = MixService.GetConfig <int>("MaxPageSize");
            string orderBy        = MixService.GetConfig <string>("OrderBy");
            int    orderDirection = MixService.GetConfig <int>("OrderDirection");

            int.TryParse(context.Request.Query["page"], out int page);
            int.TryParse(context.Request.Query["pageSize"], out int pageSize);
            pageSize = (pageSize > 0 && pageSize < maxPageSize) ? pageSize : maxPageSize;
            page     = (page > 0) ? page : 1;

            return(await Mix.Cms.Lib.ViewModels.MixPosts.Helper.GetModelistByMeta <TView>(
                       type, context.Request.Query["keyword"],
                       culture, orderByPropertyName, direction, pageSize, page - 1, _context, _transaction));
        }
예제 #20
0
        protected virtual void ValidateRequest()
        {
            if (!MixService.GetConfig <bool>(MixAppSettingKeywords.IsInit))
            {
                LoadCulture();
            }

            // If IP retricted in appsettings
            if (forbidden)
            {
                isValid      = false;
                _redirectUrl = $"/403";
            }

            // If mode Maintenance enabled in appsettings
            if (MixService.GetConfig <bool>("IsMaintenance") && Request.RouteValues["seoName"].ToString() != "maintenance")
            {
                isValid      = false;
                _redirectUrl = $"/maintenance";
            }
        }
예제 #21
0
        /// <summary>
        /// Gets the template by path.
        /// </summary>
        /// <param name="path">The path.</param> Ex: "Pages/_Home"
        /// <returns></returns>
        public static async Task <RepositoryResponse <ReadViewModel> > GetTemplateByPathAsync(string path, string culture
                                                                                              , MixCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            RepositoryResponse <ReadViewModel> result = new RepositoryResponse <ReadViewModel>();

            string[] temp = path.Split('/');
            if (temp.Length < 2)
            {
                result.IsSucceed = false;
                result.Errors.Add("Template Not Found");
            }
            else
            {
                int activeThemeId = MixService.GetConfig <int>(
                    MixConstants.ConfigurationKeyword.ThemeId, culture);
                string name = temp[1].Split('.')[0];
                result = await Repository.GetSingleModelAsync(t => t.FolderType == temp[0] && t.FileName == name && t.ThemeId == activeThemeId
                                                              , _context, _transaction);
            }
            return(result);
        }
예제 #22
0
				V_1 = Expression.Parameter(Type.GetTypeFromHandle(// 
				// Current member / type: System.Collections.Generic.List`1<Mix.Cms.Lib.ViewModels.Account.NavUserRoleViewModel> Mix.Cms.Lib.ViewModels.Account.MixRegisterViewModel::GetRoleNavs()
				// Exception in: System.Collections.Generic.List<Mix.Cms.Lib.ViewModels.Account.NavUserRoleViewModel> GetRoleNavs()
				// Specified method is not supported.
				// 
				// mailto: [email protected]


		public override MixCmsUser ParseModel(MixCmsContext _context = null, IDbContextTransaction _transaction = null)
		{
			if (this.get_MediaFile().get_FileStream() != null)
			{
				stackVariable8 = this.get_MediaFile();
				stackVariable10 = new string[2];
				stackVariable10[0] = MixService.GetConfig<string>("UploadFolder");
				V_0 = DateTime.get_UtcNow();
				stackVariable10[1] = V_0.ToString("MMM-yyyy");
				stackVariable8.set_FileFolder(CommonHelper.GetFullPath(stackVariable10));
				if (!FileRepository.get_Instance().SaveWebFile(this.get_MediaFile()))
				{
					this.set_IsValid(false);
				}
				else
				{
					this.set_Avatar(this.get_MediaFile().get_FullPath());
				}
			}
			return this.ParseModel(_context, _transaction);
		}
예제 #23
0
        public async Task <ActionResult <UpdateViewModel> > Init(string attributeSetName)
        {
            var getAttrSet = await Lib.ViewModels.MixAttributeSets.ReadViewModel.Repository.GetSingleModelAsync(m => m.Name == attributeSetName);

            if (getAttrSet.IsSucceed)
            {
                FormViewModel result = new FormViewModel()
                {
                    Specificulture   = _lang,
                    AttributeSetId   = getAttrSet.Data.Id,
                    AttributeSetName = getAttrSet.Data.Name,
                    Status           = Enum.Parse <MixEnums.MixContentStatus>(MixService.GetConfig <string>(MixConstants.ConfigurationKeyword.DefaultContentStatus))
                };
                result.ExpandView();
                return(Ok(result));
            }
            else
            {
                return(BadRequest(getAttrSet.Errors));
            }
        }
예제 #24
0
        public static IQueryable <string> GetPostIdsByValue(
            Expression <Func <MixDatabaseDataValue, bool> > valExp,
            MixCmsContext context,
            string culture  = null,
            string postType = MixDatabaseNames.ADDITIONAL_FIELD_POST)
        {
            culture = culture ?? MixService.GetConfig <string>(MixAppSettingKeywords.DefaultCulture);

            var dataIds = context.MixDatabaseDataValue.Where(valExp).Select(m => m.DataId);

            // TODO: Enhance query not using AsEnummerable to get int value
            Expression <Func <MixDatabaseDataAssociation, bool> > relatedExp =
                m => m.Specificulture == culture && dataIds.Any(d => d == m.DataId) &&
                m.ParentType == MixDatabaseParentType.Post;

            var associations = context.MixDatabaseDataAssociation.Where(relatedExp);
            var parentIds    = associations.Select(m => m.ParentId);


            return(parentIds);
        }
예제 #25
0
        protected async Task <RepositoryResponse <TView> > GetSingleAsync <TView>(Expression <Func <TModel, bool> > predicate = null, TModel model = null)
            where TView : ODataViewModelBase <TDbContext, TModel, TView>
        {
            RepositoryResponse <TView> data = null;

            if (predicate != null)
            {
                data = await ODataDefaultRepository <TDbContext, TModel, TView> .Instance.GetSingleModelAsync(predicate);
            }
            else
            {
                data = new RepositoryResponse <TView>()
                {
                    IsSucceed = true,
                    Data      = ODataDefaultRepository <TDbContext, TModel, TView> .Instance.ParseView(model)
                };
            }

            data.LastUpdateConfiguration = MixService.GetConfig <DateTime?>("LastUpdateConfiguration");
            return(data);
        }
예제 #26
0
        public async Task <RepositoryResponse <bool> > CloneAttributeValuesAsync(MixCulture parent, MixCmsContext context, IDbContextTransaction transaction)
        {
            var result = new RepositoryResponse <bool>()
            {
                IsSucceed = true
            };

            try
            {
                var getPages = await DefaultModelRepository <MixCmsContext, MixAttributeSetValue> .Instance.GetModelListByAsync(
                    c => c.Specificulture == MixService.GetConfig <string>(MixAppSettingKeywords.DefaultCulture),
                    context, transaction);

                if (getPages.IsSucceed)
                {
                    foreach (var p in getPages.Data)
                    {
                        if (!context.MixAttributeSetValue.Any(m => m.DataId == p.DataId && m.Specificulture == Specificulture))
                        {
                            p.Id = Guid.NewGuid().ToString();
                            if (!string.IsNullOrEmpty(p.StringValue) && p.StringValue.Contains($"/{p.Specificulture}"))
                            {
                                p.StringValue = p.StringValue.Replace($"/{p.Specificulture}", $"/{Specificulture}");
                            }
                            p.Specificulture       = Specificulture;
                            p.CreatedDateTime      = DateTime.UtcNow;
                            context.Entry(p).State = EntityState.Added;
                        }
                    }
                    await context.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Exception = ex;
                result.Errors.Add(ex.Message);
            }
            return(result);
        }
예제 #27
0
        public override void ExpandView(MixCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            Cultures = LoadCultures(Specificulture, _context, _transaction);
            Cultures.ForEach(c => c.IsSupported = _context.MixModule.Any(m => m.Id == Id && m.Specificulture == c.Specificulture));
            Columns = new List <ModuleFieldViewModel>();
            JArray arrField = !string.IsNullOrEmpty(Fields) ? JArray.Parse(Fields) : 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   = (MixDataType)(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);
            }
            this.Templates = this.Templates ?? MixTemplates.UpdateViewModel.Repository.GetModelListBy(
                t => t.Theme.Name == ActivedTheme && t.FolderType == this.TemplateFolderType).Data;
            int themeId = MixService.GetConfig <int>(MixConstants.ConfigurationKeyword.ThemeId, Specificulture);

            View = MixTemplates.UpdateViewModel.GetTemplateByPath(Template, Specificulture, MixEnums.EnumTemplateFolder.Modules, _context, _transaction);
            if (this.View == null)
            {
                this.View = MixTemplates.UpdateViewModel.GetDefault(EnumTemplateFolder.Modules, Specificulture);
            }
            this.Template = CommonHelper.GetFullPath(new string[]
            {
                this.View?.FileFolder
                , this.View?.FileName
            });
        }
예제 #28
0
        public override void ExpandView(MixCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            if (string.IsNullOrEmpty(Id))
            {
                Status = Status == default ? Enum.Parse <MixEnums.MixContentStatus>(MixService.GetConfig <string>(MixAppSettingKeywords.DefaultContentStatus)) : Status;
            }
            // Related Datas
            DataNavs = MixRelatedAttributeDatas.UpdateViewModel.Repository.GetModelListBy(
                n => n.ParentId == Id && n.ParentType == MixEnums.MixAttributeSetDataType.Set.ToString() && n.Specificulture == Specificulture,
                _context, _transaction).Data;

            Values = MixAttributeSetValues.UpdateViewModel
                     .Repository.GetModelListBy(a => a.DataId == Id && a.Specificulture == Specificulture, _context, _transaction).Data.OrderBy(a => a.Priority).ToList();
            Fields = MixAttributeFields.UpdateViewModel.Repository.GetModelListBy(f => (f.AttributeSetId == AttributeSetId || f.AttributeSetName == AttributeSetName), _context, _transaction).Data;
            foreach (var field in Fields.OrderBy(f => f.Priority))
            {
                var val = Values.FirstOrDefault(v => v.AttributeFieldId == field.Id);
                if (val == null)
                {
                    val = new MixAttributeSetValues.UpdateViewModel(
                        new MixAttributeSetValue()
                    {
                        AttributeFieldId = field.Id
                    }
                        , _context, _transaction)
                    {
                        Field = field,
                        AttributeFieldName = field.Name,
                        StringValue        = field.DefaultValue,
                        Priority           = field.Priority
                    };
                    Values.Add(val);
                }
                val.AttributeSetName   = AttributeSetName;
                val.Priority           = field.Priority;
                val.Field              = field;
                val.DataType           = val.Field.DataType;
                val.AttributeFieldName = val.AttributeFieldName ?? val.Field?.Name;
            }
        }
예제 #29
0
        public override void ExpandView(MixCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            this.View = MixTemplates.ReadViewModel.GetTemplateByPath(Template, Specificulture, _context, _transaction).Data;

            var getDataResult = MixModuleDatas.ReadViewModel.Repository
                                .GetModelListBy(m => m.ModuleId == Id && m.Specificulture == Specificulture
                                                , MixService.GetConfig <string>(MixConstants.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 = MixModuleArticles.ReadViewModel.Repository.GetModelListBy(n => n.ModuleId == Id && n.Specificulture == Specificulture
                                                                                        , MixService.GetConfig <string>(MixConstants.ConfigurationKeyword.OrderBy), 0
                                                                                        , 4, 0
                                                                                        , _context: _context, _transaction: _transaction
                                                                                        );

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

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

            if (getProducts.IsSucceed)
            {
                Products = getProducts.Data;
            }
        }
예제 #30
0
        protected async Task <RepositoryResponse <PaginationModel <TView> > > GetListAsync <TView>(string key, RequestPaging request, Expression <Func <TModel, bool> > predicate = null, TModel model = null)
            where TView : ViewModelBase <TDbContext, TModel, TView>
        {
            var cacheKey = $"api_{_lang}_{typeof(TModel).Name.ToLower()}_list_{key}_{request.Status}_{request.Keyword}_{request.OrderBy}_{request.Direction}_{request.PageSize}_{request.PageIndex}_{request.Query}";
            RepositoryResponse <PaginationModel <TView> > data = null;

            if (MixService.GetConfig <bool>("IsCache"))
            {
                data = await MixCacheService.GetAsync <RepositoryResponse <PaginationModel <TView> > >(cacheKey);
            }

            if (data == null)
            {
                if (predicate != null)
                {
                    data = await DefaultRepository <TDbContext, TModel, TView> .Instance.GetModelListByAsync(
                        predicate, request.OrderBy, request.Direction, request.PageSize, request.PageIndex, null, null);

                    if (data.IsSucceed)
                    {
                        await MixCacheService.SetAsync(cacheKey, data);

                        AlertAsync("Add Cache", 200, cacheKey);
                    }
                }
                else
                {
                    data = await DefaultRepository <TDbContext, TModel, TView> .Instance.GetModelListAsync(request.OrderBy, request.Direction, request.PageSize, request.PageIndex, null, null).ConfigureAwait(false);

                    if (data.IsSucceed)
                    {
                        await MixCacheService.SetAsync(cacheKey, data);

                        AlertAsync("Add Cache", 200, cacheKey);
                    }
                }
            }
            data.LastUpdateConfiguration = MixService.GetConfig <DateTime?>("LastUpdateConfiguration");
            return(data);
        }