Minifycode 2020-02-22 Viewed 1.4K times ASP.NET MVC

In this article, you will learn how to Bundling and Minification in MVC

In this post, Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.) Bundling and minification are two techniques you can use in ASP.NET 4.5 or above to improve request load time. 

BundleConfig.cs

 

public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js","~/Scripts/event.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
            BundleTable.EnableOptimizations = true;
        }

RouteConfig.cs

 

public static void RegisterRoutes(RouteCollection routes)
        {
            BundleTable.EnableOptimizations = true;
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes();
            routes.MapRoute(
            name: "sitemap",
            url: "sitemap.xml",
            defaults: new { controller = "Home", action = "sitemap" }
        );
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

FilterConfig.cs

 

 public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }
    class EtagFilter : ActionFilterAttribute
    {
        private DateTime _currentTime = DateTime.Now;

        private string _currentEtag = string.Empty;
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            var httpContext = filterContext.RequestContext.HttpContext;
            string eTag = httpContext.Request.Headers["If-None-Match"];
            string responseETag = GetEtag();
            if (!string.IsNullOrEmpty(eTag))
            {
                if (eTag.Equals(responseETag))
                {
                    filterContext.HttpContext.Response.StatusCode = 304;

                    filterContext.HttpContext.Response.StatusDescription = "Not Modified";
                }

                return;
            }

            httpContext.Response.AddHeader("ETag", responseETag);
        }
        private string GetEtag()
        {
            if (_currentTime <= DateTime.Now.AddSeconds(10))
            {
                _currentEtag = GenerateEtag();
                return _currentEtag;
            }

            _currentEtag = GenerateEtag();

            return _currentEtag;
        }

        private string GenerateEtag()
        {
            return Guid.NewGuid().ToString().Substring(0, 20);
        }
    }

Web.config

 <httpProtocol>
      <customHeaders>
        <clear />
        <remove name="X-Powered-By" />
        <remove name="X-Powered-By-Plesk" />
        <add name="Transfer-Encoding: chunked" />
      </customHeaders>
    </httpProtocol>

_Layout.cshtml

 

 @Styles.Render("~/Content/css") 
@Scripts.Render("~/bundles/modernizr") 
@Scripts.Render("~/bundles/jquery")

Output

 

<link href="/Content/css?v=MPPPiGFOcsEC7dgGAMkxW-oe1ajI6SxTIx5z9izAXwk1" rel="stylesheet"/>
 <script src="/bundles/modernizr?v=wBEWDufH_8Md-Pbioxomt90vm6tJN2Pyy9u9zHtWsPo1"></script>
 <script src="/bundles/jquery?v=hMTR6S5uitG_pTi_gAkAnslTfg4guLwzTBNa9TcoD3s1"></script>

 

Bundling and Minification in MVC
public static byte[] CreateHTMLtoPDF(string HtmlString) { var htmlContent = String.Format(HtmlString); var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter(); htmlToPdf.Orientation = NReco.PdfGenerator.PageOrientation.Landscape; //var Orientation = new NReco.PdfGenerator.HtmlToPdfConverter().Orientation=NReco.PdfGenerator.PageOrientation.Landscape; htmlToPdf.Size = NReco.PdfGenerator.PageSize.A4; //htmlToPdf.Zoom = -0.55f; var pageMargin = new NReco.PdfGenerator.HtmlToPdfConverter().Margins; //htmlToPdf.PageHeight= 210; //htmlToPdf.PageWidth = 297; pageMargin.Left = 25; pageMargin.Right = 25; pageMargin.Bottom = 25; pageMargin.Top = 25; var pdfBytes = htmlToPdf.GeneratePdf(htmlContent); byte[] bytes; using (MemoryStream input = new MemoryStream(pdfBytes)) { using (MemoryStream output = new MemoryStream()) { string userpassword = "123";//Change it with User DOB Format dd-MM-yyyy string Ownerpassword = "123";//Change it with whatever owner is wanted PdfReader reader = new PdfReader(input); PdfEncryptor.Encrypt(reader, output, true, userpassword, Ownerpassword, PdfWriter.ALLOW_SCREENREADERS); bytes = output.ToArray(); //Response.ContentType = "application/pdf"; //Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf"); //Response.Cache.SetCacheability(HttpCacheability.NoCache); //Response.BinaryWrite(bytes); //Response.End(); } } return bytes; } <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SendOTP.aspx.cs" Inherits="Shoping_Cart.SendOTP" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>How to Send and Verify OTP On Mobile No Using C# In Asp.Net</title> </head> <body> <form id="form1" runat="server"> <div> Mobile No: <asp:TextBox ID="txtMobileNo" runat="server" Width="200px"></asp:TextBox> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Send OTP" /> <br /> <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label> </div> </form> </body> </html> using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Shoping_Cart { public partial class SendOTP : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { try { Random r = new Random(); string OTP = r.Next(1000, 9999).ToString(); //Send message string Username = "youremail@domain.com"; string APIKey = "YourHash"; string SenderName = "MyName"; string Number = "981111111"; string Message = "OTP code is - " + OTP; string URL = "http://api.minifycode.in/send/?username=" + Username + "&hash=" + APIKey + "&sender=" + SenderName + "&numbers=" + Number + "&message=" + Message; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); StreamReader sr = new StreamReader(resp.GetResponseStream()); string results = sr.ReadToEnd(); sr.Close(); Session["OTP"] = OTP; //Redirect for varification Response.Redirect("VerifyOTP.aspx"); } catch (Exception ex) { lblMessage.Text = ex.Message.ToString(); } } } } <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Verify.aspx.cs" Inherits="Cart.VerifyOTP" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Verify OTP</title> </head> <body> <form id="form1" runat="server"> <div> OTP: <asp:TextBox ID="txtOTP" runat="server" Width="200px"></asp:TextBox> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Verify OTP" /> <br /> <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label> </div> </form> </body> </html> using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Cart { public partial class OTP : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { if (Session["OTP"].ToString() == txtOTP.Text) { lblMessage.Text = "You have enter correct OTP."; Session["OTP"] = null; } else { lblMessage.Text = "Pleae enter correct OTP."; } } } }