Tuesday, February 24, 2015

Brief version history of ASP.NET MVC with features

Asp.Net MVC is a new framework from Microsoft that sits over standard Asp.Net engine. It is built on top of Asp.Net and uses core features of Asp.Net. It implements MVC (Model-Viw-Controller) pattern which provides separation of code and better support for test-driven development (TDD).

Here is the list of released version history of Asp.Net MVC Framework for all stable versions and their features:

Asp.Net MVC 1

Release Date: 13 March, 2009
.Net Framework: .Net 3.5 with Visual Studio 2008 and Visual Studio 2008 SP1
Features: 
  • MVC Architecture
  • WebForm Engine
  • Concept of routing
  • Html Helpers
  • Ajex Helpers
  • Unit Testing
  • Automatic binding of posted forms to .NET objects and model validation

Asp.Net MVC 2

Release Date: 10 March, 2010
.Net Framework: .Net 3.5 and .Net 4.0 with Visual Studio 2008 and Visual Studio 2010
Features: 
  • Model validation based on attributes, both server and client side
  • Areas to partition bigger applications in modules
  • Html Templated helpers, to automatically render edit forms and display pages based on the model and attributes applied on it
  • Strongly types Html Helpers means lambda based Html Helpers to remove most of the "magic strings" previously needed in html helpers
  • Asynchronous Controllers
  • Data Annotation Attributes
  • Client Side Validation
  • Overriding the HTTP Method Verb including GET, PUT, POST, and DELETE

Asp.Net MVC 3

Release Date: 13 January, 2011
.Net Framework: .Net 4.0 with Visual Studio 2010
Features: 
  • Razor view engine
  • Unobtrusive javascript validation and general better javascript
  • Remote Validation
  • Dependency Resolver
  • Global Filters
  • Compare Attribute
  • Child Action Output Caching
  • Session-less Controller
  • ViewBag dynamic property
  • Child Action Output Caching
  • Partial View Output Caching
  • Entity framework code-first support
  • Support for Nuget packages to install dll and their dependencies

Additionally, a new "New Project" dialog that allows you to choose different project templates as base for your ASP.NET MVC 3 application was introduced. It includes the usual template (with user management and login pages) but is open for including other project templates very easily.

Asp.Net MVC 4

Release Date: 15 August 2012
.Net Framework: .Net 4.0 and .Net 4.5 with Visual Studio 2010 SP1 and Visual Studio 2012
Features: 
  • Asp.Net Web API
  • Enhancements in default project template
  • New mobile project template using jQuery Mobile, an open-source library for building touch-optimized UI
  • Display Modes feature that lets an application select views depending on the browser that's making the request
  • Task support for Asynchronous Controller
  • Supports Azure SDK
  • Database migrations by Entity Framework 5
  • Empty project template
  • Bundling and Minification
  • Support for login from social sites like Facebook using OAuth and OpenID

Asp.Net MVC 5

Release Date: 17 October 2013
.Net Framework: .Net 4.5 and .Net 4.5.1 with Visual Studio 2013
Features: 
  • One Asp.Net
  • Asp.Net Identity
  • Bootstrap
  • Authentication Filters
  • Filter Override
  • Attribute Routing
  • Asp.Net Scaffolding
  • Asp.Net Web API 2

I hope you found this article useful. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Monday, February 23, 2015

SQL best practices for query optimization and increasing performance

1. Avoid unnecessary columns in the SELECT list and unnecessary tables in join conditions
  • Selecting unnecessary columns in a select query adds overhead to the actual query, specially if the unnecessary columns are of LOB types.
  • Including unnecessary tables in join conditions forces the database engine to retrieve and fetch unnecessary data and increases the query execution time.

2. Don't use "SELECT *" in a SQL query
Unnecessary columns may get fetched and may add expense to the data retrieval time.

3. Do not use the COUNT() aggregate in a subquery to do an existence check
Do not use:

SELECT column_list FROM table WHERE 0 < (SELECT count(*) FROM table2 WHERE ..)

Instead, use:

SELECT column_list FROM table WHERE EXISTS (SELECT * FROM table2 WHERE ...)

  • When you use COUNT(), SQL Server does not know that you are doing an existence check. It counts all matching values, either by doing a table scan or by scanning the smallest non-clustered index.
  • When you use EXISTS, SQL Server knows you are doing an existence check. When it finds the first matching value, it returns TRUE and stops looking. The same applies to using COUNT() instead of IN or ANY.

