Wednesday 4 July 2012

update values in parent window from child


This example explains how to Open PopUp Window In Asp.Net And Update Refresh Parent Child Values using ClientScript .

I am opening popup window from aspx page and updating values in parent window from child or popup window using javascript

I have added to labels in Home.aspx page and one button to open popup window.

I've also added a PopupWindow.aspx page which is having two textboxes and a button to update lable values of parent page.

The textboxes in popup window are populated with Text values of lables in parent page (Home.aspx), after making changes in textbox values i'm updating values back in parent page.

HTML source Parent page (Home.aspx)


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="JavaScriptDemo.Home" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function openPopUp() {
            var firstName = document.getElementById("txtFirstName").value;
            var lastName = document.getElementById("txtLastName").value;
            var url = "popupWindow.aspx?firstname=" + firstName + "&lastname=" + lastName;
            window.open(url, "popup", "width=400,height=200,left=300,top=150");
        }

        function updateValues(arr) {
            document.getElementById("txtFirstName").value = arr[0];
            document.getElementById("txtLastName").value = arr[1];
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;&nbsp;&nbsp;
        <asp:Label ID="lblFirstName" runat="server" Text="First Name"></asp:Label>&nbsp;
        <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
        <br />
        <br />
        &nbsp;&nbsp;
        <asp:Label ID="lblLastName" runat="server" Text="Last Name"></asp:Label>&nbsp;
        <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
        <br />
        <br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="btnModify" runat="server" Text="Modify" OnClientClick="openPopUp()" />
    </div>
    </form>
</body>
</html>

HTML SOURCE OF PopupWindow.aspx(child) page 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="popupWindow.aspx.cs" Inherits="JavaScriptDemo.popupWindow" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function updateParentAndClose() {
            var arr = new Array();
            arr.push(document.getElementById("txtFirstName").value);
            arr.push(document.getElementById("txtLastName").value);
            window.opener.updateValues(arr);
            window.close();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;&nbsp;&nbsp;
        <asp:Label ID="lblFirstName" runat="server" Text="First Name"></asp:Label>&nbsp;
        <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
        <br />
        <br />
        &nbsp;&nbsp;
        <asp:Label ID="lblLastName" runat="server" Text="Last Name"></asp:Label>&nbsp;
        <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
        <br />
        <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="btnModify" runat="server" Text="Modify" OnClientClick="updateParentAndClose()" />
    </div>
    </form>
</body>
</html>

SOURCE OF PopupWindow.aspx,cs (child) page

protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["firstname"] != null)
            {
                txtFirstName.Text = Request.QueryString["firstname"];
                txtLastName.Text = Request.QueryString["lastname"];
            }
        }

Wednesday 11 April 2012

Data Reader In ADO.NET


using System;
using System.Data.SqlClient;

class Program
{
static void Main()
{
SqlConnection con=new SqlConnection();
con.ConnectionString="server=.;database=student;integrated security=true;";
SqlCommand cmd=new SqlCommand();
cmd.Connection=con;
cmd.CommandText="SELECT * FROM student";
SqlDataReader reader;
con.Open();
reader=cmd.ExecuteReader();

Console.WriteLine("Sno\tSname\t\tCourse\tDuration");
Console.WriteLine("-------------------------------------------------------------------");
while(reader.Read())
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}",reader["Sno"],reader["Sname"],reader["Cname"],reader["duration"]);
Console.WriteLine();
}
reader.Close();
con.Close();
}
}

DataBase Connectivity in c#


using System;
using System.Data.SqlClient;

