Hello, Welcome to my blog. If you like feel free to refer others

Monday, 23 January 2012

Create a function to determine Leap year or not

CREATE FUNCTION dbo.fn_IsLeapYear (@year int)
    WHEN 2 THEN 1
    ELSE 0

Happy Learning........

ASP .Net Web Page Optimization Checklist

Checklist for all pages

Here is the list of checks that you need to run, not necessarily in order:
  • Disable ViewState - Set "EnableViewState=false" for any control that does not need the view state. As a general rule if your page does not use postback, then it is usually safe to disable viewstate for the complete page itself.

  • Use Page.Ispostback is used in Page_Load - Make sure that all code in page_load is within "if( Page.Ispostback)" unless it specifically needs to be executed upon every Page Load.

  • Asynchronous calls for Web Services - If you are using Web Services in you page and they take long time to load, then preferably use Asynchronous calls to Web Services where ever applicable and make sure to wait for end of the calls before the page is fully loaded. But remember Asynchronous calls have their own overheads, so do not overdo it unless needed.

  • Use String Builder for large string operations - For any long string operations, use String Builder instead.

  • Specialized Exception Handling - DO not throw exceptions unless needed, since throwing an exception will give you a performance hit. Instead try managing them by using code like "if not system.dbnull ." Even you if you have to handle an exception then de-allocate any memory extensive object within "finally" block. Do not depend on Garbage Collector to do the job for you.

// Try
//        'Create Db Connection and call a query
//        sqlConn = New SqlClient.SqlConnection(STR_CONN)
// Catch ex As Exception
//        'Throw any Error that occurred
//        Throw ex
// Finally
//        'Free Database connection objects
//        sqlConn = Nothing
//End Try

  • Leave Page Buffering on - Leave Page buffering On, unless specifically required so. Places where you might require to turn it on in case of very large pages so that user can view something while the complete page is loading.

  • Use Caching - Cache Data whenever possible especially data which you are sure won't change at all or will be reused multiple times in the application. Make sure to have consistent cache keys to avoid any bugs. For simple pages which do not change regularly you can also go for page Caching

// <% @OutputCache Duration="60" VaryByParam="none" %>

Learn more about "VaryByParam" and "VaryByControl" for best results.

  • Use Script files - As a rule unless required do not insert JavaScript directly into any page, instead save them as script file ".js" and embed them. The benefit being that common code can be shared and also once a script file is loaded into browser cache, it is directly picked up from browser cache instead of downloading again.

  • Remove Unused Javascript - Run through all Javascript and make sure that all unused script is removed.

  • Remove Hidden HTML when using Tabstrip - In you are using a Tabstrip control and if the HTML size is too large and the page does frequent reloads, then turn Autopostback of Tabstrip on, put each Pageview inside a panel and turn visibility of all Panels except the current one to False. This will force the page to reload every time a tab is changed however the reload time will reduce heavily. Use your own jurisdiction to best use.

Additional Checklist for performance critical pages

  • Disable session when not using it - If your page does not use session then disable session specifically for that page.
// '<%@ Page EnableSessionState="false" %>

If the page only reads session but does not write anything in session, then make it read only.
// '<%@ Page EnableSessionState="ReadOnly" %>

  • Use Option Strict On (VB .Net only) - Enabling Option Script restricts implicit type conversions, which helps avoid those annoying type conversion and also is a Performance helper by eliminating hidden type conversions. I agree it takes away some of you freedom, but believe me the advantages outweigh the freedom.

  • Use Threading - When downloading huge amounts of data use Threading to load Data in background. Be aware, however, that threading does carry overhead and must be used carefully. A thread with a short lifetime is inherently inefficient, and context switching takes a significant amount of execution time. You should use the minimum number of long-term threads, and switch between them as rarely as you can.

  • Use Chunky Functions - A chunky call is a function call that performs several tasks. you should try to design your application so that it doesn't rely on small, frequent calls that carry so much overhead.

  • Use Jagged Arrays - In case you are doing heavy use of Multi Dimensional Arrays, use Jagged Array ("Arrays of Arrays") Instead

  • Use "&" instead of "+" - You should use the concatenation operator (&) instead of the plus operator (+) to concatenate strings. They are equivalent only if both operands are of type String. When this is not the case, the + operator becomes late bound and must perform type checking and conversions.

  • Use Ajax - In performance critical application where there are frequent page loads, resort to Ajax.

  • Use the SqlDataReader class - The SqlDataReader class provides a means to read forward-only data stream retrieved from a SQL Server database. If you only need to read data then SqlDataReader class offers higher performance than the DataSet class because SqlDataReader uses the Tabular Data Stream protocol to read data directly from a database connection

  • Choose appropriate Session State provider - In-process session state is the fastest solution. If you store only small data in session state, go for in-process provider. The out-of-process solutions is useful if you scale your application across multiple processors or multiple computers.

  • Use Stored Procedures - Stored procedures are pre-compiled and hence are much faster than a direct SQL statement call.

  • Use Web Services with care - Web Services depending on data volume can have monstrous memory requirements. Do not go for Web Services unless your Business Models demands it.

  • Paging in Database Side - When you needs to display large amount of Data to the user, go for a stored procedure based Data Paging technique instead of relying on the Data Grid/ Data List Paging functionality. Basically download only data for the current page.