4. Try to avoid joining between two different types of columns
  • When joining between two columns of different data types, one of the columns must be converted to the type of the other. The column whose type is lower is the one that is converted.
  • If you are joining tables with incompatible types, one of them can use an index, but the query optimizer cannot choose an index on the column that it converts. For example:

SELECT column_list FROM small_table, large_table WHERE
smalltable.float_column = large_table.int_column

In this case, SQL Server converts the integer column to float, because int is lower in the hierarchy than float. It cannot use an index on large_table.int_column, although it can use an index on smalltable.float_column.

5. Try to avoid dynamic SQL
Unless really required, try to avoid the use of dynamic SQL because:
  • Dynamic SQL is hard to debug and troubleshoot.
  • If the user provides the input to the dynamic SQL, then there is possibility of SQL injection attacks.

6. Try to avoid the use of temporary tables
  • Unless really required, try to avoid the use of temporary tables. Try to use table variables in place of temporary tables.
  • In 99% of cases, table variables reside in memory, hence it is a lot faster. Temporary tables reside in the TempDb database. So operating on temporary tables require inter database communication and hence will be slower.

6. Try to avoid the use of NOT IN and IN
  • When you are writing queries containing NOT IN, then this is going to offer poor performance as the optimizer need to use nested table scan to perform this activity. This can be avoided by using EXISTS or NOT EXISTS.
  • When there is a choice to use IN or EXIST, we should go with EXIST clause for better performance.

7. Try to use UNION to implement an "OR" operation
  • Try not to use "OR" in a query. Instead use "UNION" to combine the result set of two distinguished queries. This will improve query performance.
  • Better use UNION ALL if a distinguished result is not required. UNION ALL is faster than UNION as it does not have to sort the result set to find out the distinguished values.

8. Try to use WITH(NOLOCK) in SELECT statements
  • WITH(NOLOCK) hint is an explicit command directed at a specific table or view used to set the transaction isolation level against the table or tables within a view for a query. Once issued, locks will not be used against the data within the table. 
  • The advantage to this is there is no chance a deadlock will occur against any other queries running against the table. The other indirect advantage is that less memory will be used in order to hold locks against that data.

9. Implement the following good practices in User Defined Functions
  • Do not call functions repeatedly within your Stored Procedures, triggers, functions, and batches. For example, you might need the length of a string variable in many places of your procedure, but don't call the LEN function whenever it's needed; instead, call the LEN function once, and store the result in a variable for later use.

9. Implement the following good practices in Stored Procedures
  • Do not use "SP_XXX" as a naming convention. It causes additional searches and added I/O (because the system Stored Procedure names start with "SP_"). Using "SP_XXX" as the naming convention also increases the possibility of conflicting with an existing system Stored Procedure.
  • Use "Set Nocount On" to eliminate extra network trip.

10. Implement the following good practices in Triggers
  • Try to avoid the use of triggers. Firing a trigger and executing the triggering event is an expensive process.
  • Never use triggers that can be implemented using constraints.
  • Do not use the same trigger for different triggering events (Insert, Update, Delete).
  • Do not use transactional code inside a trigger. The trigger always runs within the transactional scope of the code that fires the trigger.

11. Implement the following good practices in Views
  • Use views for re-using complex TSQL blocks and to enable it for indexed views.
  • Do not use views that retrieve data from a single table only (that will be an unnecessary overhead). Use views for writing queries that access columns from multiple tables.

12. Implement the following good practices in Transactions
  • Start a transaction as late as possible and commit/rollback the transaction as fast as possible to reduce the time period of resource locking.

13. Implement a lazy loading strategy for large objects
  • Store Large Object columns (like VARCHAR(MAX), Image, Text etc.) in a different table than the main table, and put a reference to the large object in the main table.
  • Retrieve all the main table data in a query, and if a large object is required to be loaded, retrieve the large object data from the large object table only when it is required.

