CONNECT WITH US

Featured Post

ASP.NET 4.5 : Issue With CssMinify And Workaround For It

Get article update by Email

Before 2-3 days, while I was examining Bundling and Minification in ASP.NET 4.5. I observed problem with CSS3 minification while using default bundling which is available with Microsoft.Web.Optimization. Exploring more on it I found that there is a bug in CSS3 minification (while using nested parentheses) and it is already logged at

http://connect.microsoft.com/VisualStudio/feedback/details/696436/microsoft-web-optimization-cannot-compress-css3-animations
and
http://connect.microsoft.com/VisualStudio/feedback/details/689523/bugs-in-microsoft-web-optimization

Later I thought that why not create custom transform type for CSS3 which can be used with Bundling and Minification till above bug got fixed in next release. So I started to search for any open source module for CSS3 minification as I was not interested in creating my own buggy module (because it may possible, I might forget to include some possible CSS3 syntax). After searching and testing a few modules I came across to JavaScript port of YUI Compressor which is available at http://tools.w3clubs.com/cssmin/ and in my test YUI Compressor pass all cases. Luckily today I found a C# port of YUI Compressor on codeplex. Thanks to Pure Krome for this work. So with the help of C# port of YUI Compressor, I have created custom transform type for CSS3 minification which can be used with ASP.NET 4.5 and MVC 4 application. CSS3Minify transform type can be downloaded from here.

To use this transform type with Bundling and Minification download it from here and add downloaded class file into your ASP.NET 4.5 or MVC 4 application. You do not need to add reference to YUI Compressor.

Open Global.asax.cs file and in Application_Start event add following two lines.

DynamicFolderBundle Css3Bundle = new DynamicFolderBundle("css3", typeof(CSS3Minify), "*.css", false);
 
BundleTable.Bundles.Add(Css3Bundle);

That’s it now you should get your CSS3 minified. However this is temporary workaround till this bug got fixed in next version of Microsoft.Web.Optimization.

Let me know if you found any problem with this.

Read More

Creating Custom Transform Type for Bundling and Minification in .NET 4.5

Get article update by Email

Update:
Originally this article was written after first release of developer preview version of MVC 4. For latest changes in RTM version read ASP.NET 4.5 & MVC 4: Revisiting IBundleTransform

Yesterday, we have learnt how to implement default Bundling and Minification with ASP.NET MVC 4 application as well we also examined how to create custom bundle which bundle and minify only specified files. While creating custom bundle, we suppose to pass transform type to bundle. Microsoft.Web.Optimization assembly shipped with two inbuilt transform type namely JsMinify and CssMinify. In addition to built-in transform type, we can also create our own custom transform type. Today we will examine how to create custom transform type for Bundling and Minification.

To create new transform type, add new class to your MVC 4 or .NET 4.5 application. For e.g. MyJsMinify. Each transform type must implement interface IBundleTransform and Process member function of IBundleTransform interface.

Process method accepts one argument of BundleResponse type. This BundleResponse object is used to retrieve list of files included in bundle. Once we process retrieved files, we will assign processed response back to BundleResponse so it can send it back to browser.

Update:
Originally this article was written after first release of developer preview version of MVC 4. For latest changes in RTM version read ASP.NET 4.5 & MVC 4: Revisiting IBundleTransform

BundleResponse class has 4 properties. Each of them is as follow.

BundleResponse.Files

This is IEnumerable collection of files which is included in bundle.

BundleResponse.ContentType

Through this property, we can set content type for bundle so that browser can render it appropriately. Default content type "text/html".

BundleResponse.Cacheability

We can use this property to set Cache-Control HTTP header of bundled response.

BundleResponse.Content

Anything which we set as a value of this property, that content will be sent back to browser as a response of bundle. We have examined each property of BundleResponse class. So basic steps for creating custom transform type is iterate through each file of BundleResponse.Files, process it and assign it back to BundleResponse.Content. And finally set appropriate content type and cache control if it is required.

Complete code for custom transform type is given below.