class Program
{
static void Main()
{
SqlConnection con=new SqlConnection();
SqlCommand cmd=new SqlCommand();
int n;
string command;

con.ConnectionString="server=.;database=Student;integrated security=true;";
cmd.Connection=con;

// command="CREATE TABLE student(Sno INT PRIMARY KEY IDENTITY(1,1),Sname VARCHAR(30),Cname VARCHAR(30),Duration INT)";
// cmd.CommandText=command;

// con.Open();
// Console.WriteLine("Connected to Sql Server");
// cmd.ExecuteReader();
// Console.WriteLine("Table Created Successfully");
// con.Close();

command="INSERT INTO student(Sname,Cname,Duration) VALUES ('SMRITI DABGAR','.NET',90)";
cmd.CommandText=command;

con.Open();
n=cmd.ExecuteNonQuery();
Console.WriteLine("{0} Records Inserted Successfully",n);
con.Close();

command="DELETE FROM student WHERE sno=1";
cmd.CommandText=command;

con.Open();
n=cmd.ExecuteNonQuery();
Console.WriteLine("{0} Records Deleted Successfully",n);
con.Close();

command="UPDATE student SET sname='ANKUR BHATNAGAR' WHERE sno=2";
cmd.CommandText=command;

con.Open();
n=cmd.ExecuteNonQuery();
Console.WriteLine("{0} Records Updated Successfully",n);
con.Close();

command="SELECT count(*) FROM student WHERE Cname='.NET'";
cmd.CommandText=command;

con.Open();
object ob=cmd.ExecuteScalar();
Console.WriteLine("Total No Of Records in .NET is: {0}",(int)ob);
con.Close();
}
}

StringBuilder in C#


//String classs and StringBuilder Class Comparision
using System;
using System.Text;
class Program
{
static void Main()
{
StringBuilder sb=new StringBuilder();

Console.WriteLine("\n......................String Builder Example......................\n");

sb.Append("This is a example of string");

Console.WriteLine("\nActual String is: '{0}'",sb.ToString());

sb.Replace("string","StringBuilder");
Console.WriteLine("\nAfter Replace String is: '{0}'",sb.ToString());

sb.Insert(0,"Extra ");
Console.WriteLine("\nAfter Insert String is: '{0}'",sb.ToString());

sb.Remove(0,5);
Console.WriteLine("\nAfter Remove String is: '{0}'",sb.ToString());

Console.WriteLine("\nStart Time: {0}",DateTime.Now.ToString("T"));
for(int i=0;i<100000;i++)
sb.Append(i);
Console.WriteLine("\nEnd Time: {0}",DateTime.Now.ToString("T"));

Console.WriteLine("\n......................String Example......................\n");
string s1="";

Console.WriteLine("\nStart Time: {0}",DateTime.Now.ToString("T"));
for(int i=0;i<100000;i++)
s1=s1+i;
Console.WriteLine("\nEnd Time: {0}",DateTime.Now.ToString("T"));
}
}

String Funtions in C#


// Program to demonstrate sting funtions
//Instance level funtions: ToUpper(), ToLower(), Trim(), Split(), IndexOf(), LastIndexOf(), Substing(), Contains
//Static Funtions: Concat()
using System;
class Program
{
static void Main()
{
string s1,s2;
s1="Hello";
s2="World";

s1=string.Concat(s1,s2);
Console.WriteLine("Cancat Result: {0}",s1);

Console.WriteLine("Upper Result: {0}",s1.ToUpper());
Console.WriteLine("Lower Result: {0}",s1.ToLower());

bool b=s1.Contains("World");
Console.WriteLine("Contains Result: {0}",b);

int n=s1.IndexOf("llo");
Console.WriteLine("IndexOF Result: {0}",n);

n=s1.LastIndexOf('l');
Console.WriteLine("LastIndexOf Result: {0}",n);

Console.WriteLine("Substring Result: {0}",s1.Substring(3));
Console.WriteLine("substring Result: {0}",s1.Substring(3,5));

s2="                    Ankur Bhatnagar                    ";
Console.WriteLine("Before Trim Result: {0}",s2.Length);
s2=s2.Trim();
Console.WriteLine("After Trim Result: {0}",s2.Length);

s2="ASP.NET,C#.NET,VB.NET";
string[] str=s2.Split(',');
Console.WriteLine("Split Result:");
foreach(string item in str)
{
Console.WriteLine("{0}",item);
}
}
}

Thursday 22 March 2012

Exception Handling in c#