14. Use VARCHAR(MAX), VARBINARY(MAX), and NVARCHAR(MAX)

  • In SQL Server 2000, a row cannot exceed 8000 bytes in size. This limitation is due to the 8 KB internal page size of SQL Server. So to store more data in a single column, you need to use TEXT, NTEXT, or IMAGE data types (BLOBs) which are stored in a collection of 8 KB data pages.
  • These are unlike the data pages that store other data in the same table. These pages are arranged in a B-tree structure. These data cannot be used as variables in a procedure or a function, and they cannot be used inside string functions such as REPLACE, CHARINDEX, or SUBSTRING. In most cases, you have to use READTEXT, WRITETEXT, and UPDATETEXT.
  • To solve this problem, VARCHAR(MAX), NVARCHAR(MAX) and VARBINARY(MAX) were introduced in SQL Server 2005. These data types can hold the same amount of data BLOBs can hold (2 GB), and they are stored in the same type of data pages used for other data types.
  • When data in a MAX data type exceeds 8 KB, an over-flow page is used (in the ROW_OVERFLOW allocation unit), and a pointer to the page is left in the original data page in the IN_ROW allocation unit.

How to show masking with message (ex. Please wait..) in jquery?


You may need to implement a functionality in your website that when a user clicks on submit button or any link then there should be something to tell user that application is doing something behind the scene and please wait before completing this task. Application should show a user friendly message like "Please wait...", "Saving.." etc. on occurring of some event like button click, link click etc.

Here I will be letting you know how to implement this type of functionality in your website.

Html:

<div id='mask'>
</div>
<div id="divShowLoading" class="loading" style="display: none; position: fixed !important">
   <div id="divShowLoadingText" class="loading_text">
   </div>   
</div>

These divs will be using to show message. 
"mask" div is for showing masking.
"divShowLoading" div is parent div containing text to be shown.
"divShowLoadingText" div is for showing actual text.

By default these divs will be invisible. When user will trigger an event lick click on button they will be showing using jquery code. It is recommended to keep this code in master page as masking will be implemented throughout the website.

CSS:

