public static void IncludeCss(this HtmlHelper helper, string url)
        {
            var webPage     = helper.ViewDataContainer as WebPageBase;
            var virtualPath = webPage == null ? string.Empty : webPage.VirtualPath;

            MaterialCMSApplication.Get <IResourceBundler>().AddCss(virtualPath, url);
        }
예제 #2
0
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var user = base.BindModel(controllerContext, bindingContext) as User;

            IEnumerable <string> roleValues = controllerContext.HttpContext.Request.Params.AllKeys.Where(s => s.StartsWith("Role-"));

            foreach (var value in roleValues)
            {
                string s            = controllerContext.HttpContext.Request[value];
                var    roleSelected = s.Contains("true");
                var    id           = Convert.ToInt32(value.Split('-')[1]);

                var role = Session.Get <UserRole>(id);
                if (MaterialCMSApplication.Get <IRoleService>().IsOnlyAdmin(user) && role.IsAdmin)
                {
                    continue;
                }

                if (roleSelected && !user.Roles.Contains(role))
                {
                    user.Roles.Add(role);
                    role.Users.Add(user);
                }
                else if (!roleSelected && user.Roles.Contains(role))
                {
                    user.Roles.Remove(role);
                    role.Users.Remove(user);
                }
            }
            return(user);
        }
예제 #3
0
        private void SetUpInitialData(InstallModel model, IDatabaseProvider provider)
        {
            var configurator = new NHibernateConfigurator(provider);

            ISessionFactory   sessionFactory   = configurator.CreateSessionFactory();
            ISession          session          = sessionFactory.OpenFilteredSession(CurrentRequestData.CurrentContext);
            IStatelessSession statelessSession = sessionFactory.OpenStatelessSession();
            var kernel = MaterialCMSApplication.Get <IKernel>();

            kernel.Rebind <ISession>().ToMethod(context => session);
            kernel.Rebind <IStatelessSession>().ToMethod(context => statelessSession);
            var site = new Site
            {
                Name      = model.SiteName,
                BaseUrl   = model.SiteUrl,
                CreatedOn = DateTime.UtcNow,
                UpdatedOn = DateTime.UtcNow
            };

            using (ITransaction transaction = statelessSession.BeginTransaction())
            {
                statelessSession.Insert(site);
                transaction.Commit();
            }
            CurrentRequestData.CurrentSite = session.Get <Site>(site.Id);

            kernel.Get <IInitializeDatabase>().Initialize(model);
            kernel.Get <ICreateInitialUser>().Create(model);
            kernel.GetAll <IOnInstallation>()
            .OrderBy(installation => installation.Priority)
            .ForEach(installation => installation.Install(model));
        }
예제 #4
0
        private static List <DocumentMetadata> GetDocumentMetadata()
        {
            var list = new List <DocumentMetadata>();

            foreach (
                Type type in
                TypeHelper.GetAllConcreteMappedClassesAssignableFrom <Webpage>()
                .Where(type => !type.ContainsGenericParameters))
            {
                var types =
                    TypeHelper.GetAllConcreteTypesAssignableFrom(typeof(DocumentMetadataMap <>).MakeGenericType(type));
                if (types.Any())
                {
                    var definition = MaterialCMSApplication.Get(types.First()) as IGetDocumentMetadata;
                    list.Add(definition.Metadata);
                }
                else
                {
                    var definition =
                        MaterialCMSApplication.Get(typeof(DefaultDocumentMetadata <>).MakeGenericType(type)) as
                        IGetDocumentMetadata;
                    list.Add(definition.Metadata);
                }
            }
            return(list.OrderBy(x => x.DisplayOrder).ToList());
        }
 public static void AddAppAdminStylesheets(this HtmlHelper html)
 {
     foreach (var script in MaterialCMSApplication.GetAll <IAppStylesheetList>().SelectMany(appScriptList => appScriptList.AdminStylesheets))
     {
         html.IncludeCss(script);
     }
 }
 public static void AddAppUIScripts(this HtmlHelper html)
 {
     foreach (var script in MaterialCMSApplication.GetAll <IAppScriptList>().SelectMany(appScriptList => appScriptList.UIScripts))
     {
         html.IncludeScript(script);
     }
 }
예제 #7
0
 public MaterialCMSErrorLog(IDictionary config)
 {
     if (CurrentRequestData.DatabaseIsInstalled)
     {
         _session = MaterialCMSApplication.Get <ISessionFactory>()
                    .OpenFilteredSession(CurrentRequestData.CurrentContext);
     }
 }
예제 #8
0
        public static IHtmlString ParseShortcodes(this HtmlHelper htmlHelper, string content)
        {
            var shortcodeParsers = MaterialCMSApplication.GetAll <IShortcodeParser>();

            content = shortcodeParsers.Aggregate(content, (current, shortcodeParser) => shortcodeParser.Parse(htmlHelper, current));

            return(new HtmlString(content));
        }
예제 #9
0
 public static int FormPostingsCount(this Webpage webpage)
 {
     return(MaterialCMSApplication.Get <ISession>()
            .QueryOver <FormPosting>()
            .Where(posting => posting.Webpage != null && posting.Webpage.Id == webpage.Id)
            .Cacheable()
            .RowCount());
 }
