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

Friday, 4 January 2013

Arrays

An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Arrays in C#

Declaring Arrays

To declare an array in C#, you can use the following syntax:
datatype[] arrayName;
where,
  • datatype is used to specify the type of elements to be stored in the array.
  • [ ] specifies the rank of the array. The rank specifies the size of the array.
  • arrayName specifies the name of the array.
For example,
double[] balance;

Initializing an Array

Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array.
Array is a reference type, so you need to use the new keyword to create an instance of the array.
For example,
double[] balance = new double[10];

Assigning Values to an Array

You can assign values to individual array elements, by using the index number, like:
double[] balance = new double[10];
balance[0] = 4500.0;
You can assign values to the array at the time of declaration, like:
double[] balance = { 2340.0, 4523.69, 3421.0};
You can also create and initialize an array, like:
int [] marks = new int[5]  { 99,  98, 92, 97, 95};
In the preceding case, you may also omit the size of the array, like:
int [] marks = new int[]  { 99,  98, 92, 97, 95};
You can also copy an array variable into another target array variable. In that case, both the target and source would point to the same memory location:
int [] marks = new int[]  { 99,  98, 92, 97, 95};
int[] score = marks;
When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. For example for an int array all elements would be initialized to 0.

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example:
double salary = balance[9];
Following is an example which will use all the above mentioned three concepts viz. declaration, assignment and accessing arrays:
using System;
namespace ArrayApplication
{
   class MyArray
   {
      static void Main(string[] args)
      {
         int []  n = new int[10]; /* n is an array of 10 integers */
         int i,j;


         /* initialize elements of array n */         
         for ( i = 0; i < 10; i++ )
         {
            n[ i ] = i + 100;
         }

         /* output each array element's value */
         for (j = 0; j < 10; j++ )
         {
            Console.WriteLine("Element[{0}] = {1}", j, n[j]);
         }
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

Using the foreach Loop

In the previous example, we have used a for loop for accessing each array element. You can also use a foreach statement to iterate through an array.
using System;
namespace ArrayApplication
{
   class MyArray
   {
      static void Main(string[] args)
      {
         int []  n = new int[10]; /* n is an array of 10 integers */


         /* initialize elements of array n */         
         for ( int i = 0; i < 10; i++ )
         {
            n[i] = i + 100;
         }

         /* output each array element's value */
         foreach (int j in n )
         {
            int i = 0;
            Console.WriteLine("Element[{0}] = {1}", i, j);
            i++;
         }
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

C# Arrays in Detail

Arrays are important to C# and should need lots of more detail. There are following few important concepts related to array which should be clear to a C# programmer:
ConceptDescription
Multi-dimensional arraysC# supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.
Jagged arraysC# supports multidimensional arrays, which are arrays of arrays.
Passing arrays to functionsYou can pass to the function a pointer to an array by specifying the array's name without an index.
Param arraysThis is used for passing unknown number of parameters to a function.
The Array ClassDefined in System namespace, it is the base class to all arrays, and provides various properties and methods for working with arrays.

Encapsulation

Encapsulation is defined 'as the process of enclosing one or more items within a physical or logical package'. Encapsulation, in object oriented programming methodology, prevents access to implementation details.
Abstraction and encapsulation are related features in object oriented programming. Abstraction allows making relevant information visible and encapsulation enables a programmer to implement the desired level of abstraction.

What is Encapsulation?
What is Abstraction?
What is the functionality of Encapsulation and Abstraction in C#?

Encapsulation and abstraction is essential part of C sharp programming that is mostly used for hide complex code from unauthorized user and shows only relevant information.

What is encapsulation?

Encapsulation is the process of hiding irrelevant data from the user. To understand encapsulation, consider an example of mobile phone. Whenever youbuy a mobile, you don’t see how circuit board works. You are also not interested to know how digital signal converts into analog signal and vice versa. These are the irrelevant information for the mobile user, that’s why it is encapsulated inside a cabinet.
In C# programming, we will do same thing. We will create a cabinet and keep all the irrelevant information in it that will be unavailable for the user.

What is abstraction?

Abstraction is just opposite of Encapsulation. Abstraction is mechanism to show only relevant data to the user. Consider the same mobile example again. Whenever you buy a mobile phone, you see their different types of functionalities as camera, mp3 player, calling function, recording function, multimedia etc. It is abstraction, because you are seeing only relevant information instead of their internal engineering.
Understanding-concepts

Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member. C# supports the following access specifiers:
  • Public
  • Private
  • Protected
  • Internal
  • Protected internal

Public Access Specifier

Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class.The type or member can be accessed by any other code in the same assembly or another assembly that references it.
The following example illustrates this:
using System;
namespace RectangleApplication
{
    class Rectangle
    {
        //member variables
        public double length;
        public double width;

        public double GetArea()
        {
            return length * width;
        }
        public void Display()
        {
            Console.WriteLine("Length: {0}", length);
            Console.WriteLine("Width: {0}", width);
            Console.WriteLine("Area: {0}", GetArea());
        }
    }//end class Rectangle    
    class ExecuteRectangle
    {
        static void Main(string[] args)
        {
            Rectangle r = new Rectangle();
            r.length = 4.5;
   r.width = 3.5;
            r.Display();
            Console.ReadLine();
        }
    }
}
When the above code is compiled and executed, it produces following result:
Length: 4.5
Width: 3.5
Area: 15.75
In the preceding example, the member variables length and width are declared public, so they can be accessed from the function Main() using an instance of the Rectangle class, named r.
The member function Display() and GetArea() can also access these variables directly without using any instance of the class.
The member functions Display() is also declared public, so it can also be accessed from Main() using an instance of the Rectangle class, named r.

Private Access Specifier

Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.
The following example illustrates this:
using System;
namespace RectangleApplication
{
    class Rectangle
    {
        //member variables
        private double length;
        private double width;

        public void Acceptdetails()
        {
            Console.WriteLine("Enter Length: ");
            length = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine("Enter Width: ");
            width = Convert.ToDouble(Console.ReadLine());
        }
        public double GetArea()
        {
            return length * width;
        }
        public void Display()
        {
            Console.WriteLine("Length: {0}", length);
            Console.WriteLine("Width: {0}", width);
            Console.WriteLine("Area: {0}", GetArea());
        }
    }//end class Rectangle    
    class ExecuteRectangle
    {
        static void Main(string[] args)
        {
            Rectangle r = new Rectangle();
            r.Acceptdetails();
            r.Display();
            Console.ReadLine();
        }
    }
}
When the above code is compiled and executed, it produces following result:
Enter Length:
4.4
Enter Width:
3.3
Length: 4.4
Width: 3.3
Area: 14.52
In the preceding example, the member variables length and width are declared private, so they cannot be accessed from the function Main(). The member functions AcceptDetails() and Display() can access these variables. Since the member functions AcceptDetails() and Display() are declared public, they can be accessed from Main() using an instance of the Rectangle class, named r.

Protected Access Specifier

Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing inheritance. We will discuss this in more details in the inheritance chapter.

Example:


using System;

namespace Protected_Specifier
{
  class access
   {
     // String Variable declared as protected
     protected string name;
     public void print()
      {
        Console.WriteLine("\nMy name is " + name);
      }
   }

  class Program
   {
     static void Main(string[] args)
      {
        access ac = new access();
        Console.Write("Enter your name:\t");
        // raise error because of its protection level
        ac.name = Console.ReadLine();
        ac.print();
        Console.ReadLine();
      }
   }
}



Output:
'Protected_Specifier.access.name' is inaccessible due to its protection level.

This is because; the protected member can only be accessed within its child class. You can use protected access specifiers as follow:

Example:


using System;

namespace Protected_Specifier
{
  class access
   {
     // String Variable declared as protected
     protected string name;
     public void print()
      {
        Console.WriteLine("\nMy name is " + name);
      }
   }

  class Program : access // Inherit access class
   {
     static void Main(string[] args)
      {
        Program p=new Program();
        Console.Write("Enter your name:\t");
        p.name = Console.ReadLine(); // No Error!!
        p.print();
        Console.ReadLine();
      }
   }
}


Internal Access Specifier

Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly. In other words, any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined.

The type or member can be accessed by any code in the same assembly, but not from another assembly.
Whereas assembly is a project which is compiled together.
The following program illustrates this:
using System;
namespace RectangleApplication
{
    class Rectangle
    {
        //member variables
        internal double length;
        internal double width;
        
        double GetArea()
        {
            return length * width;
        }
       public void Display()
        {
            Console.WriteLine("Length: {0}", length);
            Console.WriteLine("Width: {0}", width);
            Console.WriteLine("Area: {0}", GetArea());
        }
    }//end class Rectangle    
    class ExecuteRectangle
    {
        static void Main(string[] args)
        {
            Rectangle r = new Rectangle();
            r.length = 4.5;
            r.width = 3.5;
            r.Display();
            Console.ReadLine();
        }
    }
}
When the above code is compiled and executed, it produces following result:
Length: 4.5
Width: 3.5
Area: 15.75
In the preceding example, notice that the member function GetArea() is not declared with any access specifier. Then what would be the default access specifier of a class member if we don't mention any? It is private.

Output 


Enter your name:     Steven Clark

My name is Steven Clark 

Protected Internal Access Specifier

The protected internal access specifier allows a class to hide its member variables and member functions from other class objects and functions, except a child class within the same application. This is also used while implementing inheritance.

Example:


using System;

namespace Internal_Access_Specifier
{
  class access
   {
     // String Variable declared as internal
     internal string name;
     public void print()
      {
        Console.WriteLine("\nMy name is " + name);
      }
   }

  class Program
   {
     static void Main(string[] args)
      {
        access ac = new access();
        Console.Write("Enter your name:\t");
        // Accepting value in internal variable
        ac.name = Console.ReadLine();
        ac.print();
        Console.ReadLine();
      }
   }
}



Output 


Enter your name:     Steven Clark

My name is Steven Clark

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