Tuesday, May 13, 2014

ASP.NET 4.5 Bundling and Minification

Today I was playing around with the B&M feature ASP.NET provides. Since most of the open source libraries mandate to preserve the copy right text, one of my requirements is to preserve the copyright text. When I examined most of the libraries, the comments are placed under important comments /*!-------*/

So, my first approach was to create a custom bundle class, that use the default bundle builder class and a custom bundle transformation class. The custom bundle transform class will use the AJAX Minifier class (Microsoft.Ajax.Utilities.Minifier) to minify file with PreserveImportantComments = true

Everything had worked as expected and then I found that the entire global variables from all JavaScript files included in the bundle are listed at the top of the generated file. So, I decided to go with another approach.

  • Created a custom bundle class that uses a custom bundle builder class.
  • The custom bundle builder class use AJAX Minifier class to minify the files.
  • You can set code setting properties to control the minification process
public class CustomBuilder : IBundleBuilder
{
public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<System.IO.FileInfo> files)
{
var settings = new CodeSettings()
{
// LocalRenaming = Microsoft.Ajax.Utilities.LocalRenaming.KeepAll,
PreserveImportantComments = true,
RemoveUnneededCode = true,
EvalTreatment = EvalTreatment.MakeAllSafe
};

var content = new StringBuilder();
foreach (var fileInfo in files)
{
var minifier = new Microsoft.Ajax.Utilities.Minifier();
content.Append(minifier.MinifyJavaScript(ReadFile(fileInfo), settings));
content.Append(";");
content.Append(Environment.NewLine);
}

return content.ToString();
}

private string ReadFile(FileInfo file)
{
using (var r = file.OpenText())
{
return r.ReadToEnd();
}
}
}


public class CustomScriptBundle : Bundle
{
// Methods
public CustomScriptBundle(string virtualPath)
: this(virtualPath, null)
{
}

public CustomScriptBundle(string virtualPath, string cdnPath)
: base(virtualPath, cdnPath)
{
this.Builder = new CustomScriptBuilder();
}

}



Saturday, June 15, 2013

Creating properties: VS tip

Sometimes auto implemented properties don't satisfy our requirement. So, we need to create full property declaration.

Do you feel it's time consuming? If, so check this cool feature.
1. Create property backing field. Ex: private string _name;
2. right click mouse and go to Refactor -> Encapsulate. Visual studio opens up a dialogue box. Set values accordingly. I prefer key board short cut Ctrl+R+E.

http://visualstudiomagazine.com/blogs/tool-tracker/2013/06/write-a-property-with-a-name-and-datatype.aspx

Thursday, August 9, 2012

Power Commands for Visual Studio 2010 Extension


If you install power commands, following features can be utilized. 

Format Document On Save
Remove And Sort Usings On Save
Remove and Sort Usings
Clear All Panes
Copy Path
Email Code Snippet
Insert Guid Attribute
Show All Files
Collapse Projects
Copy Class / Paste Class
Copy As Project Reference
Edit Project File
Open Containing Folder
Open Command Prompt
Unload Projects / Reload Projects
Extract Constant
Clear Recent File List
Clear Recent Project List
Close All
Choose which commands you want to use

Please refer this blog for more details

Collapse Selection in Solution: Visual Studio 2010 Extension


A tool to collapse all the projects to parent node:
How to install
1. Navigate to Tools –> Extension Manager, and search for “Collapse Selection in Solution Explorer” in the Online Gallery. Simply download and click Install.
2. Or download it from VS site

More details available at MSDN blog

Monday, February 6, 2012

LINQ Part 4 – Standard Query Operators

LINQ Part 4 – Standard Query Operators

At compile time query expressions are converted into Standard Query Operator method calls. Query expressions can be compiled to expression trees or to delegates, depending on the type that the query is applied to. IEnumerable(Of T) queries are compiled to delegates. IQueryable and IQueryable(Of T) queries are compiled to expression trees.
This section gives an overview on standard query operators.
Standard query operators are methods operate on sequence which implements either IQueryable or IEnumerable interface and help to achieve provide LINQ pattern. These methods are provided as extension methods to these interfaces. We can also replace the standard query operators with our own implementations using method extension feature.



Previous Post                        Next Post

LINQ Part 3 - Writing a query

Part 3 - Writing a query 

The quires operate on simple in-memory collections. A user can use any of the following three ways to create a query
  1. Query Syntax
  2.  Method syntax
  3. Combination of query and method syntax
