Complete set in ASP.NET

ASP.NET – this is a technology that allows you to increase productivity. With output ASP.NET 4.5 its stack took a huge step forward by adding automated web resource bundling, which made it easy and flexible to work with.

In this article, I would like to review the bundling of elements in ASP.NET. I’ll tell you how to fully customize the configuration options for any project. ASP.NET.

In ASP.NET 4.5
 the framework has received a new namespace System. Web. Optimization. Let’s see how it works.

Customization

In this article, I’ll start with an empty project ASP.NET MVC. This way, I can focus on what I need to do in order to set up automated bundling. The same basic steps apply in WebForms. In this article, I will use Razor and C#.

After clicking on the appropriate buttons to create a new project, add these packages to the NuGet Package Manager console:

PM> Install-Package Microsoft.AspNet.MvcPM>
 Install-Package jQueryPM>
 Install-Package BootstrapPM>
 Install-Package Microsoft.AspNet.Optimization

I would like to draw your attention to a NuGet package called Microsoft.AspNet.Optimization. If you are working with an existing project ASP.NETthis NuGet package will make your work easier. Once it’s installed, all you have to do is create the rest of the structure.

With this web optimization package, you get a tool for automating the management of web resources. You can find official documentation on MSDN.

Now add a folder named App_Start to the main project, if it’s not already there. We need to set the configuration by adding this static class:

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
 }
}

Routing is set using any existing project, so I won’t stop there.

In order to ASP.NET If I didn’t know about your newly configured configuration, do the following in Global. asax:

public class Global : HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
 BundleConfig.RegisterBundles(BundleTable.Bundles);
 }
}

ASP.NET it is an event-oriented technology. You can think of it as an IISserver that waits for new events. In our case, client browser requests via HTTP.

When the app is first launched, ASP.NET calls Application_Start in Global. asax. Application_Start is a place where you should specify specific packages that you want to use in your application.

In the end, my solution is given as follows:]

Traffic Tracking

It’s time to add the packages and see how they are displayed in the browser. Add the following code to BundleConfig, the static class I mentioned earlier:

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
 {
 bundles.Add(new StyleBundle("~/bundle/bootstrap-styles")
 .Include("~/Content/bootstrap.css")
 .Include("~/Content/bootstrap-theme.css")
 .Include("~/Content/Site.css"));
 bundles.Add(new StyleBundle("~/bundle/Home/Index-styles")
 .Include("~/Content/StyleSheet1.css")
 .Include("~/Content/StyleSheet2.css")
 .Include("~/Content/StyleSheet3.css"));

 bundles.Add(new ScriptBundle("~/bundle/bootstrap-scripts")
 .Include("~/Scripts/bootstrap.js")
 .Include("~/Scripts/jquery-{version}.js")
 .Include("~/Scripts/modernizr-{version}.js"));
 bundles.Add(new ScriptBundle("~/bundle/Home/Index-scripts")
 .Include("~/Scripts/JavaScript1.js")
 .Include("~/Scripts/JavaScript2.js")
 .Include("~/Scripts/JavaScript3.js"));
 }
}

Your specific needs may vary. The above method accepts BundleCollection as a parameter. Note that BundleTable.Bundles is passed from Global. asax. After that, I create a set of styles and scripts that fit my needs.

I use the {version} directiveto tell the bundling engine to use any version of jQuerythat is found in my solutions. In the jQuery configuration Release.min.js it will be added to the bundle, but not in Debug.

This gives me the flexibility of the development environment when working with jQuery. I can replace different versions of jQuery, and my configuration settings will not be affected. The same technique applies to any other client library.

Since I define my own packages, I can customize resources to fit specific screens.

I put the ~/bundle/bootstrap-styles and ~/bundle/bootstrap-scripts packages on the main page of _Layout. cshtml. Since this is a complex element with a large number of initial downloads, I will not describe it in this article.

This is what my Razor Index.cshtml page looks like now:

@{
 ViewBag.Title = "Index";
}

@Styles.Render("~/bundle/Home/Index-styles")
<h2>Hello World</h2>
<p>
 Be sure to check out glyphs like these:
    <span class="glyphicon glyphicon-plus"></span>.