//Program to handle exception using try catch finally
using System;
class Program
{
static void Main()
{
int x,y,z=0;

try
{
Console.Write("Enter X: ");
x=int.Parse(Console.ReadLine());
Console.WriteLine();

Console.Write("Enter Y: ");
y=int.Parse(Console.ReadLine());
Console.WriteLine();

z=x/y;
}
catch(Exception exp) //It is called as Most General Exception.It can handle all the exception because it is a top most pareant of all other exceptions
//class.So accourding to 'Run Time Polymorphism' Parent class contains the object of their children.
{
Console.WriteLine(exp.Message);
}
finally
{
Console.WriteLine("Result: {0}",z);
}
}
}

Multiple Catch Blocks


//Program to handle exception using try Multiple catch finally
using System;
class Program
{
static void Main()
{
int x,y,z=0;
try
{
Console.Write("Enter X: ");
x=int.Parse(Console.ReadLine());
Console.WriteLine();

Console.Write("Enter Y: ");
y=int.Parse(Console.ReadLine());
Console.WriteLine();

z=x/y;
}

catch(FormatException exp) //Called Specific Exception.Handles Only Exceptions Related to FormatException
{
Console.WriteLine("X and Y Both Must be Integer Type");
}

catch(DivideByZeroException exp) //Called Specific Exception.Handles Only Exceptions Related to DivideByZeroException
{
Console.WriteLine("You should not divide by 0");
}

catch(Exception exp) //Handles all Other Exceptions because it is known as General Exception.This must be at end of all exception Defined
//Why because it can handle all exception.So it must be at end of all Specific Exception.
{
Console.WriteLine(exp.Message);
}
finally
{
Console.WriteLine("Result: {0}",z);
}
}
}

Throwing Exception


//Program to throwing Exception Manually
using System;
class Program
{
static void Main()
{
int age=0;
try
{
Console.Write("Enter Age: ");
age=int.Parse(Console.ReadLine());
Console.WriteLine();

if(age<=0)
//throw is a keyword in c#.Net used to throw an exception.
throw new FormatException("Age Can not be less Than equal to zero");

if(age>100)
throw new FormatException("Invalid Range Of Age");
}
catch(Exception exp)
{
Console.WriteLine(exp.Message);
}
finally
{
Console.WriteLine("Entered Age: {0}",age);
}
}
}

Stack in C#


//Stack demonstration
using System;
using System.Collections;

class Program
{
static void Main()
{
Stack stackObj=new Stack();

stackObj.Push(20);
stackObj.Push(30);
stackObj.Push(50);
stackObj.Push(40);
stackObj.Push(60);
stackObj.Push(80);

//To Print Stack Objects
Console.WriteLine();
foreach(object obj in stackObj)
{
Console.WriteLine((int)obj);
}
Console.WriteLine();

for(int i=0;i<stackObj.Count;i=i+0)
{
Console.WriteLine((int)stackObj.Pop());
}
}
}

Generate Random no List


//Program to store 20 Random no in List and find sum of them.
using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
Random rdm=new Random(); // Random class is there in system namespace used to generate random numbers
List<int> lst=new List<int>();

for(int i=0;i<20;i++)
{
int n=rdm.Next(0,300); // Next Is a instance method of Random class used to generate Next Random no with in the specified Range.
lst.Add(n);
}

int sum=0;
Console.WriteLine();
foreach(int n in lst)
{
Console.Write("{0} ",n);
sum+=n;
}
Console.WriteLine("\n");
Console.WriteLine("Sum: {0}",sum);
}
}

Generic Queue


//Generic Queue demonstration
using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
Queue<int> queueObj=new Queue<int>();

queueObj.Enqueue(20);
queueObj.Enqueue(30);
queueObj.Enqueue(50);
queueObj.Enqueue(40);
queueObj.Enqueue(60);
queueObj.Enqueue(80);

for(int i=0;i<queueObj.Count;i=i+0)
{
Console.WriteLine(queueObj.Dequeue());
}
}
}

Queue in c#


//demonstration of Queue Class
using System;
using System.Collections;