public class MyJsMinify : IBundleTransform
{
    public void Process(BundleResponse bundle)
    {
        string strAllJS = string.Empty;
        // Collect content of each included files
        foreach (FileInfo obj in bundle.Files)
        {
            StreamReader srCSSFile = new StreamReader(obj.FullName);
            strAllJS += srCSSFile.ReadToEnd();
            srCSSFile.Close();
        }
        // Process gathered content or
        // process indivisual file in
        // loop and finally assign it back
        bundle.Content = strAllJS;
        bundle.ContentType = "text/javascript";
        bundle.Cacheability = HttpCacheability.Public;
    }
}

Finally we can use custom transform type as we were using built-in transform type!!!

Bundle myJSBundle = new Bundle("~/MyJSBundle", typeof(MyJsMinify));

Hope this would be helpful.

Update:
Originally this article was written after first release of developer preview version of MVC 4. For latest changes in RTM version read ASP.NET 4.5 & MVC 4: Revisiting IBundleTransform

Read More

Bundling and Minification in ASP.NET MVC 4

Get article update by Email

This post is part of ASP .NET MVC 4 Article Series.

In yesterday’s post, we have discussed that in today’s web application, client side operation is also important as much as server operation. And hence client side operation increase, JavaScript code is also increased and for maintainability of code we generally separate it by functionality in different files. Hence separated code is JavaScript so web page needs to reference many JavaScript files. Now the trouble may starts, as all browsers limits the parallel request and request beyond that limits goes in queue. More information on each browser can be found here on Browserscope. To overcome this we can combine all JavaScript files in one. But as far as code maintainability is concern this is not the right solutions. Another way is to combine and minify all files on the fly. This is also sound to be right solution than combining all JavaScript files into one. Here we will see how we can leverage the Microsoft.Web.Optimization assembly to achieve this.

With .NET 4.5, Microsoft introduced a new featured called Bundling and Minification which bundle multiple JavaScript and CSS files in one requests and minify it by removing white spaces and characters which is not required. Microsoft introduced a new class called BundleTable which take care of Bundling and Minification. BundleTable class is shipped with two inbuilt Bundle for JavaScript and CSS respectively. However one can easily create their own custom Bundle as per requirements. Here we will see how we implement Bundling and Minification in MVC 4 application.

To get started, create new MVC 4 application, build it and open it in Firefox or any other browser. And inspect the loaded JavaScript information with the help of developer tools of browser you are using.

We can see in above image that before implementing Bundling and Minification, browser requests four JavaScript files and total size of JavaScript files are 503.8KB. Now let enable Bundling with MVC 4 application and again inspect the loaded JavaScript to check how it benefit. We discuses earlier that BundleTable shipped with two inbuilt Bundle one for JavaScript and one for CSS. So first of all let enable this default Bundle. Later we will also see how we can create our own custom Bundle also. To enable default bundling, open global.asax.cs and in Application_Start events write following lines.

BundleTable.Bundles.EnableDefaultBundles();

We have enabled default bundles, but still we have not referenced it in view. Open _Layout.cshtml and looks for following lines in Head tag.

Replace above lines with following line to reference default JavaScript Bundle and press Ctrl + F5 to see Bundling and Minification in action.

Again inspect JavaScript information, after enabling default bundle. We can see in below image that browser request only one JavaScript file which is combination of previously loaded four files. Moreover if you will look at size of loaded JavaScript then you will find that it is also reduced by almost 25% previously it was total 503.8KB and after Minification it is just 359.8KB!!!

Bundling and Minification with CSS

Same way we can also reference bundled and minified CSS by replacing default CSS reference with following one in _Layout.cshtml. However Bundling and Minification does not works with CSS3 rules. It is also logged here on connect.microsoft.com. I have posted temporary workaround for it here in my post: ASP.NET 4.5 : Issue With CssMinify And Workaround For It

Creating custom Bundle with .NET 4.5 and MVC 4

So far we have used default bundle. Now we will create one custom bundle which will bundle and minify only required files. To create custom bundle we need to create object of Bundle class by specifying virtual path through which we can reference custom bundle and transform type whether it is JavaScript or CSS. Complete code for creating custom bundle is as follow. Write following code snippet in Application_Start event.

Bundle myJSBundle = new Bundle("~/MyJSBundle", typeof(JsMinify));
 