예제 #10
0
 public static bool AnyChildren(this Document document)
 {
     return(MaterialCMSApplication.Get <ISession>()
            .QueryOver <Document>()
            .Where(doc => doc.Parent != null && doc.Parent.Id == document.Id)
            .Cacheable()
            .Any());
 }
예제 #11
0
        public static MvcHtmlString Honeypot(this HtmlHelper html)
        {
            var siteSettings = MaterialCMSApplication.Get <SiteSettings>();

            return(siteSettings.HasHoneyPot
                       ? MvcHtmlString.Create(siteSettings.GetHoneypot().ToString())
                       : MvcHtmlString.Empty);
        }
예제 #12
0
        public static IPagedList <TResult> Paged <TResult>(this IQueryable <TResult> queryable, int pageNumber,
                                                           int?pageSize = null)
            where TResult : SystemEntity
        {
            int size = pageSize ?? MaterialCMSApplication.Get <SiteSettings>().DefaultPageSize;

            IQueryable <TResult> cacheable = queryable.Cacheable();

            return(new PagedList <TResult>(cacheable, pageNumber, size));
        }
예제 #13
0
        private bool CanAccessLogic(UserRole userRole, string operation, string typeName = null)
        {
            if (!MaterialCMSApplication.Get <ACLSettings>().ACLEnabled)
            {
                return(false);
            }
            var aclRoles = userRole.ACLRoles;
            var b        = GetKey(operation, typeName);

            return(aclRoles.Any(role => role.Name == b));
        }
예제 #14
0
        public static IPagedList <T> PagedChildren <T>(this Webpage webpage, QueryOver <T> query = null, int pageNum = 1,
                                                       int pageSize = 10) where T : Webpage
        {
            query = query ??
                    QueryOver.Of <T>()
                    .Where(a => a.Parent == webpage && a.Published)
                    .OrderBy(arg => arg.PublishOn)
                    .Desc;

            return(MaterialCMSApplication.Get <ISession>().Paged(query, pageNum, pageSize));
        }
예제 #15
0
        public static void ConfigureAuth(this IAppBuilder app)
        {
            var standardAuthConfigurationService = MaterialCMSApplication.Get <IStandardAuthConfigurationService>();

            standardAuthConfigurationService.ConfigureAuth(app);
            if (CurrentRequestData.DatabaseIsInstalled)
            {
                var authConfigurationService = MaterialCMSApplication.Get <IAuthConfigurationService>();
                authConfigurationService.ConfigureAuth(app);
            }
        }
예제 #16
0
        public static IPagedList <TResult> Paged <TResult>(this IQueryOver <TResult, TResult> queryBase, int pageNumber,
                                                           int?pageSize = null)
            where TResult : SystemEntity
        {
            int size = pageSize ?? MaterialCMSApplication.Get <SiteSettings>().DefaultPageSize;
            IEnumerable <TResult> results = queryBase.Skip((pageNumber - 1) * size).Take(size).Cacheable().List();

            int rowCount = queryBase.Cacheable().RowCount();

            return(new StaticPagedList <TResult>(results, pageNumber, size, rowCount));
        }
예제 #17
0
        public static void EnsureIndexExists <T1, T2>()
            where T1 : SystemEntity
            where T2 : IndexDefinition <T1>
        {
            var service = MaterialCMSApplication.Get <IIndexService>();
            IIndexManagerBase indexManagerBase = service.GetIndexManagerBase(typeof(T2));

            if (!indexManagerBase.IndexExists)
            {
                service.Reindex(indexManagerBase.GetIndexDefinitionType().FullName);
            }
        }
예제 #18
0
        public static IPagedList <T> Paged <T>(this ISession session, QueryOver <T> query, int pageNumber,
                                               int?pageSize = null)
            where T : SystemEntity
        {
            int             size   = pageSize ?? MaterialCMSApplication.Get <SiteSettings>().DefaultPageSize;
            IEnumerable <T> values =
                query.GetExecutableQueryOver(session).Skip((pageNumber - 1) * size).Take(size).Cacheable().List <T>();

            var rowCount = query.GetExecutableQueryOver(session).ToRowCountQuery().SingleOrDefault <int>();

            return(new StaticPagedList <T>(values, pageNumber, size, rowCount));
        }
 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
     if (!CurrentRequestData.DatabaseIsInstalled)
     {
         return;
     }
     if (!string.IsNullOrWhiteSpace(
             filterContext.HttpContext.Request[MaterialCMSApplication.Get <SiteSettings>().HoneypotFieldName]))
     {
         filterContext.Result = new EmptyResult();
     }
 }
 public override IModelBinder GetBinder()
 {
     try
     {
         return(MaterialCMSApplication.Get(BinderType) as IModelBinder);
     }
     catch (Exception ex)
     {
         throw new InvalidOperationException(
                   string.Format("Error instantiating model binder of type {0}", BinderType.AssemblyQualifiedName), ex);
     }
 }