class Customer
{
private int no;
private string name,request;

public Customer(int id)
{
no=id;
}

public int Id
{
get
{
return no;
}
}

public string Name
{
get
{
return name;
}
set
{
name=value;
}
}

public string Requestinfo
{
get
{
return request;
}
set
{
request=value;
}
}

}
class Program
{
static void Main()
{
Queue customerDetailsQueue=new Queue();

Customer c;

c=new Customer(1001);
c.Name="Ankur Bhatnagar";
c.Requestinfo="Network problem";
customerDetailsQueue.Enqueue(c);

c=new Customer(1002);
c.Name="Ankit Agarwal";
c.Requestinfo="Desktop problem";
customerDetailsQueue.Enqueue(c);

c=new Customer(1003);
c.Name="Tushar Agarwal";
c.Requestinfo="Mouse problem";
customerDetailsQueue.Enqueue(c);

//To print Queue Items
foreach (object obj in customerDetailsQueue)
        {
Console.WriteLine("Id: {0}, Name: {1},Request: {2}", ((Customer)obj).Id, ((Customer)obj).Name, ((Customer)obj).Requestinfo);
        }

Console.WriteLine();

for(int i=0;i<customerDetailsQueue.Count;)
{
Customer obj= (Customer)customerDetailsQueue.Dequeue();
Console.WriteLine("Id: {0} Name: {1} Problem:{2}",obj.Id,obj.Name,obj.Requestinfo);
}
}
}

Generic Stack


//Generic Stack demonstration
using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
Stack<int> stackObj=new Stack<int>();

stackObj.Push(20);
stackObj.Push(30);
stackObj.Push(50);
stackObj.Push(40);
stackObj.Push(60);
stackObj.Push(80);

for(int i=0;i<stackObj.Count;i=i+0)
{
Console.WriteLine(stackObj.Pop());
}
}
}

Generic List Collection


//Generic List Demonstration
using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
List<string> list=new List<string>();

list.Add("ASP.NET");
list.Add("C#.NET");
list.Add("VB.NET");
list.Add("Java");
list.Add("Jquery");

PrintList(list);

Console.WriteLine("\nAfter using Insert Statement list is:");
list.Insert(0,"JavaScript");
PrintList(list);

Console.WriteLine("\nAfter using Remove Statement list is:");
list.Remove("JavaScript");
PrintList(list);

Console.WriteLine("\nAfter using Remove At Statement list is:");
list.RemoveAt(1);
PrintList(list);
}

static void PrintList(List<string> list)
{
Console.WriteLine();
foreach(string s in list)
{
Console.Write("{0} ",s);
}
Console.WriteLine();
}

}

Generic sortedList Collection


// Create a Generic contact list of your friends using Generic Sorted List
using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
SortedList<string,string> ContactList=new SortedList<string,string>();

//Adding Names and address of your friend in contact list
ContactList.Add("Smriti Dabgar","Bareilly");
ContactList.Add("Ankur Bhatnagar","Hyderabad");

foreach(string key in ContactList.Keys)
{
Console.WriteLine("{0} Lives In {1}",key,ContactList[key]);
}
}
}

Creating SortedList


// Create a contact list of your friends using Sorted List
using System;
using System.Collections;

class Program
{
static void Main()
{
SortedList ContactList=new SortedList();

//Adding Names and address of your friend in contact list
ContactList.Add("Ankur Bhatnagar","Hyderabad");
ContactList.Add("Smriti Dabgar","Bareilly");


foreach(object key in ContactList.Keys)
{
Console.WriteLine("{0} Lives In {1}",key,ContactList[key]);
}
}
}

SortedList Collection class


//Program of sortedList Of Departments
using System;
using System.Collections;

class Program
{
static void Main()
{
SortedList deptList=new SortedList();

//Adding elements to sorted List
deptList.Add(20,"Sales");
deptList.Add(40,"Admin");
deptList.Add(10,"IT");
deptList.Add(30,"purchase");
deptList.Add(50,"Finance");

//Processing SortedList
foreach(object key in deptList.Keys)
{
string s=(string)deptList[key];
Console.WriteLine("Key: {0}, Value: {1}",key,s);
}
}
}

ArrayList in C#


//to demonstrate ArrayList Class
using System;
using System.Collections;