myJSBundle.AddDirectory("~/Scripts", "*.js", false);
myJSBundle.AddFile("~/Scripts/jquery.validate.min.js");
myJSBundle.AddFile("~/Scripts/common.js");
 
BundleTable.Bundles.Add(myJSBundle);

To reference created custom bundle, write following lines in respective view.

Conclusion

With vNext or .NET 4.5, it is easier to implement Bundling and Minification with very less effort and without major changes.

Hope this would be helpful.

Check out this index post on ASP.NET Web Optimization Framework (a.k.a Bundling & Minification) to read other post on same.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

Efficient Use Of jQuery Object

Get article update by Email

Day by day, jQuery is becoming a more popular and it is widely used instead core JavaScript. With ASP.NET & ASP.NET MVC also there are so many good examples available on net to get best of both. Moreover default project template of ASP.NET MVC is also including latest jQuery file for easiness of client operation.

To perform any jQuery operation, first we need to select target DOM element or set of DOM elements. And we are living (rather programming) in the era of web 2.0 and Mashup where web documents are suppose to be large with few hundred elements and lots of client side operation as well. So here we will see how one small tip can be helpful to improve jQuery performance.

Many a time we have seen developer to perform a various operation on a specific DOM element or specific set of DOM element as described below.

$("#MyDiv").show();
$("#MyDiv").addClass("header");
$("#MyDiv").css("height","100");

However nothing is wrong in above code and it will works fine without any error. But there is a lot to improvements in above code. In above example we are selecting "MyDiv" elements three times; means for each of three operations, jQuery will search for "MyDiv" in whole document and then after it will perform specific operation on it. There are two different ways to overcome this overhead. Both are explained below.

jQuery Chaining 'em up

$("#MyDiv").show().addClass("header").css("height","100");

As displayed in above example, if we are supposed to use specific DOM elements or set of DOM elements in one code block only, Then we should use jQuery Chaining pattern as displayed above. In this it will select "MyDiv" only once. As we know that after performing any jQuery operation, it will return jQuery object so we can directly use that returned jQuery object to perform next operation and can form chaining pattern.

Cache jQuery Object

var myDivElement = $("#MyDiv");
myDivElement.show();
myDivElement.addClass("header");
myDivElement.css("height","100");

jQuery chaining pattern is suitable when we are suppose to perform multiple operation in one code block only, but it will not helpful when we have to perform multiple operation from different-different code block. In such situation we should cache jQuery object as displayed in above example and then after use cached object instead selecting it each and every times.

Hope this would be helpful.

Read More

SQL Wait Stats Joes 2 Pros Review

Get article update by Email

Last month on 5th Anniversary give away of http://blog.sqlauthority.com/ , I received, SQL Wait Stats Joes 2 Pros book from Pinal Dave. Although I am not a SQL developer but I was very curious to know more about SQL Wait Stats since the June 11, 2011 (day, I attended Pinal Dave’s session on Wait Stats at Community Tech Day, Ahmadabad) as it affect the overall performance of system. As I told I am not SQL developer, so after that day, I could not bother (frankly telling) to look into book when it is published. Luckily, Last month I received book from Pinal Dave on 5th anniversary of his blog. And surprisingly after starting to read it I could not stop it and completed whole book in one seating! And I realized that I could have missed many things if I have not received the book. I would highly recommend all reader of this blog to read this book once. So I thought to write on why this book is special for person who has to deals with SQL server (and of course to convey my gratitude towards Pinal Dave also).

Real world example

One of the best parts of this book is that each and every topic in this book is explained with real life example just like Head First Series except graphical representation. But I am sure examples used in this book are very much easy to understand and uses day to day life example.

Covered Beginner to Advance Level Topic

Another great feature about this small book (110 pages only) is that it starts with beginner level introduction and end with justifying advance level topics. For e.g. Wait Stats on Multi-tasking, external resources, etc.

System Architecture

Apart from exploration of SQL Wait Stats, if you are little interested in knowing Under the hood of system then also this book is useful for you to get started thinking on how actual systems work.

Practical hands-on example

Each chapter of this book is wrapped with ready to use hands on example and exercise so reader can directly use that example on their machine and can get started to explore around it.

Points to Ponder Section

