Sunday, August 5, 2012

Javascript Anonymous Functions And The Module Pattern

One of the most annoying things about JavaScript is that it has no scope for variables. Any variable, function, array or object you define that is not inside another function is global, which means that other scripts on the same page can access—and will usually override— them.
The workaround is to encapsulate your variables in an anonymous function and call that function immediately after you define it. For example, the following definition would result in three global variables and two global functions:

var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
  // [...]
}
function getMemberDetails(){
  // [...]
}

Any other script on the page that has a variable named status could cause trouble. If we wrap all of this in a name such as myApplication, then we work around that issue:

 var myApplication = function(){
  var name = 'Chris';
  var age = '34';
  var status = 'single';
  function createMember(){
    // [...]
  }
  function getMemberDetails(){
    // [...]
  }
}();
This, however, doesn't do anything outside of that function. If this is what you need, then great. You may as well discard the name then:

  (function(){
  var name = 'Chris';
  var age = '34';
  var status = 'single';
  function createMember(){
    // [...]
  }
  function getMemberDetails(){
    // [...]
  }
})();
If you need to make some of the things reachable to the outside, then you need to change this. In order to reach createMember() or getMemberDetails(), you need to return them to the outside world to make them properties of myApplication:

var myApplication = function(){
  var name = 'Chris';
  var age = '34';
  var status = 'single';
  return{
    createMember:function(){
      // [...]
    },
    getMemberDetails:function(){
      // [...]
    }
  }
}();
// myApplication.createMember() and 
// myApplication.getMemberDetails() now works.


This is called a module pattern or singleton. It was mentioned a lot by Douglas Crockford and is used very much in the Yahoo User Interface Library YUI. What ails me about this is that I need to switch syntaxes to make functions or variables available to the outside world. Furthermore, if I want to call one method from another, I have to call it preceded by the myApplication name. So instead, I prefer simply to return pointers to the elements that I want to make public. This even allows me to shorten the names for outside use:

 var myApplication = function(){
  var name = 'Chris';
  var age = '34';
  var status = 'single';
  function createMember(){
    // [...]
  }
  function getMemberDetails(){
    // [...]
  }
  return{
    create:createMember,
    get:getMemberDetails
  }
}();
//myApplication.get() and myApplication.create() now work.

Reffer: "revealing module pattern."
http://coding.smashingmagazine.com/2010/04/20/seven-javascript-things-i-wish-i-knew-much-earlier-in-my-career/

Friday, July 27, 2012

Map SqlReader to Bussiness Entity Collection using Reflection C#