</p>
@Scripts.Render("~/bundle/Home/Index-scripts")

Everything is simple. Once the packages are defined, I can put them anywhere in my application. I follow the simple {Controller}/{Action} conventionto define bundling. You can do the same.

If you see that the Razor page error is displayed, because it can’t find Styles.Render or Scripts. Render, make sure that you have enabled them in the Web. config filelocated in the Views folder:

<system.web.webPages.razor>
 ...
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
 ...
      <add namespace="System.Web.Optimization"/>
    </namespaces>
  </pages>
  </system.web.webPages.razor>
</system.web.webPages.razor>

This tells the Razor engine to enable the System.Web.Optimization namespace when rendering dynamic HTML. You can also include any other namespaces that are necessary for your specific project. This will give you the option to completely disqualify every Razor extension.

Now let’s look at the network traffic:

Red color means that the browser is idle. Yellow – when the browser makes a request. Blue – the time required to receive a response from the server.

In most modern browsers, you can make about six requests at a time. If you need more than six requests, the browser will have to wait. The topmost request is dynamic HTML, which I have to get from the server.

Why is this important?

To understand how this all works, you can imagine the server-side programming language C #as a spaceship. During space travel, when you increase the speed, you will see the effect of slowing down time.

As long as the back-end runs locally on your server, you can assume that it will do everything with high performance. But, when a request is transmitted over HTTP channels, it’s a completely different story.

I think of the HTTP network protocolas a cart pulled by a mule. No matter how well or poorly optimized your backend is, HTTP will still run slower.

Thus, it would be good to load the mule’s basket with more provisions before it sets off across town. Constantly sending requests and getting responses over and over again is a sure way to kill performance.

HTTP requests consume a lot of resources. Your main goal is to reduce the number of HTTP requests.

Connections

To enable bundling in the framework, you need to make the following change in the Web. config file of your solution folder:

<compilation debug="false" targetFramework="4.5" />

You can also hard-set this with:

BundleTable.EnableOptimizations = true;

When you hard-set this in C #, this instruction will take precedence over Web. config. In the standard configuration, you can use a change in the Web. config file to enable it in Release mode. Then you will no longer need to try to debug minified JavaScriptcode.

Let’s take a look at the traffic after enabling bundling:

Great. Resources start loading as soon as dynamic HTML is loaded. I’m now making full use of the browser’s capabilities, as exactly six resources are now being requested. Note that the last resource is not started until all other resources have been issued. This is because it is a web font, and it is linked to a CSS package.

Caching

When bundling is enabled, you get an additional benefit from the fact that resources are cached in the browser for approximately one year. If your resources change before that, the query string added to the end will change. This, in fact, leads to the fact that some resources will no longer be needed by the browser. This is often referred to as cache-busting.

For example, here’s what our completed resources will look like:

/bundle/bootstrap-styles?v=epi1k_G4Tsd0o4dXIOJcBg5gefY7ieCSx0AUDxqm78U1
/bundle/Home/Index-styles?v=uxFDb5XiuKadZOyd2DKyzUU-mh3OUTNuikUDUlL7e_Q1
/bundle/Home/Index-scripts?v=Giv511fvuZRlJKLjJDPqmIxOhmtht9zFlW7lvvTMf0Y1
/bundle/bootstrap-scripts?v=j4YIBwFVDdtvOMWp63GzkWLSoYrcw0ertU_njZLALnk1

The query string appended to the end is a hash of the specific content of each packet. When the content inside the package changes, the hash added as a query string will also change.

You can check the HTTP headers:

The Expires HTTP header cache expires after one year.

Conclusion

ASP.NET – this is a cool technology designed to make your life easier. What I like most about it is how the engine outputs the <link> and <link><style>tags for us. I was always most worried about the fact that these tags will be placed in a circle. And this is a real nightmare for managing a web resource.

I hope that you now understand how to fully define automated bundling for your project. Be sure to check out the simple demo that demonstrates the basics of this method, which is posted on GitHub.

What do you think about the bundling feature ASP.NET? Do you have any recommendations of your own to improve your productivity?

Leave a Reply

Your email address will not be published.

You May Also Like