#mask
{
       position: absolute;
       left: 0;
       top: 0;
       background: #000;
}
.loading
{
    position: fixed !important;
    width:180px;
    background:#008dc4;
    background: -moz-linear-gradient(top,#008dc4 0%,#37b4e4 100%);
    background: -webkit-gradient(linear,left top,left bottom,color-stop(0%,#008dc4),color-   stop(100%,#37b4e4));
    background: -webkit-linear-gradient(top,#008dc4 0%,#37b4e4 100%);
    background: -o-linear-gradient(top,#008dc4 0%,#37b4e4 100%);
    background: -ms-linear-gradient(top,#008dc4 0%,#37b4e4 100%);
    background: linear-gradient(top,#008dc4 0%,#37b4e4 100%);
    border-color: white;
    color: white !important;
    border-radius: 8px;
    -moz-border-radius: 8px;
    -webkit-border-radius: 8px;
    height: 40px;
    padding-top: 20px;
    text-decoration: none;
    position: absolute;
    display: none;
    z-index: 5000001 !important
 }
.loading_text
{
    font: 20px "Trebuchet MS";
    text-align: center;
    margin-bottom: 15px

}

Paste this code in your .css file. 

Java Script:

function ShowLoading(TrueOrFalse, Message, BoxWidth) {
    if (TrueOrFalse == true) {
        var maskHeight = $(window).height();
        var maskWidth = $(window).width();
        $('#mask').css({ 'width': $(window).width(), 'height': $(document).height() });
        $('#mask').fadeTo("fast", .5);
        $('#mask').css({ 'z-index': '500' });
        $('#divShowLoadingText').html(Message);
        $("#divShowLoading").css({ 'top': maskHeight / 2 - (($("#divShowLoading").height() / 2) + 60), 'left': maskWidth / 2 - $("#divShowLoading").width() / 2, 'display': 'block', width: BoxWidth });
        BringLoadingtoFront_Popup();
        $("#divShowLoadingText").show();
    }
    else if (TrueOrFalse == false) {
        $('#mask').css({ 'display': 'none' });
        $('#divShowLoading').css({ 'display': 'none' });
    }
    else {
        $('#divShowLoadingText').html(TrueOrFalse);
    }
}
function BringLoadingtoFront_Popup() {
    $('#divShowLoading').css({ 'z-index': '10000' });
    $("#divShowLoadingText").css({ 'z-index': '10001' });

}

Place this code in a new javascript file and add reference of this file in you master page. Do not forget to add reference of core java script file before reference of this file.

"ShowLoading" function will be used to show messages with mask. This function has 3 parameters:

TrueOrFalse: Whether masking will be shown or hide. Valid values: true, false
Message: Message to be shown in masking.
BoxWidth: Width of box in which message will be showing.


Html (Actual Page):

<script type="text/javascript">
    $(document).ready(function () {
        $("a").click(function () {
            ShowLoading(true, "Please Wait...", 250);
        });
    });

</script>

Now you just need to call "ShowLoading" function on occurring of any event. In this example i have called this function on clicking of all links.
I have passed "true" in first parameter because i want to show message on clicking on all link elements.
I have passed "Please Wait..." in message parameter as i want to show this message on clicking on all link elements.
I have passed 250 as width of box.

Saturday, February 21, 2015

How to increase the performance of asp.net website?

1. Avoid Inline Code

Avoid inline css styles code, place them in css file.
Avoid inline java-script code, place them in separate java-script file.


2. Placement of JavaScript file

When scripts are defined on top of the page they can take unnecessary time to load. It's better to display the HTML contents of a page firstly and then load any scripting code. So place javascript file reference bottom of page content.

3. Optimize css file

Clean up style sheets and remove unnecessary code from style sheets because it increases the load time. Remove all unnecessary classes from style sheets and try to use a single CSS file. CSS files are normally cached by browsers, so a single and heavy .css file doesn't cause a long wait on each page request.

4. Minify Resources

Since every unnecessary piece of code adds to the size of your page, it’s important that you eliminate extra spaces, line breaks, and indentation in your code so your pages are as lean as possible. You can achieve it by minification so minify your java-script files and css files.

5. Optimize Images

With images, you need to focus on three things: size, format and the src attribute.

Image Size:
  • Crop your images to the correct size. For instance, if your page is 570px wide, resize the image to that width. Don’t just upload a 2000px-wide image and set the width parameter (width=”570”). This slows your page load time and creates a bad user experience.
  • Reduce color depth to the lowest acceptable level.
  • Remove image comments.

Image Format:
  • Do not use BMPs or TIFFs.
  • JPEG is the best option.
  • PNG is also good option but older browsers may not fully support it.
  • GIFs should only be used for small or simple graphics (less than 10×10 pixels, or a color palette of 3 or fewer colors) and for animated images.

Src attribute:
Avoid empty image src codes. In HTML, the code for an image includes this:

<img src=””>

When there’s no source in the quotation marks, the browser makes a request to the directory of the page or to the actual page itself. This can add unnecessary traffic to your servers and even corrupt user data.

6. Http Compression

HTTP compression is used to compress page content from the server end. It compress HTTP requests and responses, so is a great performance improvement

7. Disable possible ViewState

View State allows the page state to be persisted with the client, and it does not require cookies or server memory. View State saves data in a hidden input filed inside a page. Definitely, it is a powerful feature, but the drawback is it increases page size and memory allocation in the server.

So, we should avoid View State where it is not necessary. Especially, in the case of DataGrid controls, we should avoid View State as it loads all the grid data in the page state.

8. Server.Transfer() instead of Response.Redirect()

Search your code for “Response.Redirect” and consider replacing it with Server.Transfer. This does not incur the cost of a new request because it avoids any client-side redirection.

9. Proper use of "Page.IsPostBack"

Make sure it is properly used to avoid repetition code execution. Check that the logic in your page uses the Page.IsPostBack property to reduce redundant processing and avoid unnecessary initialization costs. Use the Page.IsPostBack property to conditionally execute code, depending on whether the page is generated in response to a server control event or whether it is loaded for the first time.

10. More use of client side validation

Validate user input on the client to reduce round trips to the server. This also provides better feedback to the user. For security reasons, ensure that any client-side validation is complimented with the equivalent server-side validation

11. Deploying Production Code in Release Mode

Check your Web.config file and ensure debug is set to false in the <compilation> section and check your .aspx pages to ensure debug is set to false. If debugging is enabled, the compiler does not generate optimized code and pages are not batch compiled. 

12. Proper use of server controls

Evaluate your use of server controls to determine if you can replace them with light weight HTML controls or possibly static text. You might be able to replace a server control under the following conditions:
  • The data being displayed in the control is static, for example, a label.
  • You do not need programmatic access to the control on the server side.
  • The control is displaying read-only data.
  • The control is not needed during post back processing.

13. Manage Strings Efficiently
  • Use += for concatenating stringsIdentify places in your code where you perform string concatenation by using the += operator. If the number of appends is unknown, or you are appending an unknown size of data, consider using the StringBuilder class instead.
  • Use strString=string.Empty instead of strString="" or strString=null

14. Proper use of caching
  • Check your pages that use the output cache to ensure that the number of variations has a limit. Too many variations of an output cached page can cause an increase in memory usage. You can identify pages that use the output cache by searching for the string “OutputCache”.
  • When reviewing your pages, start by asking yourself if the whole page can be cached. If the whole page cannot be cached, can portions of it be cached? Consider using the output cache even if the data is not static. If your content does not need to be delivered in near real-time, consider output caching. 
  • Using the output cache to cache either the entire page or portions of the page can significantly improve performance.
  • Identify application-side data that is static or infrequently updated. This type of data is a great candidate for storing in the cache like “Contact us” and “About us” pages.
  • Checking for null before accessing the cached item as shown in the following code fragment.

15. div instead of table

Replace table with div wherever possible as it increase performance. Read my another blog for div vs table.

What is jQuery?

jQuery is not a language but it is a well written code. jQuery is a set of JavaScript libraries that have been designed specifically to simplify HTML document traversing, animation, event handling, and Ajax interactions

There are many other JavaScript code libraries such as MooTools, but jQuery has become the most popular because it is so easy to use

Prerequisite
To start work on jQuery, you should be aware of the basics of JavaScript, HTML and CSS

License
jQuery is free, open source software Dual-licensed under the MIT License and the GNU General Public License. Microsoft has integrated jQuery officially into its IDE Visual Studio 2010 and jQuery intellisense is available in Visual Studio 2010 and higher version now.

Why use jQuery?

  • It helps to improve the performance of the application.
  • It simplifies the task of creating highly responsive web pages.
  • It helps to develop most browser compatible web page as it works across modern browsers.
  • It helps to implement UI related critical functionality without writing hundreds of lines of codes.
  • It abstracts away browser-specific features, allowing you to concentrate on design.
  • It leverages your existing knowledge of CSS
  • It performs multiple operations on a set of elements with one line of code (known as statement chaining)
  • Is extensible (so you can use third-party-plug-ins to perform specialized tasks or write your own)

Browser Compatibility

Currently compatible with modern version of all the main browsers in use today

BrowserWorks WithKnown Issues With
Internet Explorer6.0 and greater1.0 through 5.x
Safari3 and greater1.0 through 2.1
Chrome1 and greaterN/A
Firefox2 and greater1.0.x
Opera9 and greater1.0 through 8.x

Downloading jQuery

jQuery comes in two versions:
  1. Development
  2. Production (which is compressed and minified)
jQuery file can be downloaded from jQuery Official website.

Typically, you download both versions and then use each one for its intended purpose

How to use jQuery?

Use as local file:

<script src="jquery-1.6.1.min.js" type="text/javascript"></script>

Ideally, this markup is kept in under <head></head> tag of your web page, however you are free to keep anywhere you want.

Loading jQuery from CDN:
CDN Stands for Content Distribution Network or also called Content Delivery Network is a group of computers placed at various points connected with network containing copies of data files to maximize bandwidth in accessing the data. In CDN, a client accesses a copy of data nearer to the client location rather than all clients accessing from the one particular server. This helps to achieve better performance of data retrieval by client.

There are two leading CDNs available that host jQuery files: Microsoft & Google


<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>

Friday, February 20, 2015

div vs table

DIV

Advantage:

  1. Lesser code i.e. Lesser code = smaller files = faster load time

Disadvantage:

  1. Require knowledge of css
  2. Some older Web browsers do not display pages designed with div tags properly because these older browsers do not work well with CSS so may need to provide fixes for older browsers
  3. Displaying of data such as a calendar or a price list is time consuming and would require significant amount of code

Table

Advantage:
  1. No need for css knowledge
  2. Easy to implement
  3. Displaying of data such as a calendar or a price list is easy

Disadvantage:
  1. Large amount of code i.e. More code = large files = slower to load page
  2. Significant amount of time to make modifications site wide