Each chapter of this book is committed (so there is no need of rollback) with "Points to Ponder Section" which include quick review of the points covered in respective chapter and review quiz for a quick refresh.

SQL Wait Stats Joes 2 Pros on Flipkart | Amazon

Read More

Upgrading an ASP.NET MVC 3 Project to ASP.NET MVC 4

Get article update by Email

Updated on 03-Feb-2013
Check out this NuGet package for auto update MVC 3 to MVC 4 application and read this post for more info ASP.NET MVC: Auto upgrade MVC 3 to MVC 4 application

This post is part of ASP .NET MVC 4 Article Series.

To upgrade and existing ASP.NET MVC 3 Project to ASP.NET MVC 4, one need to take care of following points. Complete guideline on upgrading from MVC 3 to MVC 4 is available in MVC 4 Release Notes.

  • In all web.config, including one in root folder and Views folder, change assembly version 3.0.0.0 to 4.0.0.0 for System.Web.Mvc and 1.0.0.0 to 2.0.0.0 for System.Web.WebPages, System.Web.Helpers, System.Web.WebPages.Razor.
  • Change appSettings value for key "webPages:Version" to "2.0.0.0". Apart from that also add new appSettings key named "PreserveLoginUrl" with "true" as a value.
  • Now remove all reference to MVC 3.0 assembly and Webpages 1.0 assembly. And add a reference to MVC 4.0 assembly and Webpages 2.0 assembly.
  • If you are using any third party assembly built with previous versions of MVC then do not forget to configure bindingredirect in root web.config as mentioned here.
  • Finally one more step is to change project type to MVC 4 from MVC 3. For that unload project by right clicking in solution explorer and select edit ProjectName.csproj file. Now Locate the ProjectTypeGuids element and replace {E53F8FEA-EAE0-44A6-8774-FFD645390401} with {E3E379DF-F4C6-4180-9B81-6769533ABE47}. Now save changes and re load the project.

Complete step by step information is given here in MVC 4 Release Notes.

Read More

Summarizing DateTime.Now & StopWatch In C#

Get article update by Email

In last post, Efficient Use of Try Catch Block, we have used StopWatch class to measure CPU ticks consumed by particular code execution. After reading that one of the reader asked cant we use DateTime.Now instead. So here I have tried to explain the same.

Many times we have found developer to use DateTime.Now to measure the performance of code execution. But if you google it out, you will find plenty of source which recommend using StopWatch class instead DateTime.Now. Here I am summarizing few of them.

As per the MSDN

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

It means StopWatch class uses higher resolution / precision than DateTime.Now. So it is worth to use StopWatch class for more accurate result.

One more thing we need to consider while using DateTime.Now function is that DateTime.Now return Date and Time after applying system time zone and daylight saving time settings. So it also adds overhead to the DateTime.Now function.

In above output, we can see that DateTime.Now return time zone applied value (UTC +05:30 in my case). So one may recommend using DateTime.UtcNow to overcome time zone calculation overhead. But it will not also helpful. Continue reading what is difference between DateTime.Now and DateTime.UtcNow :)

Moreover StopWatch class is shipped under System.Diagnostics namespaces hence Microsoft designed StopWatch class keeping in mind that it would more useful for diagnosis purpose and provide utmost accurate result.

However as per Barfield’s comment on John Chapman’s blog that StopWatch uses more system resources. But I don’t think that you will consider it while you are benchmarking your system.

We have enough discussion. Now let see one small example which shows clear measurement difference discussed here.

Use of DateTime.Now

DateTime dtStart;
DateTime dtEnd;
TimeSpan tsDifference;
 
dtStart = DateTime.Now;
System.Threading.Thread.Sleep(500);
dtEnd = DateTime.Now;
 
tsDifference = dtEnd - dtStart;
 
Console.WriteLine("CPU Ticks Count With Now : " + tsDifference.Ticks);

Output:

Use of DateTime.UtcNow

DateTime dtStart;
DateTime dtEnd;
TimeSpan tsDifference;
 
dtStart = DateTime.UtcNow;
System.Threading.Thread.Sleep(500);
dtEnd = DateTime.UtcNow;
 
tsDifference = dtEnd - dtStart;
 