class Program
{
public static void Main()
{
ArrayList arr=new ArrayList();
arr.Add("ASP.NET");
arr.Add("C#");
arr.Add("SQL SERVER");
arr.Add("ADO.NET");
arr.Add("JAVA SCRIPT");
arr.Add("JQUERY");

Console.WriteLine("Actual Array");
PrintList(arr);

Console.WriteLine("After adding Element Array is");
arr.Add("VB.NET");
PrintList(arr);

Console.WriteLine("After Inserting Element Array at First Position is");
arr.Insert(0,".NET TECHNOLOGY");
PrintList(arr);

Console.WriteLine("After Removing Element Array JQUERY is");
arr.Remove("JQUERY");
PrintList(arr);


Console.WriteLine("After Removing Element Array at First Position is");
arr.RemoveAt(0);
PrintList(arr);

Console.WriteLine("After Clearing Element Array ");
arr.Clear();
PrintList(arr);
}

public static void PrintList(ArrayList arr)
{
string str;
Console.WriteLine("\n");
foreach(object obj in arr)
{
str=(string)obj;
Console.Write(str+"  ");
}
Console.WriteLine("\n");
}
}

Method Arguments and Parameters


using System;
class ParamTest
{
//call by value
public  void Update(int a)
{
a=a+10;
}

//call by Reference
public  void Swap(ref int a,ref int b)
{
int t=a;
a=b;
b=t;
}

//call by Out
public  void Power(int a,out int b,out int c)
{
b=a*a;
c=a*a*a;
}
}

class Program
{
public static void Main()
{
ParamTest obj=new ParamTest();

int x=10,a=10,b=20,y,z;
Console.WriteLine("Before Update x={0}",x);
obj.Update(x);
Console.WriteLine("After Update x={0}",x);

Console.WriteLine("Before Swapping a={0} and b={1}",a,b);
obj.Swap(ref a,ref b);
Console.WriteLine("Before Swapping a={0} and b={1}",a,b);

x=5;
obj.Power(x,out y,out z);
Console.WriteLine("X:{0}, Y={1} Z={2}",x,y,z);
}
}

Tuesday 13 March 2012

Boxing and Unboxing in c#


//Program to Demonstrate Boxing And Unboxing
using System;
class Program
{
static void Main()
{
int i=123; // Value Type

object obj=i;// Implicit Boxing

int j=(int)obj;// Explicit/ Unboxing

//string s=(string)obj;//Note: This Statement will Give System.InvalidCastException
//why because object is boxed an int value while we r trying to convert it in to string

Console.WriteLine(j);
}
}

DateTime Structure In C#


// Program to demonstrate DateTime
using System;

class Program
{
static void Main()
{
DateTime d=DateTime.Now;

//To Print Only Date
Console.WriteLine("------------Date Only------------");
Console.WriteLine(d.ToString("d"));
Console.WriteLine(d.ToString("D"));


//To Print Only Time
Console.WriteLine("------------Time Only------------");
Console.WriteLine(d.ToString("t"));
Console.WriteLine(d.ToString("T"));

//To Print Only Day
Console.WriteLine("------------Day Only------------");
Console.WriteLine(d.ToString("dd"));
Console.WriteLine(d.ToString("ddd"));
Console.WriteLine(d.ToString("dddd"));

//To Print Only Month
Console.WriteLine("------------Month Only------------");
Console.WriteLine(d.ToString("M"));
Console.WriteLine(d.ToString("MM"));
Console.WriteLine(d.ToString("MMM"));
Console.WriteLine(d.ToString("MMMM"));

//To Print Only Year
Console.WriteLine("------------Year Only------------");
Console.WriteLine(d.ToString("YYYY"));
Console.WriteLine(d.ToString("YY"));

//To Print Only hours
Console.WriteLine("------------Hours Only------------");
//Console.WriteLine(d.ToString("H"));
Console.WriteLine(d.ToString("HH"));

//To Print Only Minutes
Console.WriteLine("------------Minutes Only------------");
Console.WriteLine(d.ToString("m"));
Console.WriteLine(d.ToString("mm"));

//To Print Only Seconds
Console.WriteLine("------------Seconds Only------------");
Console.WriteLine(d.ToString("s"));
Console.WriteLine(d.ToString("ss"));

//To Print Diffrent Cobinations of Date Time
Console.WriteLine("------------Combinations of above formats------------");
Console.WriteLine(d.ToString("ddd dd-MM-YYYY"));
Console.WriteLine(d.ToString("dddd, dd MMMM YYYY hh:mm:ss"));
}
}