Reflection provides objects (of type Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, Reflection enables you to access them. For more information

Map Data To Business Entity Collection

MapDataToBusinessEntityCollection is a generic Reflective method. We pass in the data-type for the objects to be mapped as a generic parameter along with a data reader. We use reflection to find the properties in this type and we use the meta data in the DataReader to find the fields.

Whenever we find a field from the data reader that has a matching writable property in the generic type, we pull the value from the DataReader and assign it to a newly created object. Regardless of how many properties are in T, this method will map every property that has a matching field in the DataReader. Any properties that are not in the DataReader will be unmapped. Any fields in the data reader that do not have a matching property will be ignored. The validation logic is handled in the implementation of the properties in T.

public static List<T> MapDataToBusinessEntityCollection<T>(IDataReader dr) 
where T : new()
 {
  Type businessEntityType = typeof (T);
  List<T> entitys = new List<T>();
  Hashtable hashtable = new Hashtable();
  PropertyInfo[] properties = businessEntityType.GetProperties();
  foreach (PropertyInfo info in properties)
  {
      hashtable[info.Name.ToUpper()] = info;
  }
  while (dr.Read())
  {
      T newObject = new T();
      for (int index = 0; index < dr.FieldCount; index++)
      {
          PropertyInfo info = (PropertyInfo)
                              hashtable[dr.GetName(index).ToUpper()];
          if ((info != null) && info.CanWrite)
          {
              info.SetValue(newObject, dr.GetValue(index), null);
          }
      }
      entitys.Add(newObject);
  }
  dr.Close();
  return entitys;
}
 

Wednesday, July 25, 2012

Working With Cookies In Javascript

Cookies are variables of temporary data which is stored on the visitors computers. They are normally used for things like remember my username on a login form. This can be a useful way to store information about your returned visitors without them having to log in to store information on a database.

It's worth noting that cookies should not be used to store secure information as they are just files stored on your visitors computer.

You can set a cookie on both the server side and the client side in this article we are going to look at the process you would set-up a cookie on the client side using Javascript.

Raw Javascript

Working with cookies in Javascript is not the best feature of Javascript, there is no easy way of dealing with setting and getting cookies.

All Values

To get all the cookies which are set for the current document you need to use the following.
                var allCookies = document.cookie;
            

Setting Values In Javascript

To set a cookie you need to use the Javascript variable document.cookie, to add values to this you need to setup the data as a query string and add onto the end of the document.cookie.
document.cookie = "website=weblink";
// cookie is website=weblink

If you want to add extra data to the cookie then you just need to repeat the above step.
document.cookie = "secondwebsite=second-site-demo";
// cookie is website=weblink;secondwebsite=second-site-demo;

Now this seems easy to set data but this will not deal with expiring the cookie or domain for the cookie. To set the expiry of the cookie you need to add the expiry on the end of the document.cookie.
document.cookie += "; expires="+date.toGMTString();

To set the domain path of the cookie you then need to set the path on the end of the document.cookie.
            document.cookie += "; path=/";
        

With these factors you can add to just setting data on the cookie it can be difficult to handle you need to write a function to handle the setting of the cookie.
function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

Getting Values

As you can see there is a lot you need to do to set the values on the document.cookie but you will need to do even more to get values out of the document.cookie.
If you want to get a certain value you have set you can't just call the key of the data to get the value you have to use a function which will do a reg ex search to get the value of a key.

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

Easier Way Of Working With Cookies In Javascript

There must be an easier way of handling the cookie data then having to create you own functions to deal with the different scenarios of setting, getting, all cookies, remove cookies, empty all cookies, testing if cookies are enabled.
There is an easier way of working with cookies there is a Github project called cookie.js, this is a simple javascript file which when included on your web page you can easily handle the cookie data.

Cookie.js

To use cookie.js all you have to do is download it from Github and include it on your page, download it from here. Then you can include it on the page by doing using the following code.

            <script src="cookie.min.js" > </script >
        

When this file is included there will be a new cookie object to use to set and get the data.

Setting Cookie

To set a cookie with cookie.js all you have to do is use the method set().

cookie.set( 'key', 'value' );

If you want to add extra parameters to the cookie you can set these up as the third argument on the method.
cookie.set( 'key' , 'value', {
   expires: 7,
   domain: "paulund.co.uk",
   path: "/",
   secure: false
});

Getting Cookie

To get the values from the cookie it is as easy as using the get() method, this will return string of the value of the key.

cookie.get( 'key1' );

Or you can even use a shorthand version of this by just doing.
cookie( 'key1' );

Get All Cookies

To get all the cookies available it is very simple by using the all() method.

var allCookies = cookie.all();

Removing Cookies

It is also easy to remove the cookies by referring to the key you have setup on the cookie, by using the remove() method.

cookie.remove( 'key1' );

You can even remove all cookies available on the domain by using the empty method.

cookie.empty();

Cookies Enabled

Visitors can turn cookies off on the browser so you will not be able to store data on the visitors computer, for this reason you will need to check if cookies are enabled before you try setting up new cookies.
With cookie.js you can do this easily by using the enabled() method.

if (cookie.enabled()) {
   // Cookies are on you can setup cookies
} else {
   // Cookies are turned off you can not use cookies
}

ref:http://www.paulund.co.uk/cookies-with-javascript

Friday, July 6, 2012

Converts a virtual path to an application absolute path - Extension Methods

Converts the provided app-relative path into an absolute Url containing the full host name

   /// App-Relative path
    /// Provided relativeUrl parameter as fully qualified Url
    /// ~/path/to/foo to http://www.web.com/path/to/foo
    public static string GetAbsoluteUrl(string relativeUrl)
    {
        //VALIDATE INPUT
        if (String.IsNullOrEmpty(relativeUrl))
            return String.Empty;

        //VALIDATE INPUT FOR ALREADY ABSOLUTE URL
        if (relativeUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || relativeUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
            return relativeUrl;

        //VALIDATE CONTEXT
        if (HttpContext.Current == null)
            return relativeUrl;

        //GET CONTEXT OF CURRENT USER
        HttpContext context = HttpContext.Current;

        //FIX ROOT PATH TO APP ROOT PATH
        if (relativeUrl.StartsWith("/"))
        {
            relativeUrl = relativeUrl.Insert(0, "~");
        }

        //GET RELATIVE PATH
        Page page = context.Handler as Page;
        if (page != null)
        {
            //USE PAGE IN CASE RELATIVE TO USER'S CURRENT LOCATION IS NEEDED
            relativeUrl = page.ResolveUrl(relativeUrl);
        }
        else //OTHERWISE ASSUME WE WANT ROOT PATH
        {
            //PREPARE TO USE IN VIRTUAL PATH UTILITY
            if (!relativeUrl.StartsWith("~/"))
            {
                relativeUrl = relativeUrl.Insert(0, "~/");
            }

            relativeUrl = VirtualPathUtility.ToAbsolute(relativeUrl);
        }

        var url = context.Request.Url;
        var port = url.Port != 80 ? (":" + url.Port) : String.Empty;

        //BUILD AND RETURN ABSOLUTE URL
        return String.Format("{0}://{1}{2}{3}",
               url.Scheme, url.Host, port, relativeUrl);
    }

Compares to DateTimes and converts the result to an easy human readable

Take this:2012-07-13 17:47:33

and turn it into this:5 minutes 16 seconds ago

   /// 
    /// Compares to DateTimes and converts the result to an easy human readable format.
    /// 
    /// A past or future DateTime.
    /// Relative to this time.
    /// 
    public static string ToRelativeTime(this DateTime time, DateTime relativeTo)
    {
        TimeSpan ts = relativeTo.Subtract(time).Duration();
        string DateFormat = "d MMMM";
        string dir = (relativeTo > time) ? "Ago" : "To go";

        if (relativeTo.Year != time.Year)
            DateFormat += " yyyy";

        if (ts.Days < 360)
        {
            //Months
            if (ts.Days >= 30)
                return string.Format("{0} ({1} Months {2})", time.ToString(DateFormat), (int)(ts.Days / 30), dir);

            //Days
            if (ts.Days > 0)
                return string.Format("{0} ({1} Days {2})", time.ToString(DateFormat), ts.Days, dir);

            //hours
            if (ts.Hours > 0)
                return string.Format("{0} Hours {1} Minutes {2}", ts.Hours, ts.Minutes, dir);

            //minutes
            if (ts.Minutes > 0)
                return string.Format("{0} Minutes {1} Seconds {2}", ts.Minutes, ts.Seconds, dir);

            //seconds
            return string.Format("{0} Seconds {1}", ts.Seconds, dir);
        }

        return time.ToString(DateFormat);
    }

Extension Methods (C# Programming)

Another cool feature of C# is Extension Methods. They allow you to extend an existing type with new functionality, without having to sub-class or recompile the old type. For instance, you might like to know whether a certain string was a number or not. The usual approach would be to define a function and then call it each time, and once you got a whole lot of those kind of functions, you would put them together in a utility class.However, with Extension Methods, you can actually extend the String class to support this directly. You do it by defining a static class, with a set of static methods that will be your library of extension methods. Here is an example:

public static class Helpers
{
    public static bool isNumber(this object inputvalue)
    {
        if (inputvalue == null) return false;
        Regex isnumber = new Regex("[^0-9]");
        return !isnumber.IsMatch(inputvalue.ToString());
    }

    public static bool isNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}
    

The only thing that separates this from any other static method, is the "this" keyword in the parameter section of the method. It tells the compiler that this is an extension method for the string class, and that's actually all you need to create an extension method. Now, you can call the isNumber() method directly on strings, like this:

     string test = "4";
     if (test.isNumber())
      Console.WriteLine("Yes");
    else
      Console.WriteLine("No");
    
    
Ref:


Friday, June 22, 2012

Crop Image in ASP.NET using JCrop, JQuery

You might have seen various websites and web application giving features to Crop your image and save it. That can be done in DHTML or in Javascript. Lets see one example of doing it with the help of JCrop which can be download from here (JCrop)



How to start

1. First include the following file into your project

  • jquery.Jcrop.js
  • jquery.Jcrop.min.js
  • jquery.min.js
or you can directly drag and drop the JCrop folder in your project

2. We need to write code in our page. Include the JQuery function in the page and also add one event for crop control for updation of the cordinates in the variable on selection by users. Check the head section of the page given below

                    <head runat="server">
                        <title></title>
                        <script src="js/jquery.min.js"></script>
                        <script src="js/jquery.Jcrop.min.js"></script>
                        <link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
                        <script language="Javascript">
                            jQuery(document).ready(function () {  
                                 // Create variables (in this scope) to hold the API and image size
        var jcrop_api, boundx, boundy;                              
                                $('#cropbox').Jcrop({
                                    onChange: updatePreview,
                                    onSelect: updatePreview,
                                    aspectRatio: 1,
                                    boxWidth: 450,
                                    boxHeight: 400,
                                    maxSize: [300, 300],
                                    minSize: [200, 200]
                                }, function () {
                                    // Use the API to get the real image size
                                    var width = $('#cropbox').width();
                                    var height = $('#cropbox').height();
                                    var rect = new Array();
                                    rect[0] = 1;
                                    rect[1] = 1;
                                    rect[2] = width - 1;
                                    rect[3] = height - 1;
                                    if (width >= 300) {
                                        rect[0] = width / 6;
                                        rect[2] = width - 100;
                                    }
                                    if (height >= 300) {
                                        rect[1] = 10;
                                        rect[3] = height - (height / 4);
                                    }
                                    var bounds = this.getBounds();
                                    boundx = bounds[0];
                                    boundy = bounds[1];
                                    // Store the API in the jcrop_api variable
                                    jcrop_api = this;
                                    jcrop_api.setSelect(rect);
                                });
                            });

                            function updatePreview(c) {
                                jQuery('#X').val(c.x);
                                jQuery('#Y').val(c.y);
                                jQuery('#W').val(c.w);
                                jQuery('#H').val(c.h);

                                if (parseInt(c.w) > 0) {
                                    var rx = 100 / c.w;
                                    var ry = 100 / c.h;

                                    $('#preview').css({
                                        width: Math.round(rx * boundx) + 'px',
                                        height: Math.round(ry * boundy) + 'px',
                                        marginLeft: '-' + Math.round(rx * c.x) + 'px',
                                        marginTop: '-' + Math.round(ry * c.y) + 'px'
                                    });
                                }
                            };                          
                        </script>
                    </head>
                

3. In your body section add following form to your page

                   
  <div>
<asp:button id="Submit" runat="server" text="Crop Image" onclick="Submit_Click" />
 
<asp:image id="cropedImage" runat="server" visible="False" />
 
<table>
<tr>
    <td>
        <div>
            <img src="Sunset.jpg" id="cropbox" />
        </div>
    </td>
    <td valign="middle">
        <div>
            <table>
                <tr>
                    <td class="headInnerLarger">
                        Thumbnail Preview:
                    </td>
                </tr>
                <tr>
                    <td>
                        <div style="width: 100px; height: 100px; overflow: hidden;">
                            <img src="Sunset.jpg" id="preview" />
                        </div>
                    </td>
                </tr>
            </table>
        </div>
    </td>
</tr>
</table>
<asp:hiddenfield id="X" runat="server" />
<asp:hiddenfield id="Y" runat="server" />
<asp:hiddenfield id="W" runat="server" />
<asp:hiddenfield id="H" runat="server" />
</div>
                

4. We need to handle the click event of crop button in our code and crop the image there

                
protected void Submit_Click(object sender, EventArgs e)
{
  if (this.IsPostBack)
  {
   //Get the Cordinates                
   int x = Convert.ToInt32(X.Value);
   int y = Convert.ToInt32(Y.Value);
   int w = Convert.ToInt32(W.Value);
   int h = Convert.ToInt32(H.Value);

   //Load the Image from the location
   System.Drawing.Image image = Bitmap.FromFile(
         HttpContext.Current.Request.PhysicalApplicationPath + "Sunset.jpg");
  
  //Create a new image from the specified location to                
  //specified height and width                
  Bitmap bmp = new Bitmap(w, h, image.PixelFormat);
  Graphics g = Graphics.FromImage(bmp);
  g.DrawImage(image, new Rectangle(0, 0, w, h), new Rectangle(x, y, w, h), 
                     GraphicsUnit.Pixel);

  //Save the file and reload to the control
  bmp.Save(HttpContext.Current.Request.PhysicalApplicationPath + "Sunset2.jpg",          image.RawFormat);
  cropedImage.Visible = true;
  cropedImage.ImageUrl = ".\\Sunset2.jpg";
 }
}
             

Sunday, June 10, 2012

.Net Framework-Basics

Explain the .Net Framework.

The .Net framework allows infrastructural services to all the applications developed in .net compliant language. It is an engine that provides runtime services using its component like Common Runtime Language. It consists of two main components such as Common Language Runtime and Framework Class Library.

Difference between .Net 4.0 and .Net 3.5, 2.0

  • ControlRenderingCompatabilityVersion Setting in the Web.config File
  • ClientIDMode Changes
  • HtmlEncode and UrlEncode Now Encode Single Quotation Marks
  • ASP.NET Page (.aspx) Parser is Stricter
  • Browser Definition Files Updated
  • System.Web.Mobile.dll Removed from Root Web Configuration File
  • ASP.NET Request Validation
  • Default Hashing Algorithm Is Now HMACSHA256
  • Configuration Errors Related to New ASP.NET 4 Root Configuration
  • ASP.NET 4 Child Applications Fail to Start When Under ASP.NET 2.0 or ASP.NET 3.5 Applications
  • ASP.NET 4 Web Sites Fail to Start on Computers Where SharePoint Is Installed
  • The HttpRequest.FilePath Property No Longer Includes PathInfo Values
  • ASP.NET 2.0 Applications Might Generate HttpException Errors that Reference eurl.axd
  • Event Handlers Might Not Be Not Raised in a Default Document in IIS 7 or IIS 7.5 Integrated Mode Changes to the ASP.NET Code Access Security (CAS) Implementation
  • MembershipUser and Other Types in the System.Web.Security Namespace Have Been Moved
  • Output Caching Changes to Vary * HTTP Header
  • System.Web.Security Types for Passport are Obsolete
  • The MenuItem.PopOutImageUrl Property Fails to Render an Image in ASP.NET 4
  • Menu.StaticPopOutImageUrl and Menu.DynamicPopOutImageUrl Fail to Render Images When Paths Contain Backslashes
Link to find details of all the Major changes in .Net 4.0

Explain CLR (Common Language Runtime) and its functionalities?

Common Language Runtime (CLR) is the engine available in .Net Framework to compile and run the program. CLR engine does not compile the code in machine code but converts the code in a set of instructions called Microsoft Intermediate Language (MSIL). This MSIL is one of the section of Portable Executable (PE) file, the other being Metadata. PE file automatically get generated when you compile the program code.
The conversion of the program code to MSIL by CLR engine, makes .Net platform and language independent. Although at present, Microsoft does not have CLR engines for other platforms, in future you can find .Net application being compiled in UNIX or Linux operating system. After the conversion of the program code to MSIL, the code is then translated to native or machine code. Instead of compiling the program code at development time, the MSIL code gets translated 'just in time' (JIT) by JIT compilers.
CLR helps developers in managing both allocation and deallocation of memory. This removes two of the largest sources of programmer error: leaks and memory corruption.
CLR is also helpful for security purposes. CLR provide permissions to a component based on what process it runs in, validates the code based on evidence such as information about code at load time and the website from which component was obtained to assign permissions on a component-by-component basis. Moreover, CLR checks the code to see if it has been manipulated. The metadata in a CLR component can contain a digital signature that can be used to verify that the component was written by genuine person and that it has not been modified.

Explain the components of common language runtime.

  • Class Loader: is an abstract class. Its purpose is to tell JVM in what manner a class is to be loaded at runtime.
  • MSIL: Microsoft Intermediate Language is considered to be the lowest form of human readable language. It is CPU independent and includes instructions of how to load, store, initialize objects. JIT converts this MSIL into native code which is dependent on the CPU.
  • Code Manager: Is responsible for managing code at runtime.
  • Garbage Collector:The .NET garbage collector enables high-speed allocation and release of memory for the objects in managed code. Its main aim is proper memory management.
  • Security Engine:It ensures all the security restrictions.
  • Checker:Type It enforces the constraints of types. It enforces strictness in type checking.
  • Thread Support:It allows multithreading
  • Debug engine: It allows proper debugging of an application.
  • Base class library: It provides all the types that an application need at runtime.
  • Exception manager: Handles all the exception for an application during runtime.
  • COM Marshaller:It provides an option for interoperability for an application.

Monday, May 28, 2012

Operation is not valid due to the current state of the object. :ASP.Net Error

Issue:
System.InvalidOperationExceptionOperation is not valid due to the current state of the object.
    System.InvalidOperationException: Operation is not valid due to the current state of the object.
   at System.Web.HttpRequest.FillInFormCollection()
   at System.Web.HttpRequest.get_Form()
   at Rhino.Commons.LongConversationManager.LoadConversationFromRequest(Boolean& privateConversation)
   at Rhino.Commons.LongConversationManager.LoadConversation()
   at Rhino.Commons.HttpModules.UnitOfWorkApplication.UnitOfWorkApplication_BeginRequest(Object sender, EventArgs e)
   at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
 
Cause:

Microsoft recently (12-29-2011) released an update to address several serious security vulnerabilities in the .NET Framework. MS11-100 was introduced just recently that handles potential DoS attacks.

Unfortunately the fix has also broken page POSTs with very large amounts of posted data (form fields). MS11-100 places a limit of 500 on postback items. The new default max introduced by the recent security update is 1000.

Adding the setting key to the web-config file overcomes this limitation, as in this example increases it to 2000.

  <appSettings>
    <add key="aspnet:MaxHttpCollectionKeys" value="2000" />
</appSettings>

Saturday, May 26, 2012

ASP.Net Page Life Cycle

When a page request is sent to the Web server, the page is run through a series of events during its creation and disposal. In this article, I will discuss in detail the ASP.NET page life cycle Events
(1) PreInit The entry point of the page life cycle is the pre-initialization phase called “PreInit”. This is the only event where programmatic access to master pages and themes is allowed. You can dynamically set the values of master pages and themes in this event. You can also dynamically create controls in this event.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;using 
System.Web.UI;
using System.Web.UI.WebControls; 

public partial class _Default : System.Web.UI.Page
{    
    protected void Page_PreInit(object sender, EventArgs e)    
    {       
      //  Use this event for the following:         
      //  Check the IsPostBack property to determine whether this is the first time the page is being processed.       
      //  Create or re-create dynamic controls.        
      //  Set a master page dynamically.        
      //  Set the Theme property dynamically.           
    }  
  


(2)Init This event fires after each control has been initialized, each control's UniqueID is set and any skin settings have been applied. You can use this event to change initialization values for controls. The “Init” event is fired first for the most bottom control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_Init(object sender, EventArgs e)
{
   // Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.
}


(3)InitComplete Raised once all initializations of the page and its controls have been completed. Till now the viewstate values are not yet loaded, hence you can use this event to make changes to view state that you want to make sure are persisted after the next postback
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_InitComplete(object sender, EventArgs e)

{       
   // Raised by the  Page object. Use this event for processing tasks that require all initialization be complete.
 }



(4)PreLoad Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance
(1)Loads ViewState : ViewState data are loaded to controls Note : The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden <input> control that is passed from page request to page request.
(2)Loads Postback data : postback data are now handed to the page controls Note : During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. Hence, the page fires the LoadPostData event and parses through the page to find each control and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control's unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected override void OnPreLoad(EventArgs e)

{        
      // Use this event if you need to perform processing on your page or control before the  Load event.        
      // Before the Page instance raises this event, it loads view state for itself and all controls, 
      and then processes any postback data included with the Request instance.
 }



(5)Load The important thing to note about this event is the fact that by now, the page has been restored to its previous state in case of postbacks. Code inside the page load event typically checks for PostBack and then sets control properties appropriately. This method is typically used for most code, since this is the first place in the page lifecycle that all values are restored. Most code checks the value of IsPostBack to avoid unnecessarily resetting state. You may also wish to call Validate and check the value of IsValid in this method. You can also create dynamic controls in this method.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_Load(object sender, EventArgs e)

{        
         // The  Page calls the  OnLoad event method on the  Page, then recursively does the same for each child control, 
         which does the same for each of its child controls until the page and all controls are loaded.      
        // Use the OnLoad event method to set properties in controls and establish database connections.
 }


(6)Control (PostBack) event(s)ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button’s click event or a dropdown's selectedindexchange event, for example.These are the events, the code for which is written in your code-behind class(.cs file).
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Button1_Click(object sender, EventArgs e)

{        // This is just an example of control event.. Here it is button click event that caused the postback}



(7)LoadComplete This event signals the end of Load.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_LoadComplete(object sender, EventArgs e)

{        // Use this event for tasks that require that all other controls on the page be loaded.}



(8)PreRender Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved.
For example : After this event, you cannot change any property of a button or change any viewstate value. Because, after this event, SaveStateComplete and Render events are called.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected override void OnPreRender(EventArgs e)

{        
         // Each data bound control whose DataSourceID property is set calls its DataBind method.       
         // The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.
 }



(9)SaveStateComplete Prior to this event the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected override void OnSaveStateComplete(EventArgs e)
{       
     // Before this event occurs,  ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.        // Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.
}


(10)Render This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser. Note: Right click on the web page displayed at client's browser and view the Page's Source. You will not find any aspx server control in the code. Because all aspx controls are converted to their respective HTML representation. Browser is capable of displaying HTML and client side scripts.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page


(11) UnLoad This event is used for cleanup code. After the page's HTML is rendered, the objects are disposed of. During this event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. Cleanup can be performed on-
(a)Instances of classes i.e. objects
(b)Closing opened files
(c)Closing database connections.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
        protected void Page_UnLoad(object sender, EventArgs e)  
        {       
            // This event occurs for each control and then for the page. In controls, 
            use this event to do final cleanup for specific controls, such as closing control-specific database connections.       
            // During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream.          
            //If you attempt to call a method such as the Response.Write method, the page will throw an exception.   
       }



For More Reference : Follow the below links
(1)http://www.15seconds.com/issue/020102.htm
(2) http://msdn.microsoft.com/en-us/library/ms178472.aspx
(3) http://www.devlifestyle.net/blogs/articles/archive/2009/05/24/asp-net-internals-viewstate-and-page-life-cycle.aspx

Thank You...

Tuesday, May 15, 2012

ASP.Net Custom Pager

Create simple ASP.Net custom pager for List View, Grid View,etc. with SQL paging.




Create a user control for Paging and add to main page
<%@ Register Src="~/SysControls/SysAdminPager.ascx" TagName="DataPagerControl" TagPrefix="uc1" %>
.
.
.
 

Using a simple list view for binding data.
<uc1:DataPagerControl ID="sysPager" runat="server" />
        <asp:ListView ID="lstView" runat="server">
            <LayoutTemplate>
                <table class="normal fullwidth">
                    <thead>
                        <tr style="background-color: #EEE">
                            <th>
                                ID
                            </th>
                            <th>
                                Name
                            </th>
                            <th>
                                Address
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <asp:PlaceHolder ID="itemPlaceHolder" runat="server"></asp:PlaceHolder>
                    </tbody>
                </table>
            </LayoutTemplate>
            <ItemTemplate>
                <tr class='<%# (Container.DataItemIndex+1)%2==0?"":"odd" %>'>
                    <td>
                        <%#Eval("ID") %>
                    </td>
                    <td>
.
.
.


On Page Load Reginster Event handler for Pager Control. Use Sql Paging..pass your page number and page size SP and return data and totalrow count . Set page properties using pagenumber,pagesize and total rows
  
  protected void Page_Load(object sender, EventArgs e)
        {
            sysPager.PageChanged += new EventHandler<PageEventArgs>(sysPager_PageChanged);
            if (!IsPostBack)
            {
                BindData();
            }
        }
        void sysPager_PageChanged(object sender, PageEventArgs e)
        {
            BindData(e.StartRowIndex, e.MaximumRows);
        }
        void BindData(int pagenumber = 1, int pagesize = 20)
        {
            SampleCollectionML lstCollection = SampleBL.SelectAll(new SampleML { PageNumber = pagenumber, PageSize = pagesize });
            if (lstCollection.Count > 0)
            {
                lstView.DataSource = lstCollection;
                lstView.DataBind();
                sysPager.SetPageProperties(pagenumber, pagesize, lstCollection[0].TotalRows);
            }
        } 


Source code User Control For Pager
  <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SysAdminPager.ascx.cs"
    Inherits=" GradeBook.SysControls.SysAdminPager" %>
<div class="pager-container">
    <div style="float: left; margin-right: 15px; vertical-align: middle">
        Page size:
        <asp:DropDownList ID="ddlPageSize" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlPageSize_SelectedIndexChanged"
            Style="padding: 2px;">
            <asp:ListItem Value="10" Text="10"></asp:ListItem>
            <asp:ListItem Value="20" Text="20"></asp:ListItem>
            <asp:ListItem Value="50" Text="50"></asp:ListItem>
            <asp:ListItem Value="100" Text="100"></asp:ListItem>           
        </asp:DropDownList>
    </div>
    <asp:Repeater ID="rpt" runat="server">
        <HeaderTemplate>
            <div class='<%# PagerCss %>'>
                <div style="float: left; padding: 4px 0 2px;">
                    Page <b>
                        <%# Convert.ToInt32(TotalRowCount > 0 ? CurrentPage : 0)%>                       
                    </b>of <b>
                        <%# Convert.ToInt32(MaximumRows>0? Math.Ceiling((double)TotalRowCount / MaximumRows):0)%>
                    </b>(<%# TotalRowCount %>
                    item(s))
                </div>
                <div style="float: right; padding-top: 2px;">
                    <asp:LinkButton ID="lnkbFirst" CommandName="<%#PageChangedItemCommand %>" CommandArgument="1"
                        runat="server" ToolTip="First" CssClass="page-text">&laquo;First</asp:LinkButton>&nbsp;
                    <asp:LinkButton ID="lnkbPrevious" CommandName="<%#PageChangedItemCommand %>" CommandArgument="<%#PreviousPageIndex%>"
                        runat="server" ToolTip="Previous" CssClass="page-text">&laquo;Prev</asp:LinkButton>
            &nbsp;
        </HeaderTemplate>
        <ItemTemplate>
            <asp:LinkButton CommandName="<%#PageChangedItemCommand %>" CommandArgument='<%#DataBinder.Eval(Container.DataItem, "Page")%>'
                ID="p" runat="server"><%#DataBinder.Eval(Container.DataItem, "Text")%>&nbsp;</asp:LinkButton>
        </ItemTemplate>
        <FooterTemplate>
            <asp:LinkButton ID="lnkbNext" CommandName='<%#PageChangedItemCommand %>' CommandArgument="<%#NextPageIndex%>"
                runat="server" ToolTip="Next" CssClass="page-text">Next &raquo;</asp:LinkButton>&nbsp;
            <asp:LinkButton ID="lnkbLast" CommandName="<%#PageChangedItemCommand %>" CommandArgument="<%#PagesCount%>"
                runat="server" ToolTip="Last" CssClass="page-text">Last &raquo;</asp:LinkButton>
            </div> </div>
        </FooterTemplate>
    </asp:Repeater>
    <div style="float: right; margin-right: 6px">
        Go to:
        <asp:DropDownList ID="ddlPageNumber" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlPageNumber_SelectedIndexChanged"
            Style="padding: 2px;">
        </asp:DropDownList>
    </div>
    <div class="clear">
    </div>
</div>




A Class for holding Paging parameter
  public class SysPager
    {
        public int Page { get; set; }
        public string Text { get; set; }
        public SysPager(int _p, string _t)
        {
            Page = _p;
            Text = _t;
        }
    }


Page Propeties for holding paging information
        //public partial class SysAdminPager : System.Web.UI.UserControl
        // {
        // Summary:
        //     Gets the maximum number of records to display on each page.
        //
        // Returns:
        //     The maximum number of records to display on each page.
        public int MaximumRows
        {
            get
            {
                return (int)(ViewState["MaximumRows"] ?? 10);
            }
            set
            {
                ViewState["MaximumRows"] = value;
            }
        }
        //
        // Summary:
        //     Gets the index of the first record on a page.
        //
        // Returns:
        //     The index of the first record on a page.
        public int CurrentPage
        {
            get
            {
                return (int)(ViewState["CurrentPage"] ?? 1);
            }
            set
            {
                ViewState["CurrentPage"] = value;
            }
        }
        //
        // Summary:
        //     Gets the total number of records in the underlying data source.
        //
        // Returns:
        //     The total number of records of the underlying data source.
        public int TotalRowCount
        {
            get
            {
                return (int)(ViewState["TotalRowCount"] ?? 0);
            }
            set
            {
                ViewState["TotalRowCount"] = value;
            }
        }

        public int ButtonCount
        {
            get
            {
                return (int)(ViewState["ButtonCount"] ?? 10);
            }
            set
            {
                ViewState["ButtonCount"] = value;
            }
        }

        private int _pagesCount;

        public int PagesCount
        {
            get
            {
                if (TotalRowCount == 0)
                    return _pagesCount = 0;
                else if (TotalRowCount % MaximumRows == 0)
                    return _pagesCount = (TotalRowCount / MaximumRows);
                else
                    return _pagesCount = ((TotalRowCount / MaximumRows) + 1);
            }

            private set
            {
                _pagesCount = value;
            }
        }

        public string PagerCss
        {
            get
            {
                return (string)(ViewState["PagerCss"] ?? "pagination-default");
            }
            set
            {
                ViewState["PagerCss"] = value;
            }
        }
        protected int NextPageIndex { get { return CurrentPage + 1; } }
        protected int PreviousPageIndex { get { return CurrentPage - 1; } }


Page Changing Event Declaration and Invoking
        public event EventHandler<PageEventArgs> PageChanged;
        protected const string PageChangedItemCommand = "PageChanged";
        private const string CurrentPageCssStyle = "current";//"font-weight:bold; font-size:15px;";

        private void RaiseEvent(int currentPage)
        {
            if (PageChanged != null)
                PageChanged(this, new PageEventArgs(currentPage, MaximumRows, TotalRowCount));
        }


Create Paging data using Totalrows,Pagesize and button count
       
     protected List<SysPager> DataSource
        {
            get
            {
                List<SysPager> pages = new List<SysPager>();
                int _startpage = 1;
                int _endpage = PagesCount;
                bool showMore_first = false;
                bool showMore_last = false;
                if (PagesCount > ButtonCount)
                {
                    if (CurrentPage - (ButtonCount / 2) > 1)
                    {
                        _startpage = CurrentPage - (ButtonCount / 2);
                        showMore_first = true;
                    }
                    if (CurrentPage + (ButtonCount / 2) < PagesCount)
                    {
                        _endpage = CurrentPage + (ButtonCount / 2);
                        if (_endpage < ButtonCount)
                            _endpage = ButtonCount;

                        showMore_last = true;
                    }
                }
                if (showMore_first)
                {
                    pages.Add(new SysPager(_startpage - 1, "..."));
                }
                for (int i = _startpage; i <= _endpage; i++)
                {

                    pages.Add(new SysPager(i, i.ToString()));
                }
                if (showMore_last)
                {
                    pages.Add(new SysPager(_endpage + 1, "..."));

                }

                return pages;
            }
        }



        public SysAdminPager()
        {
            CurrentPage = 1;
            MaximumRows = 1;
            TotalRowCount = 1;
        }



Page Load And Other Events
        protected void Page_Load(object sender, EventArgs e)
        {
            rpt.ItemCommand += new RepeaterCommandEventHandler(rpt_ItemCommand);

            if (!Page.IsPostBack)
            {
                //CurrentPageSetCssStyle(CurrentPageCssStyle);
                // SetupCommandArguments();
            }
        }

        void rpt_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == PageChangedItemCommand)
            {
                CurrentPage = int.Parse(e.CommandArgument.ToString());
                CurrentPageSetCssStyle(CurrentPageCssStyle);
                // SetupCommandArguments();
                SetPageProperties();
                RaiseEvent(CurrentPage);

            }
        }



        private void CurrentPageSetCssStyle(string style)
        {
            ddlPageNumber.SetDropDownSelectedValue(CurrentPage);
            ddlPageSize.SetDropDownSelectedValue(MaximumRows);
            foreach (RepeaterItem item in rpt.Items)
            {
                LinkButton lnkButton = item.FindControl("p") as LinkButton;
                if (lnkButton != null)
                {
                    if (lnkButton.CommandArgument == CurrentPage.ToString())
                        lnkButton.Attributes.Add("class", style);
                }
            }
            //  SetupCommandArguments();
        }



        void SetupCommandArguments()
        {
            LinkButton lnkbPrevious = rpt.Controls[0].Controls[0].FindControl("lnkbPrevious") as LinkButton;
            LinkButton lnkbFirst = rpt.Controls[0].Controls[0].FindControl("lnkbFirst") as LinkButton;
            if (lnkbPrevious != null)
            {

                if (CurrentPage == 1 || PagesCount == 0)
                {
                    lnkbPrevious.Enabled = false;
                    lnkbFirst.Enabled = false;
                    lnkbPrevious.CommandArgument = (CurrentPage).ToString();
                }
                else
                {
                    lnkbPrevious.Enabled = true;
                    lnkbFirst.Enabled = true;
                    lnkbPrevious.CommandArgument = (CurrentPage - 1).ToString();
                }
            }

            LinkButton lnkbNext = rpt.Controls[rpt.Controls.Count - 1].Controls[0].FindControl("lnkbNext") as LinkButton;
            LinkButton lnkbLast = rpt.Controls[rpt.Controls.Count - 1].Controls[0].FindControl("lnkbLast") as LinkButton;
            if (lnkbNext != null)
            {
                if (CurrentPage == PagesCount || PagesCount == 0)
                {
                    lnkbNext.CommandArgument = (CurrentPage).ToString();
                    lnkbNext.Enabled = false;
                    lnkbLast.Enabled = false;
                }
                else
                {
                    lnkbNext.CommandArgument = (CurrentPage + 1).ToString();
                    lnkbNext.Enabled = true;
                    lnkbLast.Enabled = true;
                }
            }
        }

        internal void SetPageProperties(int _startpage, int _maxrows, int _totrows)
        {
            CurrentPage = _startpage;
            MaximumRows = _maxrows;
            TotalRowCount = _totrows;

            SetPageProperties();
        }
        internal void SetPageProperties()
        {

            rpt.DataSource = DataSource;
            rpt.DataBind();
            SetupCommandArguments();

            ddlPageNumber.Items.Clear();
            for (int i = 1; i <= PagesCount; i++)
            {
                ddlPageNumber.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
            CurrentPageSetCssStyle(CurrentPageCssStyle);



        }



Dropdown LIst Changing Events
       
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {

                MaximumRows = int.Parse(ddlPageSize.SelectedValue);
                if (PagesCount < CurrentPage)
                    CurrentPage = PagesCount;
                CurrentPageSetCssStyle(CurrentPageCssStyle);
                SetPageProperties();
                RaiseEvent(CurrentPage);
            }
            catch (Exception)
            {

            }

        }
        protected void ddlPageNumber_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                CurrentPage = int.Parse(ddlPageNumber.SelectedValue);
                CurrentPageSetCssStyle(CurrentPageCssStyle);
                SetPageProperties();
                RaiseEvent(CurrentPage);
            }
            catch (Exception)
            {

            }

        }
       
    }



You can change theme Gray,Blue,Red,Green.
 /*########################################################  Pagination  ########################################################*/
.pager-container {
    background: -moz-linear-gradient(center top , #FBFBFB, #F5F5F5) repeat scroll 0 0 transparent;
    border: 1px solid #CBC5C5;
    border-radius: 5px 5px 5px 5px;
    padding: 5px 8px;
}
.pagination a{font-size: 9px !important;text-transform: uppercase; /* background-color: #FFFFFF;*/border: 1px #5e90c3 solid;color: #5e90c3;padding: 1px 3px;
               text-decoration: none;outline: none;}
.pagination a:hover{    color: white;background-color: #5e90c3;border: 1px #5e90c3 solid;}
.pagination a.current,.pagination a:hover{font-size: 9px;text-transform: uppercase;background-color: #5e90c3;
                                          border: 1px solid #F2F2F2;color: white;padding: 1px 5px;text-decoration: none;outline: none;}
.pagination a[disabled=disabled]{    background-color: #CCCCCC;border: 1px solid #F2F2F2;color: #003366;}

/* $$$$$$$$$$$$$$  Default $$$$$$$$$$$$$$$$*/  
.pagination-default a{
   font-size: 10px !important;text-transform: uppercase;color: #606060;border: 1px solid #DDDDDD;border-radius: 4px;
   padding: 2px 3px; cursor: pointer;    outline: none !important;    text-align: center;    text-decoration: none;   
  
   /*border-color: #c0c0c0 #d4d4d4 #dbdbdb;text-shadow: 0px -1px 0px #fff;
   background: -moz-linear-gradient(top,#ebebeb,#f4f4f4 50%,#fff); background: -webkit-gradient(linear, left top, left bottom, from(#ebebeb), color-stop(0.5, #f4f4f4),to(#fff));
 filter: progid:DXImageTransform.Microsoft.Gradient(StartColorStr='#f4f4f4', EndColorStr='#ffffff');*/ } 
 
   .pagination-default a.current,.pagination-default a:hover {  color: #606060; text-shadow: 0px 1px 0px #fff;                                                         
                                                           border-color: #D0D0D0; box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);}
  
  .pagination-default a:hover{  background: #f1f1f1;}                                                         
   .pagination-default a.current{ box-shadow:none; background-color: #e0e0e0; background: -moz-linear-gradient(top,#e0e0e0,#f4f4f4 50%,#e0e0e0)); 
                                                          background: -webkit-gradient(linear, left top, left bottom,from(#fff),color-stop(0.5, #f4f4f4),to(#e0e0e0));
                                                          filter: progid:DXImageTransform.Microsoft.Gradient(StartColorStr='#f4f4f4', EndColorStr='#e0e0e0');}                                                                                                                    
  .pagination-default a[disabled=disabled]{  color: #aaa;}
  .pagination-default a.page-text{border:none;text-decoration:underline;}
 
/* $$$$$$$$$$$$$$  ORANGE $$$$$$$$$$$$$$$$*/  
 /* $$$$$$$$$$$$$$  GRAY $$$$$$$$$$$$$$$$*/
.pagination-gray a{ font-size: 9px !important;text-transform: uppercase; border: 1px #5e90c3 solid;color: #5e90c3;padding: 1px 3px;
   cursor: pointer;    outline: none !important;    text-align: center;    text-decoration: none;  -moz-border-radius: 3px;   
    -webkit-border-radius: 3px;    -khtml-border-radius: 3px;    border-radius: 3px;    
    -moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);    -webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);   
     -khtml-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);    box-shadow:inset 0 1px 0 rgba(255,255,255,0.5); 
    background: #f1f1f1;    background: -webkit-gradient(linear, left top, left bottom, from(#e9e9e9), to(#d1d1d1));
    background: -moz-linear-gradient(top,  #e9e9e9,  #d1d1d1);    -pie-background: linear-gradient(top,  #e9e9e9,  #d1d1d1);    
    border: 1px solid #bbb;    color: #555;    text-shadow: 0 1px 0 #fff;
 } 
 .pagination-gray a.current ,.pagination-gray a:hover {       background: #fff;    -pie-background: #fff;    color: #666;}
.pagination-gray a[disabled=disabled]{   color: #aaa;}

 /* $$$$$$$$$$$$$$  WHITE $$$$$$$$$$$$$$$$*/  
.pagination-white a{
   font-size: 9px !important;text-transform: uppercase; /* background-color: #FFFFFF;*/border: 1px #D8D8D8 solid;color: #606060;padding: 1px 3px;
   cursor: pointer;    outline: none !important;    text-align: center;    text-decoration: none;   
    -moz-border-radius: 3px;    -webkit-border-radius: 3px;    -khtml-border-radius: 3px;    border-radius: 3px;    
    -moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);  -webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);  -khtml-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);       box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);     
     background: #fff;    -pie-background: #fff;        border: 1px solid #bbb;    color: #555;
    text-shadow: 0 1px 0 #fff; } 
 .pagination-white a.current,.pagination-white a:hover { background: #f1f1f1;background: -webkit-gradient(linear, left top, left bottom, from(#e9e9e9), to(#d1d1d1));
                                                            background: -moz-linear-gradient(top,  #e9e9e9,  #d1d1d1);  -pie-background: linear-gradient(top,  #e9e9e9,  #d1d1d1);  
                                                             color: #666;}
.pagination-white a[disabled=disabled]{   color: #aaa;}
 
/* $$$$$$$$$$$$$$  ORANGE $$$$$$$$$$$$$$$$*/  
.pagination-orange a
{
   font-size: 9px !important;text-transform: uppercase; /* background-color: #FFFFFF;*/border: 1px #D8D8D8 solid;color: #606060;padding: 1px 3px;
   cursor: pointer;    outline: none !important;    text-align: center;    text-decoration: none;   
    -moz-border-radius: 3px;    -webkit-border-radius: 3px;    -khtml-border-radius: 3px;    border-radius: 3px;
    
     background: #f78d1d;
    background: -webkit-gradient(linear, left top, left bottom, from(#faa51a), to(#f47a20));
    background: -moz-linear-gradient(top, #faa51a, #f47a20);
    -pie-background: linear-gradient(top, #faa51a, #f47a20);
    border: solid 1px #dd6611;
    color: #fef4e9;
    text-shadow: 0 1px 1px rgba(0,0,0,0.25);     
 } 
 .pagination-orange a.current,.pagination-orange a:hover { 
     background: #EEEEEE;
    background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#EEEEEE));
    background: -moz-linear-gradient(top,  #FFFFFF,  #EEEEEE);
    -pie-background: linear-gradient(top,  #FFFFFF,  #EEEEEE);
    border: solid 1px #F88E11;
    color: #F88E11;
}
.pagination-orange a[disabled=disabled]
{
   color: #d1d1d1;
}
 
/* $$$$$$$$$$$$$$  RED $$$$$$$$$$$$$$$$*/  
.pagination-red a
{
   font-size: 9px !important;text-transform: uppercase; /* background-color: #FFFFFF;*/border: 1px #D8D8D8 solid;color: #606060;padding: 1px 3px;
   cursor: pointer;    outline: none !important;    text-align: center;    text-decoration: none;   
    -moz-border-radius: 3px;    -webkit-border-radius: 3px;    -khtml-border-radius: 3px;    border-radius: 3px;
    
   background-color: #C44747;
    background: -moz-linear-gradient(top, #DD5F5F 10%, #A92C2C 90%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0.1, #DD5F5F), color-stop(0.9, #A92C2C));
    -pie-background: linear-gradient(top, #DD5F5F 10%, #A92C2C 90%);
    border: 1px solid #A92C2C; 
    color: #fef4e9;
    text-shadow: 0 1px 1px rgba(0,0,0,0.25);
 } 
 .pagination-red a.current,.pagination-red a:hover { 
     background-color: #FFFFFF;
    background: -moz-linear-gradient(top, #FFFFFF  10%, #EEEEEE 90%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0.1, #FFFFFF ), color-stop(0.9, #EEEEEE));
    -pie-background: linear-gradient(top, #FFFFFF  10%, #EEEEEE 90%);
    border: 1px solid #ccc; 
    color: #000;
}
.pagination-red a[disabled=disabled]
{
   color: #CCCCCC;
}
 
/* $$$$$$$$$$$$$$  BLUE $$$$$$$$$$$$$$$$*/  
.pagination-blue a
{
   font-size: 9px !important;text-transform: uppercase; /* background-color: #FFFFFF;*/border: 1px #D8D8D8 solid;color: #606060;padding: 3px 3px;
   cursor: pointer;    outline: none !important;    text-align: center;    text-decoration: none;   
    -moz-border-radius: 3px;    -webkit-border-radius: 3px;    -khtml-border-radius: 3px;    border-radius: 3px;
    
   background: #0095cd;
    background: -webkit-gradient(linear, left top, left bottom, from(#00adee), to(#0078a5));
    background: -moz-linear-gradient(top,  #00adee,  #0078a5);
    -pie-background: linear-gradient(top,  #00adee,  #0078a5);
    border: 1px solid #034462;
    color: #fff;
    text-shadow: 0 1px 1px rgba(0,0,0,0.25);
 } 
 .pagination-blue a.current,.pagination-blue a:hover { 
     background: #EEE;
    background: -webkit-gradient(linear, left top, left bottom, from(#EEE), to(#FFF));
    background: -moz-linear-gradient(top,  #EEE,  #FFF);
    -pie-background: linear-gradient(top,  #EEE,  #FFF);
    border: 1px solid #234;
    color: #000;
}
.pagination-blue a[disabled=disabled]{   color: #ccc;}
 
/* $$$$$$$$$$$$$$  GREEN $$$$$$$$$$$$$$$$*/  
.pagination-green a
{
   font-size: 9px !important;text-transform: uppercase; /* background-color: #FFFFFF;*/border: 1px #D8D8D8 solid;color: #606060;padding: 1px 3px;
   cursor: pointer;    outline: none !important;    text-align: center;    text-decoration: none;   
    -moz-border-radius: 3px;    -webkit-border-radius: 3px;    -khtml-border-radius: 3px;    border-radius: 3px;
    
    color: #fff;
    background: #8fc857;
    background: -webkit-gradient(linear, left top, left bottom, from(#8fc857), to(#5c9425));
    background: -moz-linear-gradient(top,  #8fc857,  #5c9425);
    -pie-background: linear-gradient(top,  #8fc857,  #5c9425);
    text-shadow: 0 1px 1px rgba(0,0,0,0.25);
    border:1px solid #561;
 } 
 .pagination-green a.current,.pagination-green a:hover { 
     background: #E9E9E9;
    background: -webkit-gradient(linear, left top, left bottom, from(#E9E9E9), to(#D1D1D1));
    background: -moz-linear-gradient(top,  #E9E9E9,  #D1D1D1);
    -pie-background: linear-gradient(top,  #E9E9E9,  #D1D1D1);
    border:1px solid #342;     
}
.pagination-green a[disabled=disabled]
{
   color: #ccc;
}
 
/* $$$$$$$$$$$$$$  PAGINATIOn END $$$$$$$$$$$$$$$$*/  

DateTime.ToString() Patterns


DateTime.ToString() Patterns


All the patterns:

0 MM/dd/yyyy 08/22/2006
1 dddd, dd MMMM yyyy Tuesday, 22 August 2006
2 dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
3 dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
4 dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
5 dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM
6 dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
7 MM/dd/yyyy HH:mm 08/22/2006 06:30
8 MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
9 MM/dd/yyyy H:mm 08/22/2006 6:30
10 MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
10 MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
10 MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
11 MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07
12 MMMM dd August 22
13 MMMM dd August 22
14 yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK 2006-08-22T06:30:07.7199222-04:00
15 yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK 2006-08-22T06:30:07.7199222-04:00
16 ddd, dd MMM yyyy HH':'mm':'ss 'GMT' Tue, 22 Aug 2006 06:30:07 GMT
17 ddd, dd MMM yyyy HH':'mm':'ss 'GMT' Tue, 22 Aug 2006 06:30:07 GMT
18 yyyy'-'MM'-'dd'T'HH':'mm':'ss 2006-08-22T06:30:07
19 HH:mm 06:30
20 hh:mm tt 06:30 AM
21 H:mm 6:30
22 h:mm tt 6:30 AM
23 HH:mm:ss 06:30:07
24 yyyy'-'MM'-'dd HH':'mm':'ss'Z' 2006-08-22 06:30:07Z
25 dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
26 yyyy MMMM 2006 August
27 yyyy MMMM 2006 August

The patterns for DateTime.ToString ( 'd' ) :

0 MM/dd/yyyy 08/22/2006

The patterns for DateTime.ToString ( 'D' ) :

0 dddd, dd MMMM yyyy Tuesday, 22 August 2006

The patterns for DateTime.ToString ( 'f' ) :

0 dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
1 dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
2 dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
3 dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM

The patterns for DateTime.ToString ( 'F' ) :

0 dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07

The patterns for DateTime.ToString ( 'g' ) :

0 MM/dd/yyyy HH:mm 08/22/2006 06:30
1 MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
2 MM/dd/yyyy H:mm 08/22/2006 6:30
3 MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM

The patterns for DateTime.ToString ( 'G' ) :

0 MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07

The patterns for DateTime.ToString ( 'm' ) :

0 MMMM dd August 22

The patterns for DateTime.ToString ( 'r' ) :

0 ddd, dd MMM yyyy HH':'mm':'ss 'GMT' Tue, 22 Aug 2006 06:30:07 GMT

The patterns for DateTime.ToString ( 's' ) :

0 yyyy'-'MM'-'dd'T'HH':'mm':'ss 2006-08-22T06:30:07

The patterns for DateTime.ToString ( 'u' ) :

0 yyyy'-'MM'-'dd HH':'mm':'ss'Z' 2006-08-22 06:30:07Z

The patterns for DateTime.ToString ( 'U' ) :

0 dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07

The patterns for DateTime.ToString ( 'y' ) :

0 yyyy MMMM 2006 August

Building a custom DateTime.ToString Patterns

The following details the meaning of each pattern character. Note the K and z character.
d Represents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero
dd Represents the day of the month as a number from 01 through 31. A single-digit day is formatted with a leading zero
ddd Represents the abbreviated name of the day of the week (Mon, Tues, Wed etc)
dddd Represents the full name of the day of the week (Monday, Tuesday etc)
h 12-hour clock hour (e.g. 7)
hh 12-hour clock, with a leading 0 (e.g. 07)
H 24-hour clock hour (e.g. 19)
HH 24-hour clock hour, with a leading 0 (e.g. 19)
m Minutes
mm Minutes with a leading zero
M Month number
MM Month number with leading zero
MMM Abbreviated Month Name (e.g. Dec)
MMMM Full month name (e.g. December)
s Seconds
ss Seconds with leading zero
t Abbreviated AM / PM (e.g. A or P)
tt AM / PM (e.g. AM or PM
y Year, no leading zero (e.g. 2001 would be 1)
yy Year, leadin zero (e.g. 2001 would be 01)
yyy Year, (e.g. 2001 would be 2001)
yyyy Year, (e.g. 2001 would be 2001)
K Represents the time zone information of a date and time value (e.g. +05:00)
z With DateTime values, represents the signed offset of the local operating system's time zone from Coordinated Universal Time (UTC), measured in hours. (e.g. +6)
zz As z but with leadin zero (e.g. +06)
zzz With DateTime values, represents the signed offset of the local operating system's time zone from UTC, measured in hours and minutes. (e.g. +06:00)
f Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value.
ff Represents the two most significant digits of the seconds fraction; that is, it represents the hundredths of a second in a date and time value.
fff Represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value.
ffff Represents the four most significant digits of the seconds fraction; that is, it represents the ten thousandths of a second in a date and time value. While it is possible to display the ten thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
fffff Represents the five most significant digits of the seconds fraction; that is, it represents the hundred thousandths of a second in a date and time value. While it is possible to display the hundred thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
ffffff Represents the six most significant digits of the seconds fraction; that is, it represents the millionths of a second in a date and time value. While it is possible to display the millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
fffffff Represents the seven most significant digits of the seconds fraction; that is, it represents the ten millionths of a second in a date and time value. While it is possible to display the ten millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
F Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value. Nothing is displayed if the digit is zero.
: Represents the time separator defined in the current DateTimeFormatInfo..::.TimeSeparator property. This separator is used to differentiate hours, minutes, and seconds.
/ Represents the date separator defined in the current DateTimeFormatInfo..::.DateSeparator property. This separator is used to differentiate years, months, and days.
" Represents a quoted string (quotation mark). Displays the literal value of any string between two quotation marks ("). Your application should precede each quotation mark with an escape character (\).
' Represents a quoted string (apostrophe). Displays the literal value of any string between two apostrophe (') characters.
%c Represents the result associated with a c custom format specifier, when the custom date and time format string consists solely of that custom format specifier. That is, to use the d, f, F, h, m, s, t, y, z, H, or M custom format specifier by itself, the application should specify %d, %f, %F, %h, %m, %s, %t, %y, %z, %H, or %M. For more information about using a single format specifier, see Using Single Custom Format Specifiers.
||\c || Represents the escape character, and displays the character "c" as a literal when that character is preceded by the escape character (\). To insert the backslash character itself in the result string, the application should use two escape characters ("\\").
Any other character copies any other character to the result string, without affecting formatting. ||