Use HTML controls whenever possible
HTML controls is lighter than server controls especially if you are using server controls with its default properties. Server controls generally is easier to use than HTML controls, and on the other side they are slower than HTML controls. So, it is recommended to use HTML controls whenever possible and avoid using unnecessary server controls.

Avoid round trips to server whenever possible
Using server controls will extensively increase round trips to the server via their post back events which wastes a lot of time. You typically need to avoid these unnecessary round trips or post back events as possible. For example, validating user inputs can always (or at least in most cases) take place in the client side. There is no need to send these inputs to the server to check their validity. In general you should avoid code that causes a round trip to the server.

The Page.IsPostBack Property
The Page.IspostBack Boolean property indicates whether this page is loaded as a response to a round trip to the server, or it is being loaded for the first time. This property helps you to write the code needed for the first time the page is loaded, and avoiding running this same code each time the page is posted back. You can use this property efficiently in the page_load event. This event is executed each time a page is loaded, so you can use this property conditionally to avoid unnecessary re-running of certain code.

Server Control's AutoPostBack Property
Always set this property to false except when you really need to turn it on. This property automatically post back to the server after some action takes place depending on the type of the control. For example, in the Text Control this property automatically post back to the server after the text is modified which is a great deal of processing cost and hence much slower performance and most importantly a poor user experience.

Leave Buffering on
It is important to leave page buffering in its on state to improve your page speed, unless you have a serious reason to turn it off.

Server Controls View State 
Server control by default saves all the values of its properties between round trips, and this increases both page size and processing time which is of course an undesired behavior. Disable the server control view state whenever possible. For example, if you bind data to a server control each time the page is posted back, then it is useful to disable the control's view state property. This reduces page size and processing time.

Methods for redirection
There are many ways you can use to redirect a user from the current page to another one in the same application, however the most efficient methods to do this are: the Server.Transfer method or cross-page posting.

Web Applications

The following topics give you some tips about how to make an efficient web application:

When an already deployed ASP.NET web application page is requested for the first time, that page needs to be compiled (by the server) before the user gets a response. The compiled page or code is then cached so that we need not to compile it again for the coming requests. It is clear that the first user gets a slow response than the following users. This scenario is repeated for each web page and code file within your web site.
When using precompilation then the ASP.NET entire web application pages and code files will be compiled ahead. So, when a user requests a page from this web application he will get it in a reasonable response time whatever he is the first user or not.
Precompiling the entire web application before making it available to users provides faster response times. This is very useful on frequently updated large web applications.

By default ASP.NET applications use UTF-8 encoding. If your application is using ASCII codes only, it is preferred to set your encoding to ASCII to improve your application performance.

It is recommended to turn authentication off when you do not need it. The authentication mode for ASP.NET applications is windows mode. In many cases it is preferred to turn off the authentication in the 'machin.config' file located on your server and to enable it only for applications that really need it.

Debug Mode
Before deploying your web application you have to disable the debug mode. This makes your deployed application faster than before. You can disable or enable debug mode form within your application's 'web.config' file under the 'system.web' section as a property to the 'compilation' item. You can set it to 'true' or 'false'.

Coding Practices

The following topics give you guidelines to write efficient code:

Page Size
Web page with a large size consumes more bandwidth over the network during its transfer. Page size is affected by the numbers and types of controls it contains, and the number of images and data used to render the page. The larger the slower, this is the rule. Try to make your web pages small and as light as possible. This will improve response time.