Query Syntax
Query syntax is based on the query keywords which are used to write a query expression. I explained some of the query keywords on my previous post. This helps user to write SQL style commands.
From MSDN, query syntax is the recommended way to write quires. One reason for this is readability factor. Along with that using query syntax we can make use of let and handle complex join operations.

var employeeSalaryQuery = from employee in employees where employee.Salary > 10000

Please note as described in the earlier post, query type is IEnumerable and they do not get executed until they are iterated over a foreach loop.

Method Syntax
Some of the query expressions are wrapped under a method call, i.e as a dot operation. So, if you put a ‘.’ After a list variable, you can find these methods.
Some of these methods returns that return singleton numeric values, such as Sum, Max, Min, Average..etc. Please note these methods will be called last in any query expressions.

List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
double average = numbers.Average();

If the methods have parameters, parameters are supplied as lambda expressions. 

var employeeSalaryQuery = employees.Where(e => e.Salary>10000);

Mixed Query
As the name suggest, it contains both query syntax and method syntax. To create mixed queries, enclose query syntax in parenthesis and then call the methods (dot operators).

int employeeCount = (from employee in employees where employee.Salary > 10000).Count();

Previous Post                                        Next Post

Thursday, February 2, 2012

Linq - Part -2 Query Expressions

Part -2  Query Expressions
Query Expression:

As I mentioned on the previous post, query is a set of information used to retrieve data from data sources. So query operates on a data source (SQL, XML, collections… ). From application stand point, it sees the execution result as IEnumerable (Of T) or IQueryable(Of T) collection
A query expression is a query made of certain clauses and with certain syntax.  

Starting a query expression
A query expression starts with from clause. This specifies the data source and the range variable. Consider the example
var queryVar = from employee in employeeList where employee.Salary>10000

In this example employeeList is the data source and employee is the range variable. Since the compiler can infer the type, there is no need to specify range variable’s type.

The range variable is like an iteration variable. Actual iteration won’t happen in query expression. When query gets executed this variable will serve as a reference to each successive element in employeeList.

A range variable can be introduced by a let statement. Scope of a range statement is until the query is exited either with a semicolon or with a continuation clause.

A query expression may contain multiple from clause. As an example
Var queryVar = from employee in employeeList from department in departmentList where employee.Id =  department.Id select new  {EmployeeName=employee.Name, departmentName=department.Name} 

Ending query expression
A query expression must end with a select or group clause.

Grouping
group clause helps to group result based on a key. When we group, the result will be a list of lists of IGrouping(Of TKey, TElement). Each element in the list is an object that has a Key member and a list of elements that are grouped under that key. To access the elements use nested foreach loop. Group keys can be any type, such as a string, a built-in numeric type, or a user-defined named type or anonymous type.

 var querGroupByEmpdeptId = from employee in employeeList group employee by    employee.DepartmentId

Selecting
select  clause produces and shape the result of the query. When select clause produces something other than a copy of the source element, the operation is called a projection

Into and let clause
into clause is used conjunction with select, join or group clause to create a temporary identifier that stores the query. 

let clause is used to store the value of an expression and it can be used in the subsequent clause. 


var studentQuery =   from student in students    let avg = (int)student.Scores.Average()  group student by (avg == 0 ? 0 : avg / 10) into g  orderby g.Key   select g;     (from MSDN)

Filtering
where clause is used to filter out data from data source. 


Ex: var employeeQuery = from employee in employees where employee.Salary >1000

The where clause is a filtering mechanism. It can be positioned almost anywhere in a query expression, except it cannot be the first or last clause. A where clause may appear either before or after a group clause depending on whether you have to filter the source elements before or after they are grouped.

Sorting
ordererby clause causes the returned sequence or subsequence (group) to be sorted in either ascending or descending order. By default it is ascending, so this key word is optional

Ex: var employeeSortByNameQuery = from employee in employees orderby employee.Name

Joining
join clause is used to associating elements from different source sequences that have no direct relationship in the object model. The only requirement is that the elements in each source share some value that can be compared for equality.
There are three kinds of join
  1.  Inner Join
  2. Group join
  3.  Left outer join
Previous Post                                                                    Next Post

Featured post

How to connect to Mongo Atlas from Robo 3T

If you use a local instance of MongoDB, you might be a great fan of Robo3T. However, if you are using Mongo Atlas, the Atlas web interface p...

Popular Posts