Static Class in C#


//Demonstrate static Class with dateTime
using System;

static class TimeUtilClass
{
//To Print Only Time
public static void PrintTime()
{
Console.WriteLine(DateTime.Now.ToString("t"));
}

//To Print Only Date
public static void PrintDate()
{
Console.WriteLine(DateTime.Now.ToString("d"));
}

//To Print both Date and Time
public static void PrintDateTime()
{
Console.WriteLine(DateTime.Now.ToString());
}
}

class Program
{
static void Main()
{
TimeUtilClass.PrintTime();
TimeUtilClass.PrintDate();
TimeUtilClass.PrintDateTime();
}
}

Saturday 10 March 2012

To Access files and folders in C#


// To access files and folders of computer
using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
DirectoryInfo d = new DirectoryInfo(@"D:\myPhotos");

//To Print All Folders
        Console.WriteLine("-------------Folders-------------");
        foreach (DirectoryInfo di in d.GetDirectories())
        {
Console.WriteLine(di.Name);
        }

//To Print All Files
        Console.WriteLine("-------------Files-------------");
        foreach (FileInfo di in d.GetFiles())
        {
Console.WriteLine(di.Name);
        }

// To Create a directory
DirectoryInfo d1 = new DirectoryInfo(@"D:\myPhotos\Ankur");
        d1.Create();


//To Create, Copy and Move files
//--------------First Method---------------
        //File.CreateText(@"D:\myPhotos\Ankur.txt");
        //File.Copy(@"D:\myPhotos\Ankur.txt", @"D:\myPhotos\Ankur1.txt");
        //File.Move(@"D:\myPhotos\Ankur.txt", @"D:\myPhotos\Ankur2.txt");
//File.Delete(@"D:\myPhotos\Ankur.txt");

//--------------Second Method---------------
FileInfo fi = new FileInfo(@"D:\myPhotos\Ankur.txt");
         //fi.Create();
         //fi.CopyTo(@"D:\myPhotos\Ankur1.txt");
         fi.MoveTo(@"D:\myPhotos\Ankur2.txt");
         fi.Delete();

        Console.ReadLine();
    }
}

Get Drive Names In system


// Program to get all drives name of your system
using System;
using System.IO;

class Program
{
static void Main()
    {
DriveInfo[] driveArray = DriveInfo.GetDrives();

        foreach (DriveInfo d in driveArray)
                Console.WriteLine("Drive: {0}, Type: {1}, Free Space: {2}, Format: {3}, IsReady:{4}, Root Directory: {5},"+
            "Total Free sapce: {6}, Total Space: {7}, Volume Label: {8}", d.Name,d.DriveType,d.AvailableFreeSpace,d.DriveFormat,d.IsReady,d.RootDirectory,d.TotalFreeSpace,d.TotalSize,d.VolumeLabel);

        Console.ReadLine();
    }
}

Static Members in C#


//WAP to demonstrate static members
using System;
class Student
{
//Object Level Data Declaration
int sno,age;
string sname;
//Class Level Data Declaration i.e. static
static string cname;

//Constructor to assign Id
public Student(int sno)
{
this.sno=sno;
}

//Read-Only Property for sno
public int Id
{
get{return sno;}
}

//Property for age
public int Age
{
get{return age;}
set{age=value;}
}

//Property for sname
public string Name
{
get{return sname;}
set{sname=value;}
}

//Static Property for cname
public static string CollegeName
{
get{return cname;}
set{cname=value;}
}

//Print method
public void Print()
{
Console.WriteLine("\nId: {0}, Name: {1}, Age: {2}, College: {3}\n",sno,sname,age,cname);
}
}

class Program
{
static void Main()
{
Student.CollegeName="IME";

Student obj1=new Student(1011);
obj1.Name="Ankur Bhatnagar";
obj1.Age=26;
obj1.Print();

Student obj2=new Student(1012);
obj2.Name="Ankit Agarwal";
obj2.Age=27;
obj2.Print();
}
}

Interface in C#