Console.WriteLine("CPU Ticks Count With UtcNow : " + tsDifference.Ticks);

Output:

Use of StopWatch

Stopwatch sw = new Stopwatch();
 
sw.Start();
System.Threading.Thread.Sleep(500);
sw.Stop();
 
Console.WriteLine("CPU Ticks Count With StopWatch : " + sw.ElapsedTicks);

Output:

Conclusion

Based on above discussion and example, we can clearly see that use of StopWatch is preferable over DateTime.Now and DateTime.UtcNow as Stopwatch provide more accurate result.

What do you say reader???

Read More

Efficient Use of Try Catch Block

Get article update by Email

In all application, whether it is web or desktop, whether it is built in .NET or JAVA or any other language, we all are using (and we should use if we are not!) Try Catch Block or similar available mechanism to handle the exception.

But recently while I was working on one application, I observed that Try Catch Block was also used to make decision!!! As Try Catch mechanism is provided to handle exception and hence it is heavy operation and utilizes more CPU, we should not use Try Catch for such decision making scenario. Instead we should look for any alternate solution. Let try to understand whole scenario by formulating one small example.

In all below example, I am using System.Diagnostics.Stopwatch class to count CPU ticks consumed by particular task.

Example 1 Scenario 1 : With Try Catch

string strPrice = "abc";
int Price;           
Stopwatch sw = new Stopwatch();
sw.Start();
 
try
{
    Price = Int32.Parse(strPrice);
    // DO SOMETHING
}
catch (Exception ex)
{
    Price = 0;
    // DO SOMETHING
}
 
sw.Stop();
Console.WriteLine("CPU Ticks Used For Parsing : " + sw.ElapsedTicks.ToString());

Output:

In above example, we are parsing string into integer within Try block and performing some operation (If part of if else condition). And if we are unable to parse string (as displayed in above case), it throws an exception and goes in Catch block and there we perform some other operation (else past of if else condition).

Now observe below scenario, in that we are rewriting above 10 line code with another 10 line with if else and of course we are removing Try Catch also :)

Example 1 Scenario 2 : Without Try Catch

string strPrice = "abc";
int Price;           
Stopwatch sw = new Stopwatch();
sw.Start();
 
Int32.TryParse(strPrice, out Price);
if (Price == 0)
{
    // DO SOMETHING
}
else
{
    // DO SOMETHING
}
 
sw.Stop();
Console.WriteLine("CPU Ticks Used For Parsing : " + sw.ElapsedTicks.ToString());

Output:

Volia!!! We have reduced CPU ticks from 42949 to 27.

I don’t think that, I need to write more on scenario 2. It is self explanatory. Here the idea is that we should use Try Catch to handle exception only. In above example we are just parsing one string, but consider scenario where we are iterating through few thousands element or collection and where 90% or more elements are suppose to be string only and hence it goes in Catch block (Yes I faced the same situation!) After replacing Try Catch Block with If Else, I observed 10 times faster code than previous one.

Now let see one more example for illustrative purpose.

Example2 Scenario 1 : With Try Catch

Stopwatch sw = new Stopwatch();
sw.Start();
 
FileStream fs;
try
{
    fs = File.Open("D:\\nandip.docx", FileMode.Open);
}
catch
{
    fs = File.Open("D:\\nandip.docx", FileMode.Create);
}
 
sw.Stop();
Console.WriteLine("CPU Ticks Used For Reading File : " + sw.ElapsedTicks.ToString());

Output:

Example 2 Scenario 2 : Without Try Catch

Stopwatch sw = new Stopwatch();
sw.Start();
 
if (File.Exists("D:\\nandip.docx"))
{
    fs = File.Open("D:\\nandip.docx", FileMode.Open);
}
else
{
    fs = File.Open("D:\\nandip.docx", FileMode.Create);
}
 
sw.Stop();
Console.WriteLine("CPU Ticks Used For Reading File : " + sw.ElapsedTicks.ToString());

Output:

In above example also we can see CPU ticks reducing from 106668 to 1820. Idea behind above example is to show how to choose alternate solution where we fall in such situation or found in inherited code :)

I hope two example discussed here, one real life example and one for illustrative purpose, would be helpful.

Read More