예제 #21
0
        public static bool RequiresSSL(this Webpage webpage, HttpRequestBase request, SiteSettings siteSettings = null)
        {
            if (request.IsLocal)
            {
                return(false);
            }
            siteSettings = siteSettings ?? MaterialCMSApplication.Get <SiteSettings>();
            var isLiveAdmin = CurrentRequestData.CurrentUserIsAdmin && siteSettings.SSLAdmin && siteSettings.SiteIsLive &&
                              !request.IsLocal;

            return(siteSettings.SSLEverywhere || webpage.RequiresSSL || isLiveAdmin);
        }
예제 #22
0
 public static CultureInfo GetUICulture(this User user, CultureInfo defaultCultureInfo = null)
 {
     try
     {
         defaultCultureInfo = defaultCultureInfo ?? MaterialCMSApplication.Get <SiteSettings>().CultureInfo;
         if (user == null || string.IsNullOrWhiteSpace(user.UICulture))
         {
             return(defaultCultureInfo);
         }
         return(CultureInfo.GetCultureInfo(user.UICulture));
     }
     catch
     {
         return(defaultCultureInfo);
     }
 }
예제 #23
0
        public static IEnumerable <ImageSize> GetSizes(this MediaFile file)
        {
            if (!IsImage(file))
            {
                yield break;
            }
            yield return(new ImageSize("Original", file.Size));

            foreach (
                ImageSize imageSize in
                MaterialCMSApplication.Get <MediaSettings>()
                .ImageSizes.Where(size => ImageProcessor.RequiresResize(file.Size, size.Size)))
            {
                imageSize.ActualSize = ImageProcessor.CalculateDimensions(file.Size, imageSize.Size);
                yield return(imageSize);
            }
        }
예제 #24
0
        private static string Get <T>(object queryString, Func <T, string> selector) where T : Webpage, IUniquePage
        {
            var service = MaterialCMSApplication.Get <IUniquePageService>();

            var    processPage = service.GetUniquePage <T>();
            string url         = processPage != null?selector(processPage) : "/";

            if (queryString != null && processPage != null)
            {
                var dictionary = new RouteValueDictionary(queryString);
                url += string.Format("?{0}",
                                     string.Join("&",
                                                 dictionary.Select(
                                                     pair => string.Format("{0}={1}", pair.Key, pair.Value))));
            }
            return(url);
        }
        /// <summary>
        /// Validate Business Logic
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public Dictionary <string, List <string> > ValidateBusinessLogic(IEnumerable <DocumentImportDTO> items)
        {
            var errors    = new Dictionary <string, List <string> >();
            var itemRules = MaterialCMSApplication.GetAll <IDocumentImportValidationRule>();

            var documentImportDataTransferObjects = items as IList <DocumentImportDTO> ?? items.ToList();

            foreach (var item in documentImportDataTransferObjects)
            {
                var validationErrors = itemRules.SelectMany(rule => rule.GetErrors(item, documentImportDataTransferObjects)).ToList();
                if (validationErrors.Any())
                {
                    errors.Add(item.UrlSegment, validationErrors);
                }
            }

            return(errors);
        }
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // HTTP GET
            // if it's a GET
            if (filterContext.HttpContext.Request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
            {
                // merge in any invalid modelstate found
                var modelStateDictionary = TempData["MaterialCMS-invalid-modelstate"] as ModelStateDictionary;
                if (modelStateDictionary != null)
                {
                    ModelState.Merge(modelStateDictionary);
                }
            }

            // HTTP POST
            // if model state is invalid and it's a post
            if (!ModelState.IsValid &&
                filterContext.HttpContext.Request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
            {
                // persist the model state to the tempdata dictionary
                TempData["MaterialCMS-invalid-modelstate"] = ModelState;
                // redirect to the previous page
                filterContext.Result = new RedirectResult(Referrer.ToString());
            }

            string url = Request.Url.ToString();

            if (MaterialCMSApplication.Get <SiteSettings>().SSLAdmin&& url.ToLower().Contains("/admin"))
            {
                if (!Request.IsSecureConnection && !Request.IsLocal)
                {
                    filterContext.Result = new RedirectResult(url.Replace("http://", "https://"));
                }
            }

            SetDefaultPageTitle(filterContext);
            base.OnActionExecuting(filterContext);
        }
예제 #27
0
 public static MvcHtmlString RenderImage(this HtmlHelper helper, string imageUrl, Size targetSize = default(Size),
                                         string alt = null, string title = null, object attributes = null)
 {
     return(MaterialCMSApplication.Get <IImageRenderingService>()
            .RenderImage(helper, imageUrl, targetSize, alt, title, attributes));
 }
예제 #28
0
 public static string GetImageUrl(this HtmlHelper helper, string imageUrl, Size targetSize = default(Size))
 {
     return(MaterialCMSApplication.Get <IImageRenderingService>()
            .GetImageUrl(imageUrl, targetSize));
 }
예제 #29
0
 public IHub Create(HubDescriptor descriptor)
 {
     return(MaterialCMSApplication.Get(descriptor.HubType) as IHub);
 }
예제 #30
0
 public static int GetItemCount(this Batch batch)
 {
     return(MaterialCMSApplication.Get <IGetBatchItemCount>().Get(batch));
 }