Best Industrial Training in C,C++,PHP,Dot Net,Java in Jalandhar

Wednesday 26 December 2012

Convert & Parse methods

Convert & Parse methods

There are two groups of methods, which aid us at converting values.
using System;

class CSharpApp
{
    static void Main()
    {
        Console.WriteLine(Convert.ToBoolean(0.3));
        Console.WriteLine(Convert.ToBoolean(3));
        Console.WriteLine(Convert.ToBoolean(0));
        Console.WriteLine(Convert.ToBoolean(-1));

        Console.WriteLine(Convert.ToInt32("452"));
        Console.WriteLine(Convert.ToInt32(34.5));
    }
}
The Convert class has many methods for converting values. We use two of them.
Console.WriteLine(Convert.ToBoolean(0.3));
We convert a double value to a bool value.
Console.WriteLine(Convert.ToInt32("452"));
And here we convert a string to int.

using System;

class CSharpApp
{
    static void Main()
    {
        Console.WriteLine(Int32.Parse("34"));
        Console.WriteLine(Int32.Parse("-34"));
        Console.WriteLine(Int32.Parse("+34"));
    }
}
Converting strings to integers is a very common task. Often when we bring values from databases or GUI widgets.
Console.WriteLine(Int32.Parse("34"));
We use the Parse() method of the Int32 class to convert a string to int value.

Nullable types

Nullable types

Value types cannot be assigned a null literal. Reference types can. Applications that work with databases deal with the null value. Because of this, special nullable types were introduced into the C# language. Nullable types are instances of the System.Nullable<T> struct.
using System;

class CSharpApp
{
    static void Main()
    {
        Nullable<bool> male = null;
        int? age = null;

        Console.WriteLine(male.HasValue);
        Console.WriteLine(age.HasValue);
    }
}
A simple example demonstrating nullable types.
Nullable<bool> male = null;
int? age = null;
There are two ways how to declare a nullable type. Either with the Nullable<T> generic structure, in which the type is specified between the angle brackets. Or we can use a question mark after the type. The latter is in fact a shorthand for the first notation.
$ ./nullabletypes.exe 
False
False
Output.

DateTime(Value Type)

DateTime

The DateTime is value type. It represents an instant in time, typically expressed as a date and time of day.
using System;

class CSharpApp
{
    static void Main()
    {
        DateTime today;

        today = DateTime.Now;

        System.Console.WriteLine(today);
        System.Console.WriteLine(today.ToShortDateString());
        System.Console.WriteLine(today.ToShortTimeString());               

    }
}
We show today's date in three different formats. Date & time, date and time.
DateTime today;
We declare a variable of DateTime data type.
today = DateTime.Now;
Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time.
System.Console.WriteLine(today);
This line prints the date in full format.
System.Console.WriteLine(today.ToShortDateString());
System.Console.WriteLine(today.ToShortTimeString());
The ToShortDateString() returns a short date string format, the ToShortTimeString() returns a short time string format.
$ ./date.exe 
10/15/2010 10:56:37 AM
10/15/2010
10:56 AM

Enumerations

Enumerations

Enumerated type (also called enumeration or enum) is a data type consisting of a set of named values. A variable that has been declared as having an enumerated type can be assigned any of the enumerators as a value. Enumerations make the code more readable.
using System;

class CSharpApp
{
    enum Days 
    {
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday,
        Sunday
    }

    static void Main()
    {

        Days day = Days.Monday;
        
        if (day == Days.Monday)
        {
            Console.WriteLine("It is Monday");
        }

        Console.WriteLine(day);

        foreach(int i in Enum.GetValues(typeof(Days)))
            Console.WriteLine(i);
    }
}
In our code example, we create an enumeration for week days.
enum Days 
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}
The enumeration is created with a enum keyword. The Monday, Tuesday ... barewords store in fact numbers 0..6.
Days day = Days.Monday;
We have a variable called day, which is of enumerated type Days. It is initialized to Monday.
if (day == Days.Monday)
{
    Console.WriteLine("It is Monday");
}
This code is more readable than if comparing a day variable to some number.
Console.WriteLine(day);
This line prints Monday to the console.
foreach(int i in Enum.GetValues(typeof(Days)))
    Console.WriteLine(i);
This loop prints 0..6 to the console. We get underlying types of the enum values. For a computer, an enum is just a number. The typeof is an operator used to obtain the System.Type object for a type. It is needed by the GetValues() method. This method returns an array of the values of in a specified enumeration. And the foreach keyword goes through the array, element by element and prints them to the terminal.

We further work with enumerations.
using System;

class CSharpApp
{
    public enum Seasons : byte
    {
        Spring = 1,
        Summer = 2,
        Autumn = 3,
        Winter = 4
    }

    static void Main()
    {
        Seasons s1 = Seasons.Spring;
        Seasons s2 = Seasons.Autumn;
        
        Console.WriteLine(s1);
        Console.WriteLine(s2);
    }
}
Seasons can be easily used as enums. We can specify the underlying type for the enum plus we can give exact values for them.
public enum Seasons : byte
{
    Spring = 1,
    Summer = 2,
    Autumn = 3,
    Winter = 4
}
With a colon and a data type we specify the underlying type for the enum. We also give each member a specific number.
Console.WriteLine(s1);
Console.WriteLine(s2);
These two lines print the enum values to the console.
$ ./seasons.exe 
Spring
Autumn
Output.