//Interface Introduction
using System;

interface Shape// Declaring interface
{
void Area();
}

class Rectangle:Shape
{
public void Area()
{
Console.WriteLine("\nArea Of Rectangle Is Length*Breath");
}
}

class Square:Shape
{
public void Area()
{
Console.WriteLine("\nArea Of Square Is Side*Side");
}
}

class Circle:Shape
{
public void Area()
{
Console.WriteLine("\nArea Of Circle Is R*R*Pi");
}
}

class Program
{
static void Main()
{
Shape shapeObj;

shapeObj=new Rectangle();
shapeObj.Area();

shapeObj=new Square();
shapeObj.Area();

shapeObj=new Circle();
shapeObj.Area();
}
}

Abstract Classes In C#


// Abstract class Introduction
using System;

abstract class Shape// Declaring Abstract class
{
public abstract void Area();
}

class Rectangle:Shape
{
public override void Area()
{
Console.WriteLine("\nArea Of Rectangle Is Length*Breath");
}
}

class Square:Shape
{
public override void Area()
{
Console.WriteLine("\nArea Of Square Is Side*Side");
}
}

class Circle:Shape
{
public override void Area()
{
Console.WriteLine("\nArea Of Circle Is R*R*Pi");
}
}

class Program
{
static void Main()
{
Shape shapeObj;

shapeObj=new Rectangle();
shapeObj.Area();

shapeObj=new Square();
shapeObj.Area();

shapeObj=new Circle();
shapeObj.Area();
}
}

Overriding in C#


//Overriding demonstration
using System;
class Person
{
public virtual void Print()
{
Console.WriteLine("\nPrint Method Of Person Class\n");
}
}

class Student: Person
{
public override void Print()
{
Console.WriteLine("\nPrint Method Of Student Class\n");
}
}

class Program
{
static void Main()
{
//---------------First Method-------------------------
Person objPerson=new Person();
objPerson.Print();

Student objStudent=new Student();
objStudent.Print();
//----------------------------------------------------

//----------------Second Method-----------------------
// Accourding to runtime polymorphism base class reference can refer child class object

Person PersonObj;//Reference of Person class object

PersonObj=new Person(); // Pointing to base class object
PersonObj.Print();//Calling base class method Print()

PersonObj=new Student(); //Example of runtime polymorphism base class reference can refer child class object
PersonObj.Print();//Calling Drived class method Print()

//----------------------------------------------------
}
}

Tuesday 6 March 2012


.Net Version History

Version          Year          Visual Studio
.Net (Beta)        2000          VS.NET Beta
.Net 1.0              2002          VS.NET
.Net 1.1              2003           VS 2003
.Net 2.0              2005          VS 2005
.Net 3.0              Not for market
.Net 3.5              2008           VS 2008
.Net 4.0              2010           VS 2010
.Net 4.5              2011             VS 2011 Beta

Major Concepts Added In Different Versions:

.Net 1.1:
       1.ASP.NET Mobile Controls
          2.Retrieving data using data reader (HasRow property        introduced)
          3.Side By Side execution
          4.More Concentrate on framework Security
          5.IPV6 support

.Net 2.0:
1.   64 bit platform support
2.   Access control List Support
3.   ADO.NET
4.   ASP.NET
5.   COM Introp services
6.   Adding Console Class
7.   Data Protection in API
8.   Distributed Computing
9.   FTP Support
10.         Generics
11.         Globalization
12.         I/O
13.         Remoting
14.         Caching
15.         Security exception
16.         Serialization
17.         SMTP
18.         Threading
19.         Transaction
20.         Web Services
21.         Anomynous Type
22.         Partial Classes
23.         Nullable Types
24.         Master Pages
25.         Site navigation


.Net 3.0:

1.   WCF
2.   WPF
3.   WWF
4.   Windows CardSpace

    .Net 3.5:
1.   Collections
2.   Garbage Collector
3.   Cryptography
4.   Networking
5.   LINQ
6.   List View and Data Pager
7.   Ajax

.Net 4.0:
1.   DLR (Dynamic Language Runtime)
2.   Parallel Computing
3.   Optional and named Parameters
4.   Overridable Web.Config Settings