Changing Css throw database

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
12 anni tempo fa
Hi everyone!

I'm working on a new idea for NopCommerce, and that is to change the background as I like, for product, category, news, ....

I know that I could do that kind of changes through Asp.Net themes, but that's not what I want to achieve.

I want to achieve the user can change and enter desired background color, borders, etc. ..

That's why I decided to try to make it through the base along with. CSS file.

I found an interesting article on the Internet (http://madskristensen.net/post/Add-variables-to-standard-CSS-stylesheets-in-ASPNET.aspx) and decided to just change the way how to save variables that need to be changed . Instead I save the variables that are need to change under the #define ...; as in this example, I saved them in the database.

But from me, for some unknown reason, page does not load me up .CSS properly, ufter debuging that I found that it break when creating the object Background that I create and it appears to me the following error: "System.InvalidOperationExpection Mapping and metadata information could not be found for EntityType(Background)"

So the program gets stuck at the very beginning and entities as it does not create and is not loaded.

The code that I made is ​​the following:


using System;
using System.Web;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;
using NopSolutions.NopCommerce.BusinessLogic.Categories;
using NopSolutions.NopCommerce.BusinessLogic.Manufacturers;
using NopSolutions.NopCommerce.BusinessLogic.Products;
using NopSolutions.NopCommerce.BusinessLogic.Content.NewsManagement;
using NopSolutions.NopCommerce.BusinessLogic.Content.Topics;
using NopSolutions.NopCommerce.BusinessLogic.Content.Forums;
using NopSolutions.NopCommerce.BusinessLogic.Content.Blog;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.BusinessLogic.Css.Background;

namespace NopSolutions.NopCommerce.BusinessLogic.Css
{
/// <summary>
    /// Parses and serves dynamic stylesheets.
    /// </summary>
    public class CssHandler : IHttpHandler
    {

        #region IHttpHandler implementation

        public void ProcessRequest(HttpContext context)
        {
            FileInfo file = new FileInfo(context.Request.PhysicalPath);
            if (file.Extension.Equals(".css", StringComparison.OrdinalIgnoreCase))
            {
                SetDefaultVariables();
                ParseVariables(file.FullName);
                ApplyVariables(context);
                ReduceSize(context);
                SetHeadersAndCache(file.FullName, context);
                _Variables.Clear();
            }
        }
        

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #endregion

        #region Private members

        private Dictionary<string, string> _Variables = new Dictionary<string, string>();
        private StringBuilder _CleanedCSS = new StringBuilder();
        private StringBuilder _ParsedCSS = new StringBuilder();

        #endregion

        #region Methods

        /// <summary>
        /// Adds the built-in variables to the collection.
        /// </summary>
        private void SetDefaultVariables()
        {
            _Variables.Add("browser", "\"" + HttpContext.Current.Request.Browser.Browser + "\"");
            _Variables.Add("version", HttpContext.Current.Request.Browser.MajorVersion.ToString());
        }

        
        /// <summary>
        /// Parses the variables defined in the stylesheet
        /// and adds them to the variable collection.
        /// </summary>
        private void ParseVariables(string file)
        {
            using (StreamReader reader = new StreamReader(file))
            {
                while (reader.Peek() > -1)
                {
                    string line = reader.ReadLine();
                      _CleanedCSS.AppendLine(line);
                    
                }
            }
        }
/// <summary>
        /// Applies the defined variables to the stylesheet.
        /// </summary>
        private void ApplyVariables(HttpContext context)
        {
            string css = _CleanedCSS.ToString          

            var background = BackgroundManager.GetDefaultBackground();
            if (background != null)
            {
                var csses = CssManager.GetAllCssByBackgroundId(background.BackgroundId);

                if (csses.Count > 0)
                {
                    foreach (var css1 in csses)
                    {
                        css = css.Replace(css1.Code, css1.Value);
                    }
                }
            }

            _ParsedCSS.Append(css);
        }

        /// <summary>
        /// A simple function to get the result of a C# expression
        /// </summary>
        /// <param name="command">String value containing an expression that can evaluate to a string.</param>
        /// <returns>A string value after evaluating the command string.</returns>
        private string ProcessExpression(string expression)
        {
            if (expression.Contains("System."))
                throw new ArgumentException("Command is not allowed: " + expression);

            using (CSharpCodeProvider provider = new CSharpCodeProvider())
            {
                CompilerParameters parameters = new CompilerParameters();
                parameters.GenerateExecutable = false;
                parameters.GenerateInMemory = true;

                string source = "namespace dotnetslave{" +
                                "class css{" +
                                "public static object Evaluate(){return " + expression + ";}}} ";

                CompilerResults result = provider.CompileAssemblyFromSource(parameters, source);

                if (result.Errors.Count > 0)
                {
                    return expression;
                }
                else
                {
                    MethodInfo Methinfo = result.CompiledAssembly.GetType("dotnetslave.css").GetMethod("Evaluate");
                    return Methinfo.Invoke(null, null).ToString();
                }
            }
        }

        /// <summary>
        /// Removes all unwanted text from the CSS file,
        /// including comments and whitespace.
        /// </summary>
        private void ReduceSize(HttpContext context)
        {
            string css = _ParsedCSS.ToString();
            css = css.Replace("  ", String.Empty);
            css = css.Replace(Environment.NewLine, String.Empty);
            css = css.Replace("\t", string.Empty);
            css = css.Replace(" {", "{");
            css = css.Replace(" :", ":");
            css = css.Replace(": ", ":");
            css = css.Replace(", ", ",");
            css = css.Replace("; ", ";");
            css = css.Replace(";}", "}");
            css = Regex.Replace(css, @"/\*[^\*]*\*+([^/\*]*\*+)*/", "$1");
            css = Regex.Replace(css, @"(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,}(?=&nbsp;)|(?<=&ndsp;)\s{2,}(?=[<])", String.Empty);

            context.Response.Write(css);
        }

        /// <summary>
        /// This will make the browser and server keep the output
        /// in its cache and thereby improve performance.
        /// </summary>
        private void SetHeadersAndCache(string file, HttpContext context)
        {
            context.Response.ContentType = "text/css";
            context.Response.AddFileDependency(file);
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.VaryByParams["path"] = true;
            context.Response.Cache.SetETagFromFileDependencies();
            context.Response.Cache.SetLastModifiedFromFileDependencies();
        }

        #endregion

    }
}



In web.config I call it together with other handlers:


<httpHandlers>
      <remove path="*.asmx" verb="*"/>
      <add path="*.asmx" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
      <add path="*_AppService.axd" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
      <!--<add path="ScriptResource.axd" verb="GET,HEAD" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>-->
      <add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
      <add verb="*" path="pricelist.csv" validate="false" type="NopSolutions.NopCommerce.BusinessLogic.ExportImport.PricelistHandler, Nop.BusinessLogic"/>
      <add type="NopSolutions.NopCommerce.BusinessLogic.Css.CssHandler" verb="*" path="*.css" />
    </httpHandlers>


I will be very grateful for any help to solve this problem. Anybody know what the problem is and what causes it?

Thank you in advance.
12 anni tempo fa
Did you add any fields to the database?
12 anni tempo fa
I finally find the problem and that is that I made old school mistake and that I give the folder and class the same name.

I change the nam of the folder to the Backgrounds, name of the class is Background but now I have this message when I try to work with class Background on my web page.

"Mapping and metadata information could not be found for EntityType NopSolutions.NopCommerce.BusinessLogic.Css.Backgrounds.Background".

I do not understand what is causing the problem when I build the solution and the build was succeeded.

Can anybody help me?
12 anni tempo fa
I forget to say that I use NopCommerce 1.80

And also, because I didn't create a new folder and class for a long time I just remember, that every time when I create a new folder and class under him I had the same mistake before. But it work normally if I create subfolder under some folder that already exist and put classes in him.

Now why is that problem always there?
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.