Exception Handling
It is better for your application in terms of performance to detect in your code conditions that may cause exceptions instead of relying on catching exceptions and handling them. You should avoid common exceptions like null reference, dividing by zero , and so on by checking them manually in your code.
The following code gives you two examples: The first one uses exception handling and the second tests for a condition. Both examples produce the same result, but the performance of the first one suffers significantly.
   ‘This is not recommended.
            Output = 100 / number
   Catch ex As Exception
            Output = 0
   End Try
   ' This is preferred.
   If Not (number = 0) Then
            Output = 100 / number
            Output = 0
   End If

Garbage Collector
ASP.NET provides automatic garbage collection and memory management. The garbage collector's main task is to allocate and release memory for your application. There are some tips you can take care of when you writing your application's code to make the garbage collector works for your benefit:
Avoid using objects with a Finalize sub as possible and avoid freeing resources in Finalize functions.
Avoid allocating too much memory per web page because the garbage collector will have to do more work for each request and this increases CPU utilization (not to mention you can go out of memories in larger web applications)
Avoid having unnecessary pointers to objects because this makes these objects alive until you free them yourself within your code not in an automatic way.

Use Try / Finally
If you are to use exceptions anyway, then always use a try / finally block to handle your exceptions. In the finally section you can close your resources if an exception occurred or not. If an exception occurs, then the finally section will clean up your resources and frees them up.

String Concatenation
Many string concatenations are time consuming operations. So, if you want to concatenate many strings such as to dynamically build some HTML or XML strings then use the System.Text.StringBuilder object instead of system.string data type. The append method of the StringBuilder class is more efficient than concatenation.

If your application contains some operation that consumes time and resources, then instead of blocking the application flow awaiting for this process or operation to be finished it is recommended to create a separate thread for this blocking operation. By threading you will save your application normal flow from delays. Examples of time consuming operations that can be moved to another thread other than the main program thread are: querying on a database and waiting for results, and extensive IO operations.

Solve IE6 Problems

Here are some tips to solve the majority of IE6 problems with valid HTML and CSS code:

1. Use a DOCTYPE
You should always place a DOCTYPE at the top of every HTML page and a strict version is recommended, i.e.
Or, for XHTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
The last thing you need is IE6 going into quirks mode – it’s quirky enough already.

2. Set position: relative
Setting an element to
position:relative solves a multitude of problems, especially if you have ever experienced invisible or strangely aligned boxes. Obviously, you need to be careful that absolutely-positioned child nodes are repositioned accordingly.

3. Use display:inline for floated elements
Floated elements with a margin can fire the famous IE6 double-margin bug, e.g. you specify a left margin of 5px and actually get 10px. display:inline will fix the problem and, although it should not be required, your CSS remains valid.

4. Set an element to hasLayout
Many of IE6′s (and IE7′s) rendering issues can be fixed by setting the element’s hasLayout property. This is an internal IE setting that determines how content is bounded and positioned in relation to other items. Setting hasLayout can also be essential if you need to make an inline element such as a link into a block or apply transparency effects.
The easiest way to set hasLayout is to set a CSS height or width (zoom can also be used, but that is not part of the CSS standard). Setting the actual dimensions is recommended but, where that is not possible, you may be able to use height:1%. If the parent element has no set height, the element’s physical height is not affected but hasLayout is enabled.

5. Fixing the repeated characters bug
Complex layouts can trigger a bug where the last few characters of a floated element can appear on the cleared element below. There are several solutions; few are ideal and a little trial and error will be required:
  • ensure all floated elements use display:inline;
  • use a margin-right:-3px; on the last floated element
  • use a conditional comment as the last item in the floated element, i.e. <!--[if !IE]>Put your commentary in here...<![endif]-->
  • use an empty div in the last element of the container (it can also be necessary to set the width to 90% or similar)

6. Use only <a> tags for clickable and hovered elements
IE6 can only apply CSS hover effects to <a> tags.
You should also use them for controls within JavaScript-powered widgets so they remain keyboard navigable. There are some alternative options, but <a> tags are more reliable than most solutions.

7. Use !important or advanced selectors for IE-specific code
It is still possible to write valid code that specifically targets IE6 without resorting to traditional hacks or conditional CSS in additional files. For example, minimum heights can be defined using the code:

#element {
                min-height: 20em;
                height: auto !important; /* understood by all browsers */
                height: 20em; /* IE6 incorrectly uses this value /*
IE6 does not understand ‘min-height’ and incorrectly overrides the ‘auto’ height with 20em. However, it then increases the dimensions if the content requires more room.
Another option is to use advanced selectors, e.g.

#element {
                min-height: 20em;
                height: 20em;
/* ignored by IE6 */
#element[id] {
                 height: auto;

8. Avoid percentage dimensions
Percentages confuse IE. Unless you can carefully size every parent element, they are probably best avoided. You can still use percentage values in other browsers with !important, e.g.

body {
                margin: 2% 0 !important;
                margin: 20px 0; /* IE6 only */

9. Test early and test often
Never leave IE6 testing until your website or application is complete; the problems will be worse and take longer to fix. If your site works in Firefox and IE6, it is almost certain to work in other browsers.

10. Refactor your code
Often, it can take longer to fix than re-think a layout problem. Minor alterations to the HTML and simpler CSS are often more effective. This may mean you abandon perfectly legitimate code, but fewer long-term issues will arise and you know how to handle the problem in future.

 Happy learning.......enjoy :)

Friday, 20 January 2012

Convert your datatable to Collection of Generic List using Reflection

First you need to add the reference of the dll, "System.Reflection".

Then I have created a static function in my class that will convert my datatable to a generic list:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.Data;
using BusinessEntity;

namespace DataLayer.Entitymapper
    public static class EntityBinder
        public static List<T> ToCollection<T>(this DataTable dt)
            List<T> lst = new System.Collections.Generic.List<T>();
            Type tClass = typeof(T);
            PropertyInfo[] pClass = tClass.GetProperties();
            List<DataColumn> dc = dt.Columns.Cast<DataColumn>().ToList();
            T cn;
            foreach (DataRow item in dt.Rows)
                cn = (T)Activator.CreateInstance(tClass);
                foreach (PropertyInfo pc in pClass)
                   DataColumn d = dc.Find(c => c.ColumnName == pc.Name);
                   if (d != null)
                       if (item[pc.Name] != DBNull.Value)
                           pc.SetValue(cn, (item[pc.Name]), null);
            return lst;

How to call: In my DataLayer Project I have created a class ResourceDAL.

Now i will create a function where i will pass the datatable and EntityBinder class ToCollection method will convert it into generic list of resources.

public List<ResourceBE> GetResource()
                 DataSet DS = SqlHelper.ExecuteDataset(RTSSqlConnection.GetConnectionString, CommandType.StoredProcedure, "usp_GetResources");
                 DataTable dt = DS.Tables[0];

                 //return dt;
                 List<ResourceBE> listResource = EntityBinder.ToCollection<ResourceBE>(dt);
                 return listResource;
            catch(Exception ex)
                throw new Exception(ex.ToString());

So this function will return now a list of resources......

Happy learning............................:)

Select Cuts Off Options In IE7 and above (Fix)

This is common problem for all now a days:

I have used this to solve my problem for IE version 7 and above. Surely it will work.

Solution 1:

I have added this on my HTML select control.

<select class="limited-width" onmousedown="if(document.all) this.className='expanded-width';"
                        onblur="if(document.all) this.className='limited-width';" onchange="if(document.all) this.className='limited-width';">
                        <option>Short option</option>
                        <option>Much longer option that will overflow the select</option>

CSS class is defined as follows:
 <style type="text/css">
    width: 125px;
    position: static;
    width: auto;
    position: absolute;

Solution 2 : using JQuery

<script src="JS/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="JS/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="JS/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(function ($) {

            $.fn._ie_select = function () {

                return $(this).each(function () {

                    var a = $(this),
                            p = a.parent();

                    p.css('position', 'relative');

                    var o = a.position(),
                            h = a.outerHeight(),
                            l = o.left,
                            t = o.top;

                    var c = a.clone(true);

                    $.data(c, 'element', a);

                        zIndex: 100,
                        height: h,
                        top: t,
                        left: l,
                        position: 'absolute',
                        width: 'auto',
                        opacity: 0
                        id: this.id + '-clone',
                        name: this.name + '-clone'
                    }).change(function () {
                        $.data(c, 'element')

                    a.before(c).click(function () {

                }); // END RETURN

            }; // END PLUGIN

            // Usage
            if ($.browser.msie) {


Hope this will help you....

Happy Learning..........................Enjoy....:)