Friday 21 December 2012

ASP.NET Life Cycle


The requesting of an ASP.NET page triggers a sequence of events that encompass the page life cycle. The Web browser sends a post request to the Web server. The Web server recognizes the ASP.NET file extension for the requested page and sends the request to the HTTP Page Handler class. The following list is a sampling of these events, numbered in the order in which they are triggered.
  1. PreInt: This is the entry point of the ASP.NET page life cycle - it is the pre-initialization, so you have access to the page before it is initialized. Controls can be created within this event. Also, master pages and themes can be accessed. You can check the IsPostBack property here to determine if it is the first time a page has been loaded.
  2. Init: This event fires when all controls on the page have been initialized and skin settings have been applied. You can use this event to work with control properties. The Init event of the page is not fired until all control Init events have triggered - this occurs from the bottom up.
  3. InitComplete: This event fires once all page and control initializations complete. This is the last event fired where ViewState is not set, so ViewState can be manipulated in this event.
  4. PreLoad: This event is triggered when all ViewState and Postback data have been loaded for the page and all of its controls - ViewState loads first, followed by Postback data.
  5. Load: This is the first event in the page life cycle where everything is loaded and has been set to its previous state (in the case of a postback). The page Load event occurs first followed by the Load event for all controls (recursively). This is where most coding is done, so you want to check the IsPostBack property to avoid unnecessary work.
  6. LoadComplete: This event is fired when the page is completely loaded. Place code here that requires everything on the page to be loaded.
  7. PreRender: This is the final stop in the page load cycle where you can make changes to page contents or controls. It is fired after all PostBack events and before ViewState has been saved. Also, this is where control databinding occurs.
  8. PreRenderComplete: This event is fired when PreRender is complete. Each control raises this event after databinding (when a control has its DataSourceID set).
  9. SaveStateComplete: This is triggered when view and control state have been saved for the page and all controls within it. At this point, you can make changes in the rendering of the page, but those changes will not be reflected on the next page postback since view state is already saved.
  10. Unload: This event fires for each control and then the page itself. It is fired when the HTML for the page is fully rendered. This is where you can take care of cleanup tasks, such as properly closing and disposing database connections.
An interesting caveat of the events fired with the loading of a page is the controls within the page and their events; that is, each control has its own event life cycle. The following code provides an example of the ordering of page and a couple control events. The ASP.NET source is listed first and followed by the codebehind source. It is a basic ASP.NET 4.0 Web Form with TextBox and Literal controls. The code does not include all events, but it does provide a subset to give you a feel for how they appear. You should notice the events specified in the individual controls that ties them to code blocks.
<%@ Page Title="Home Page" Language="C#"
MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebPageLifeCycle._Default"
OnPreInit="PreInitEvent" ViewStateMode="Enabled" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent" />
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent" OnPreInit="Content_Render">
<h2>
<asp:Literal runat="server" ID="litExample" OnInit="Literal_Init"></asp:Literal>
<asp:TextBox runat="server" ID="txtExample" OnInit="Textbox_Init"></asp:TextBox>
Working with the ASP.NET Page life cycle.
</h2>
</asp:Content>
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebPageLifeCycle {
public partial class _Default : System.Web.UI.Page    {
protected void Page_Load(object sender, EventArgs e)     {
Response.Write("Page_Load<br>");
}
protected void Page_LoadComplete(object sender, EventArgs e)  {
Response.Write("Page_LoadComplete<br>");
}
protected void Page_PreRender(object sender, EventArgs e)     {
Response.Write("Page_PreRender<br>");
}
protected void Page_Render(object sender, EventArgs e)     {
Response.Write("Page_Render<br>");
}
protected void PreInitEvent(object sender, EventArgs e)    {
Response.Write("OnPreInit<br>");
}
protected void Page_Init(object sender, EventArgs e)    {
Response.Write("Page_Init<br>");
}
protected void Literal_Init(object sender, EventArgs e)   {
Response.Write("Literal_Init<br>");
}
protected void Textbox_Init(object sender, EventArgs e)  {
Response.Write("Textbox_Init<br>");
}
protected void Page_InitComplete(object sender, EventArgs e)    {
Response.Write("Page_InitComplete<br>");
}
protected void Page_PreLoad(object sender, EventArgs e)    {
Response.Write("Page_PreLoad<br>");
}
protected void TextBox_Unload(object sender, EventArgs e)    {
// Cleanup
}  }  }
Notice the Unload event does not display anything since the Response object is not available in it, since the page and controls have been fully loaded when this event is triggered. The following lines are displayed on the page when it is loaded:
OnPreInit
Literal_Init
Textbox_Init
Page_Init
Page_InitComplete
Page_PreLoad
Page_Load
Page_LoadComplete
Page_PreRender