features:
1-it is a pure oops based language
2-it is a case sensitive language
3-it derives its syntax's from c-language and oops concept from c++.
variable:
it is a named location created in the system memory to store a value temporarily while
executing a program, and once the program is terminated the value is erased.
program structure in c#
TO SAVE: filename.cs
TO COMPILE: csc filename.cs
TO EXECUTE: filename
OPERATORS USED IN C#
1-ARITHMETIC
+,-,*,/
2-COMPARISION/RELATIONAL
>,<,>=,<=,<>
3-UNARY
++
--
POST INCREMENT - I++
4-SHORT HAND/COMPOUND
+=,-=,*=,/=
I=I+10
I+=10
5-TERNARY/CONDITIONAL
VARIABLE=CONDITION?TRUE:FALSE
6-BINARY
%
7-SHORT CIRCUIT
&&,||
1
8-LOGICAL OPERATOR
&&,||,!
PROGRAMMING CONSTRUCTIONS IN C#
1-CONDITIONAL
2-SEQUENCE
3-ITERATION
1-CONDITIONAL CONSTRUCTIONS
HERE "if" IS USED.
SYNTAX:
if (condition)
{
statements;
}
----------------------
if(codition)
{
statements;
}
else if (condition)
{
statements;
}
else
{
statements;
}
2-sequence constructions
HERE "switch" CASE
SYNTAX:
switch(expression)
{
case 1:
statements;
break;
case n:
statements;
break;
default:
statements;
break //mandatory
2
}
3-ITERATION CONSTRUCTIONS
A-WHILE
B-DO WHILE
C-FOR
D-FOR EACH
A-WHILE LOOP
SYNTAX:
while(condition)
{
statements;
counter variable;
}
B-DO WHILE
SYNTAX:
do
{
statements;
counter variable;
}while(condition);
C-FOR
SYNTAX:
for(init;conditiion;counter variable)
{
statements;
}
D-for each
syntax:
for each(variable decl in array/collection name)
{
statements;
}
ARRAYS:
A contigious block of memory location having save datatype and name.
SINGLE/DOUBLE DIMENSIONAL
SINGLE DIMENSIONAL
SYNTAX:
datatype[] arrayname = new datatype[size];
int[] arr = new int[5];
3
arr[0]=10 ;
int[] arr = {10,20,30,40,50};
DOUBLE DIMENSIONAL
SYNTAX:
datatype[,] array name=new datatype[row,column];
int[,] arrayname = new int[2,3];
arr[0,0]=10
4
USE OF TERNARY OPERATOR
using System;
class test
{
static void Main()
{
int n;
string res;
Console.Write("Enter a number: ");
n=Int32.Parse(Console.ReadLine());
res=(n%2==0?"Even No":"Odd No");
Console.Write("\n"+res);
}
}
using System;
class demo
{
static void Main()
{
Console.WriteLine("This is my first program");
string nm;
int age;
Console.Write("\n"+"Enter your name and age: ");
nm=Console.ReadLine();
//age=Convert.ToInt32(Console.ReadLine());
age=Int32.Parse(Console.ReadLine());
Console.WriteLine("Your name & age is: {0} - {1}",age,nm);
//Console.WriteLine("Your name is: ",nm,"and age is: "+age);
}
}
using System;
class demo
{
static void Main()
{
int a;
Console.WriteLine("Enter a no: ");
a=Convert.ToInt16(Console.ReadLine());
Console.WriteLine("The value of a is: {0}",a);
5
}
}
using System;
class ifdemo
{
Stativ Void Main()
{
int n;
Console.WriteLine("enter a no:");
n=Int32.Parse(Console.ReadLine());
if(n%2==0)
{
Console.WriteLine("{0} is an even number",n);
}
else
{
Console.WriteLine("{0} is an odd number",n);
}
}
}
using System;
class demoswitch
{
static void Main()
{
int day=0;
Console.WriteLine("Enter a weekday serial no[1-7]:");
day=Int32.Parse(Console.ReadLine());
switch(day)
{
case 1:
Console.WriteLine("Monday");
break;
case 7:
Console.WriteLine("Sunday");
break;
default:
Console.WriteLine("Invalid Number Entered");
6
break;
}
}
}
using System;
class whileprg
{
static void Main()
{
int n=0;
while(n<=10)
{
Console.WriteLine(n);
n++;
}
}
}
using System;
class demowhile
{
static void Main()
{
int n=0;
do
{
Console.WriteLine(n);
n++;
}while(n<=10);
}
}
using System;
class demo
{
7
static void Main()
{
//int[] arr = new int[5];
int[] arr = {10,20,30,40,50};
//Console.WriteLine("Enter 5 no's in an array");
/*for(int i=0;i<5;i++)
{
arr[i]=Convert.ToInt16(Console.ReadLine());
}*/
Console.WriteLine("The contents of array is as follows");
foreach(int i in arr)
{
Console.WriteLine(i);
}
/*for(int i=0;i<5;i++)
{
Console.WriteLine(arr[i]);
}*/
}
}
using System;
class demo
{
static void Main()
{
//int[,] arr = new int[2,3];
int[,] arr = {{10,20,30},{40,50,60}};
Console.WriteLine("Enter no's in 2x3 array");
/*for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
arr[i,j]=Convert.ToInt16(Console.ReadLine());
}
}*/
Console.WriteLine("The contents of array is as follows");
/*foreach(int i in arr)
{
Console.WriteLine(i);
}*/
8
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
Console.Write(" "+"{0}",arr[i,j]);
}
Console.WriteLine("");
}
}
}
using System;
9
{
Console.Write("\t{0}",arr[i]);
}
Console.WriteLine(" ");
10
Console.WriteLine(" ");
int ln = arr1.Length; //length is a property
Console.WriteLine("The length of array after using length function");
Console.WriteLine("The length of array is :{0}",ln);
Console.WriteLine(" ");
Console.WriteLine("The array -ARR- is of {0} dimensional array",arr.Rank);
Console.WriteLine("The array -ARR2- is of {0} dimensional array",arr2.Rank);
Console.WriteLine("The value of index 3 in arr is: {0}",arr.GetValue(3));
Console.WriteLine("The value of index 2 in arr is: {0}",Array.IndexOf(arr1,10));
}
}
using System;
class demo
{
static void swap(int x, int y)
{
int z=0;
z=x;
x=y;
y=z;
Console.WriteLine("The value of a and b after swapping is: {0} & {1}",x,y);
}
static void Main()
{
int a,b;
a=10;b=20;
Console.WriteLine("The value of a and b before swapping is: {0} & {1}",a,b);
swap(a,b);
Console.WriteLine("The value of a and b after swapping is: {0} & {1}",a,b);
}
}
using System;
class demo
{
public int a,b;
public void swap(demo d)
{
int z=d.a;
d.a=d.b;
d.b=z;
11
}
}
class test
{
static void Main()
{
demo d = new demo(); //class object created
d.a=10;d.b=20;
Console.WriteLine("The value of a and b before swapping is: {0} & {1}",d.a,d.b);
d.swap(d);
Console.WriteLine("The value of a and b after swapping is: {0} & {1}",d.a,d.b);
}
}
using System;
struct MyStruct
{
public int x;
public int y;
}
class demo
{
public static void Main()
{
MyStruct ms = new MyStruct();
ms.x = 10;
ms.y = 20;
int sum = ms.x + ms.y;
Console.WriteLine("The sum is {0}",sum);
}
}
using System;
struct MyStruct
{
public static int x = 25;
public static int y = 50;
}
class demo
{
public static void Main()
12
{
int sum = MyStruct.x + MyStruct.y;
Console.WriteLine("The sum is {0}",sum);
}
}
using System;
struct MyStruct
{
static int x = 25;
static int y = 50;
public void test1(int i, int j)
{
x = i;y = j;
Console.WriteLine("Value of x and y in test is: {0} - {1}",x,y);
}
public void test2(int i)
{
x = i;y = i;
Console.WriteLine("Value of x and y in test2 is: {0} - {1}",x,y);
}
}
class MyClient
{
public static void Main()
{
MyStruct ms1 = new MyStruct();
MyStruct ms2 = new MyStruct();
ms1.test1(100,200);
ms2.test2(500);
}
}
using System;
class democlass
{
public string nm;
public int age;
}
class test
{
static void Main()
13
{
democlass d = new democlass();
Console.WriteLine("Enter u r name & age: ");
d.nm=Console.ReadLine();
d.age=Int32.Parse(Console.ReadLine());
Console.WriteLine("U r name & age is:{0} -{1}",d.nm,d.age);
}
}
PROGRAM ON CONSTRUCTOR
using System;
class democlass
{
public string nm,addr;
public int age,phno;
}
class test
{
static void Main()
{
democlass d = new democlass("sam",23);
democlass d1 = new democlass(2554714,"vizag");
Console.WriteLine("U r name,address,age & phno is:{0} - {1} - {2} &
{3}",d.nm,d1.addr,d.age,d1.phno);
}
}
14
PROGRAM ON USE OF PROPERTIES
using System;
class democlass
{
public string nm;
int age;
using System;
class demo
{
public int sum(int a, int b)
{
return a+b;
}
public string sum(string x, string y)
{
return x+y;
}
public double sum(double a, double b)
{
return a+b;
}
15
public void sum(string nm,string addr,int age)
{
Console.WriteLine("U r name,address and age is: {0} - {1} & {2}",nm,addr,age);
}
}
class test
{
static void Main()
{
demo d = new demo();
Console.WriteLine("{0}",d.sum(10,20));
Console.WriteLine("{0}",d.sum("vizag "," city"));
Console.WriteLine("{0}",d.sum(10.20,30.40));
d.sum("sam","vizag",20);
}
}
using System;
class faculty
{
public string nm,addr;
public int age;
16
mobno=Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Mobile no is: {0}",mobno);
}
}
class test
{
static void Main()
{
student s = new student();
Console.WriteLine("Enter details for faculty");
s.accept();
s.display();
Console.WriteLine("Enter details for student");
s.accept();
s.display();
s.accept1();
}
}
using System;
public class demo
{
public int hour,min;
17
PROGRAM ON USE OF FUNCTION OVERRIDING
using System;
class demo
{
public void display()
{
Console.WriteLine("This is base class's function");
}
}
class derived:demo
{
new public void display()
{
Console.WriteLine("This is derived class's function");
}
}
class test
{
static void Main()
{
derived d = new derived();
d.display();
}
}
using System;
18
Console.WriteLine("Total incentives for manager will {0} amount",inc);
}
}
public class mrkt:demobase
{
public new void incentives(double x)
{
x*=.1;
inc=x;
Console.WriteLine("Total incentives for marketing exe. will {0} amount ",x);
}
}
class test
{
static void Main()
{
manager m = new manager();
mrkt m2 = new mrkt();
Console.WriteLine("Enter amont to calculate incentives for category manager &
marketing executives");
m.inc=Convert.ToInt32(Console.ReadLine());
m.incentives(m.inc);
m2.incentives(m.inc);
Console.WriteLine("Amount for manager is:{0}",m.inc);
Console.WriteLine("Amount for mkt. exe is: {0}",m2.inc);
}
}
using System;
public abstract class democlass
{
public abstract void display(); //abstract method
19
}
}
class test
{
static void Main()
{
derived d = new derived();
democlass dc = d;//creation of base class object reference of derived type
dc.display();
d.example();
}
}
using System;
class year1:bank
{
public override void fixdept(int x,double y,int z)
{
double ri;
ri=(x*y*z)/100;
Console.WriteLine("Simple interest is: {0}",ri);
}
}
class year2:bank
{
public override void fixdept(int x,double y,int z)
{
double ri;
ri=(x*y*z)/100;
Console.WriteLine("Simple interest is: {0}",ri);
}
}
class test
{
static void Main()
{
year1 y2=new year1();
bank b1 = y2;
20
double r;
int m,p;
Console.WriteLine("Enter duration in months to calculate simple interest [12/24]");
m=Convert.ToInt32(Console.ReadLine());
switch(m)
{
case 12:
Console.WriteLine("Enter loan amount and rate of interest:");
p=Convert.ToInt32(Console.ReadLine());
r=Convert.ToDouble(Console.ReadLine());
//y1.fixdept(p,r,12);
b1.fixdept(p,r,12);
break;
case 24:
Console.WriteLine("Enter loan amount and rate of interest:");
p=Convert.ToInt32(Console.ReadLine());
r=Convert.ToDouble(Console.ReadLine());
//y1.fixdept(p,r,24);
b1.fixdept(p,r,12);
break;
default:
Console.WriteLine("Invalid value entered");
break;
}
}
}
using System;
public class baseclass
{
public virtual void display()
{
Console.WriteLine("This is virtual function");
}
}
public class derived:baseclass
{
public override void display()
{
Console.WriteLine("This is override function of derived class");
}
}
public class derived2:baseclass
{
21
public override void display()
{
Console.WriteLine("This is override function of derived2 class");
}
}
class test
{
static void Main()
{
baseclass dc = new baseclass();
derived d = new derived();
derived2 d2 = new derived2();
dc.display();
d.display();
d2.display();
}
}
using System;
public interface myinter
{
int sum(int x, int y);
int sub(int x, int y);
}
public class demo : myinter //inheriting the interface
{
public int sum(int x, int y)
{
return x+y;
}
public int sub(int x, int y)
{
return x-y;
}
}
class test
{
static void Main()
{
demo d = new demo();
int a,b;
Console.WriteLine("Enter two no's: ");
22
a=Convert.ToInt16(Console.ReadLine());
b=Convert.ToInt16(Console.ReadLine());
Console.WriteLine("The sum of {0} & {1} is: {2}",a,b,d.sum(a,b));
Console.WriteLine("The subtraction of {0} & {1} is: {2}",a,b,d.sub(a,b));
}
}
using System;
23
Console.WriteLine("The subtraction of {0} & {1}is: {2}",a,b,d.sub(a,b));
}
}
using System;
public interface myinter
{
void display();
}
public interface myinter2
{
void display();
}
public class derived:myinter,myinter2
{
void myinter.display()
{
Console.WriteLine("This is display function of first interface");
}
void myinter2.display()
{
Console.WriteLine("This is display function of second interface");
}
}
class test
{
static void Main()
{
derived d = new derived();
myinter m = (myinter) d;
m.display();
myinter2 m2 = (myinter2) d;
m2.display();
}
}
PROGRAM ON NAMESPACE’s
using System;
using trial;
namespace trial
{
public class demo
{
24
public void display()
{
Console.WriteLine("Hello friends");
}
}
namespace trial1
{
public class demo
{
public void display()
{
Console.WriteLine("Hello friends");
}
}
}
}
class test
{
static void Main()
{
//trial.demo d = new trial.demo();
demo d = new demo();
d.display();
trial.trial1.demo d1 = new trial.trial1.demo();
d1.display();
}
}
PROGRAM ON NAMESPACE’s-2
using System;
using trial;
using trial1.trial;
namespace trial
{
public class demo
{
public void display()
{
Console.WriteLine("Hello friends");
}
}
}
namespace trial1
{
public class demo
25
{
public void display()
{
Console.WriteLine("Hello friends");
}
}
public class test
{
public int sum(int x, int y)
{
return x+y;
}
}
namespace trial
{
public class trialclass
{
public int sum(int x, int y)
{
return x+y;
}
}
}
}
class test
{
static void Main()
{
//trial.demo d = new trial.demo();
demo d = new demo();
d.display();
trial1.demo d1 = new trial1.demo();
trial1.test t = new trial1.test();
d1.display();
Console.WriteLine("The sum is: {0}",t.sum(10,20));
//trial1.trial.trialclass tc = new trial1.trial.trialclass();
trialclass tc = new trialclass();
Console.WriteLine("The sum is: {0}",tc.sum(100,200));
}
}
26
PROGRAM ON CREATION OF DLL FILES OR SINGLE FILE ASSEMBLY
namespace ptax
{
public class stax
{
public double servicetax(double x)
{
return (x*12.36)/100;
}
}
}
using System;
using ptax;
class test
{
static void Main()
{
stax t = new stax();
double amt;
Console.WriteLine("Enter an amount: ");
amt=Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Service tax for amount {0} is: {1} and Total Amount is:
{2}",amt,t.servicetax(amt),amt+t.servicetax(amt));
}
}
PROGRAM ON EXCEPTION’s
using System;
class democlass
{
static void Main()
{
try
{
int a,c;
int[] b = new int[1];
Console.WriteLine("Enter 2 numbers: ");
a=Int32.Parse(Console.ReadLine());
27
b[2]=Int32.Parse(Console.ReadLine());
c=a/b[2];
}
//catch (System.Exception e)
catch(System.ArithmeticException e)
{
Console.WriteLine("Result is: {0}",e);
}
catch(System.FormatException e)
{
Console.WriteLine("Result is: {0}",e);
}
catch(System.IndexOutOfRangeException e)
{
Console.WriteLine("Result is: {0}",e);
}
}
}
PROGRAM ON EXCEPTION’s-2
using System;
class democlass
{
static void Main()
{
try
{
int a,b,c;
//int[] b = new int[1];
Console.WriteLine("Enter 2 numbers: ");
a=Int32.Parse(Console.ReadLine());
//b[2]=Int32.Parse(Console.ReadLine());
b=Int32.Parse(Console.ReadLine());
c=a/b;
Console.WriteLine("Result is: {0}",c);
}
catch(System.Exception e)
{
Console.WriteLine(e.StackTrace);
Console.WriteLine(e.Message);
Console.WriteLine(e.ToString());
Console.WriteLine(e.Source);
}
}
}
28
PROGRAM ON EXCEPTION’s – USER DEFINED EXCEPTION USING THROW
KEYWORD
using System;
class democlass
{
static void Main()
{
try
{
string nm;
int age;
Console.WriteLine("Enter u r name & age between [>=20 - <=30]: ");
nm=Console.ReadLine();
age=Int32.Parse(Console.ReadLine());
if((age<20) || (age >30))
throw new System.Exception(age.ToString());
Console.WriteLine("U r name & age is: {0} - {1}",nm,age);
}
catch(System.Exception e)
{
Console.WriteLine("Invalid age entered i.e.{0}",e);
}
}
}
PROGRAM ON DELEGATES-1
using System;
public delegate int demodele(int x, int y);
29
static void Main()
{
democlass d = new democlass();
demodele del;
del = new demodele(d.sum);
demodele del1 = new demodele(d.mul);
Console.WriteLine("Enter two no's to addition: ");
int a=Int16.Parse(Console.ReadLine());
int b=Convert.ToInt16(Console.ReadLine());
Console.WriteLine("The sum of {0} & {1} is: {2}",a,b,del(a,b));
Console.WriteLine("The multiplication is: {0}",del1(a,b));
}
}
PROGRAM ON DELEGATES-2
using System;
delegate void dlgSimple();
delegate double Addition();
class Exercise
{
private static void Welcome()
{
Console.WriteLine("Welcome to the Wonderful World of C# Programming!");
}
private static double Plus()
{
double a = 248.66, b = 50.28;
return a + b;
}
static void Main()
{
dlgSimple Announce = new dlgSimple(Welcome);
Addition Add = new Addition(Plus);
Announce();
Console.WriteLine("\n248.66 + 50.28 = {0}", Add());
}
}
PROGRAM ON DELEGATES-3
using System;
public delegate int trial();
class democlass
{
30
int n;
public int sqr1
{
set{ n=value;}
get{return n;}
}
public democlass(int x)
{
sqr1=x;
}
public int sqr()
{
return sqr1*sqr1;
}
public void disp()
{
trial t = new trial(sqr);
Console.WriteLine("The square of {0} is: {1}",sqr1,t());
}
}
class test
{
static void Main()
{
int x;
Console.WriteLine("Enter a number to display square: ");
x=Int32.Parse(Console.ReadLine());
democlass d = new democlass(x);
d.disp();
}
}
PROGRAM ON EVENTS
using System;
delegate void dlgSimple(); //delegate declaration
class Exercise
{
public static event dlgSimple Simply; //event declaration
31
public static void SayHello() //raising of event
{
Simply();
}
static void Main()
{
Simply += new dlgSimple(Welcome);
SayHello();
}
}
PROGRAM ON INDEXER’s
TO USE ARRAY WITHOUT ARRAY NAME i.e. to use the array values
using class objects.
using System;
using System.Collections;
public class demoindexer
{
public int[] arr = new int[5];
public Hashtable arr1 = new Hashtable();
32
}
class test
{
static void Main()
{
demoindexer d = new demoindexer();
d.arr[0]=10;
d[1]=100; //indexer
demoindexer d1 = new demoindexer();
d1["first"]="sam";
d1["sec"]="sameer";
d1["third"]="pavan";
Console.WriteLine("The value of first pocket in array is:{0}",d.arr[0]);
Console.WriteLine("The value of second pocket using indexer is:{0}",d[1]);
Console.WriteLine("The value of 1,2 & 3 pocket using indexer is:{0}, {1} &
{2}",d1["first"],d1["sec"],d1["third"]);
}
}
using System;
using System.Data.SqlClient;
using System.Data;
class Class1
{
foreach(DataRow i in tbl.Rows)
{
foreach(DataColumn j in tbl.Columns)
{
String str=Convert.ToString(i[j]);
33
Console.Write((str.PadRight(8,' ')));
}
Console.WriteLine(" ");
}
cn.Close();
}
}
class test
{
static void Main()
{
//StreamReader sr = new StreamReader("D:\\anil\\csharp\\notes.txt");
StreamReader sr = new StreamReader(@"D:\anil\csharp\notes.txt");
String str="";
while(str != null)
{
Console.WriteLine(str);
str=sr.ReadLine();
}
sr.Close();
}
}
using System;
using System.IO;
class test
{
static void Main()
{
StreamWriter sw = new StreamWriter(@"d:\anil\csharp\notes1.txt");
String str="";
Console.WriteLine("Enter some text to be entered into the file:");
str=Console.ReadLine();
Console.WriteLine(str);
sw.Write(str);
sw.Close();
}
34
}
PROGRAM ON IO FILES i.e. creation of a new text files by coping existing files
using System;
using System.IO;
class Tester
{
private void Run( ) //user defined function
{
FileInfo f = new FileInfo(@"D:\anil\csharp\notes.txt");
StreamReader sr = f.OpenText( );
StreamWriter sw = new StreamWriter(@"D:\anil\csharp\notes2.txt");
string text;
do
{
text = sr.ReadLine( );
sw.WriteLine(text);
Console.WriteLine(text);
} while (text != null);
sr.Close( );
sw.Close( );
}
public static void Main( )
{
Tester t = new Tester( );
t.Run( );
}
}
PROGRAM ON IO FILES i.e. reading a file and displaying total line numbers
using System;
using System.IO;
class LineAtATime
{
static void LinePrint(Stream src) //user defined function
{
StreamReader r = new StreamReader(src);
int line = 0;
string aLine = "";
while ((aLine = r.ReadLine()) != null)
{
Console.WriteLine("{0}: {1}", line++, aLine);
}
}
public static void Main(string[] args)
35
{
foreach(string fName in args)
{
Stream src = new BufferedStream(new FileStream(fName, FileMode.Open));
LinePrint(src);
src.Close();
}
}
}
PROGRAM ON IO FILES i.e. reading a text file and check the existence and delete the file
using System;
using System.IO;
36
PROGRAM ON IO FILES i.e. appending contents into an existing file
using System;
using System.IO;
using System;
using System.IO;
//MyFile.CopyTo(@"d:\anil\csharp\notes2.txt");
//or
MyFile.CopyTo(@"d:\anil\csharp\notes2.txt", true);
}
}
PROGRAM ON IO FILES i.e. moving the file location from one to another.
using System;
using System.IO;
37
{
FileInfo MyFile = new FileInfo(@"d:\anil\csharp\notes2.txt");
MyFile.MoveTo(@"d:\anil\notes33.txt");
//or
//MyFile.MoveTo(@"d:\anil\notes33.txt", true);
}
}
using System;
using System.IO;
class test
{
static void Main()
{
FileInfo[] F;
int cnt=0;
DirectoryInfo di = new DirectoryInfo(".");
F=di.GetFiles("*.cs");
foreach(FileInfo t in F)
{
Console.WriteLine(t);
cnt++;
}
Directory.CreateDirectory(@"d:\satish\test");
DateTime info1 = Directory.GetCreationTime(@"D:\satish\test");
Console.WriteLine("This direcotry is created on: "+info1.ToString());
}
}
38
Object Serialization
This state is maintained in memory. Object Serialization is the process of reducing an object
instance into a format that can either be stored to disk or transported over a network. This
process is achieved so that the object can be recreated with its current state at a later point of
time or at a different location.
The object is persisted to disk using a particular formatter and sent across the network to another
co-operating machine which then receives the stream of data and deserializes it to get back the
object with its state unchanged.
using System;
namespace Serialization
{
[Serializable]
public class Test
{
public string name;
public int phno;
}
}
PROGRAM ON SERIALIZES i.e. to serialize a file using dll file in binary format
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using Serialization;
namespace binex
{
class demo
{
static void Main(string[] args)
{
Test t = new Test();
t.name="sameer";
t.phno=2557070;
Stream mystr =File.OpenWrite("D:\\anil\\csharp\\binserialization.dat");
BinaryFormatter f = new BinaryFormatter();
f.Serialize(mystr,t);
mystr.Close();
}
}
39
}
PROGRAM ON SERIALIZES i.e. to deserialize a file using dll file in binary format
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
//using Serialization;
namespace Serialization
{
class demo
{
static void Main(string[] args)
{
FileStream file = new FileStream("d:\\anil\\binserialization.txt", FileMode.Open);
BinaryFormatter f = new BinaryFormatter();
Test t = f.Deserialize(file) as Test;
Console.WriteLine(t.name);
Console.WriteLine(t.phno);
Console.ReadLine();
}
}
}
PROGRAM ON SERIALIZES i.e. to serialize a file using dll file in xml format
using System;
using System.Runtime.Serialization.Formatters.Soap;
using System.IO;
namespace Serialization
{
class demo
{
static void Main(string[] args)
{
Test t = new Test();
t.name="sam";
t.phno=2557070;
Stream mystr = File.OpenWrite("d:\\anil\\csharp\\binserialization2.xml");
SoapFormatter f = new SoapFormatter();
f.Serialize(mystr,t);
mystr.Close();
}
}
}
40
PROGRAM ON SERIALIZES i.e. to deserialize a file using dll file in xml format
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;
using System.Runtime.Serialization;
namespace Serialization
{
class demo
{
static void Main(string[] args)
{
FileStream file = new FileStream("d:\\anil\\csharp\\binserialization2.xml", FileMode.Open);
SoapFormatter f = new SoapFormatter();
Test t = (Test) f.Deserialize(file);
Console.WriteLine(t.name);
Console.WriteLine(t.phno);
Console.ReadLine();
}
}
}
Remoting -: A remote object is an object that runs on the server. The remote client calls the
methods of the remote object with the help of a proxy. It cannot call these objects directly. In
.NET it is very easy to differentiate remote objects from local objects.
THIS PROGRAM USED TO CREATE DLL FILE WHICH IS USED IN BOTH SERVER
AS WELL AS CLIENT PROGRAM
using System;
namespace Rem1Ex1
{
public class MyClass:System.MarshalByRefObject
{
public MyClass()
{
Console.WriteLine("This is the Constructor of MyClass");
}
41
}
}
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using Rem1Ex1;
namespace Rem1Ex2
{
class MyServer
{
static void Main(string[] args)
{
TcpServerChannel channel = new TcpServerChannel(8080);
ChannelServices.RegisterChannel(channel);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(MyClass),
"HelloWorld", WellKnownObjectMode.SingleCall);
//To execute this file the class library created in the remote1example need to be referenced.
using System;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using Rem1Ex1;
namespace Rem1Ex3
{
class MyClient
{
static void Main(string[] args)
42
{
ChannelServices.RegisterChannel(new TcpClientChannel());
MyClass obj =
(MyClass)Activator.GetObject(typeof(MyClass),"tcp://localhost:8080/HelloWorld");
int cnt=0;
for(cnt=0;cnt<5;cnt++)
{
obj.HelloWorld();
}
}
}
}
using System;
using System.IO;
using System.Security.Cryptography;
class SecretCode
{
string fileName;
string FileName{
set {
fileName = value;
}
get {
return fileName;
}
}
RijndaelManaged rm;
//Each algorithm has both a base class named after the algorithm (DES, Rijndael,RSA,
etc.) and an implementation of that algorithm provided by Microsoft.
SecretCode(string fName)
{
fileName = fName;
rm = new RijndaelManaged();
}
43
ICryptoTransform encoder = rm.CreateEncryptor();
CryptoStream str = new CryptoStream(src, encoder, CryptoStreamMode.Read);
using System;
using System.Threading;
class Class1
{
static void disp()
{
Console.WriteLine("Hello, from thread {0}", Thread.CurrentThread.Name);
44
}
public void ThreadStart()
{
disp();
}
using System;
using System.Threading;
class Class1
{
//public void disp()
static void disp()
{
for (int i=0;i<10;i++)
{
Console.WriteLine("Value {0}", i);
Thread.Sleep(100);
}
}
static void Main(string[] args)
{
Class1 obj = new Class1();
Thread t1 = new Thread(new ThreadStart(disp));
t1.Start();
Thread.Sleep(2000);
t1.Join(); // wait until the thread is completed
Console.WriteLine("Goodbye");
}
}
SYNCHRONIZATION
When your Visual Basic .NET programs use multiple threads, the applications may encounter
errors due to race conditions that occur when two or more threads require synchronized access to
a shared resource. To prevent race conditions from leading to errors, inVisual Basic .NET
45
programs we can use the SyncLock statement to protect shared resources. Using the SyncLock
statement, a user can prevent one thread from accessing a shared resource until the current thread
“unlocks” the object. To use the SyncLock statement, you must specify a variable, upon which
you want your code to apply a lock.
using System;
using System.Threading;
46
using System.Threading;
enum Desire {
Pontificate, Eating
}
class Table {
readonly int iDiners = 5;
Diner[] diners;
Chopstick[] chopsticks;
Table(){
diners = new Diner[iDiners];
diners[0] = new Diner("Lovelace","The difference engine rocks the most.");
diners[1] = new Diner("Hejlsberg","C# rules, ok?");
diners[2] = new Diner("Stroustrup","C++ is still the fastest");
diners[3] = new Diner("Gosling","Write once, run anywhere!");
diners[4] = new Diner("van Rossum","Brackets are bad");
chopsticks = new Chopstick[iDiners];
for (int i = 0; i < iDiners; i++) {
Chopstick c = new Chopstick();
chopsticks[i] = c;
diners[i].LeftChopstick = c;
diners[(i + 1) % iDiners].RightChopstick = c;
}
}
public static void Main(){
new Table();
}
}
class Diner {
readonly int basePonderTime = 1000; //10;
readonly int ponderTimeRand = 0;
readonly int baseEatTime = 1000; //10;
readonly int eatTimeRand = 0;
readonly int postEatTime = 1000; //10;
readonly int betweenChopstickTime = 1500; //50;
readonly int maxStartupDelay = 1000; //150;
readonly int starvationTimeout = 1000; //100;
static int totalMealsEaten = 0;
string name;
internal string Name{
get{ return name;}
}
string opinion;
Thread myThread;
Chopstick left;
internal Chopstick LeftChopstick{
47
set { left = value;}
get{ return left;}
}
Chopstick right;
internal Chopstick RightChopstick{
set{ right = value;}
get{ return right;}
}
Desire desire = Desire.Pontificate;
static Random r = new Random();
internal Diner(string name, string opinion){
this.name = name;
this.opinion = opinion;
ThreadStart ts = new ThreadStart(EatAndTalk);
myThread = new Thread(ts);
myThread.Start();
}
void EatAndTalk(){
Thread.Sleep(r.Next(maxStartupDelay));
while (true) {
if (desire == Desire.Eating) {
Eat();
} else {
Pontificate();
}
}
}
void Pontificate(){
Console.WriteLine(name + ": " + opinion);
Thread.Sleep(basePonderTime +
r.Next(ponderTimeRand));
desire = Desire.Eating;
}
void Eat(){
GetChopsticks();
Console.WriteLine(name + ": Eating");
Thread.Sleep(baseEatTime + r.Next(eatTimeRand));
Console.WriteLine(name + ": Burp");
Thread.Sleep(postEatTime);
ReleaseChopsticks();
Interlocked.Increment(ref totalMealsEaten);
desire = Desire.Pontificate;
}
void GetChopsticks()
{
Console.WriteLine(name+ ": Picking up left chopstick");
48
left.Pickup(this);
Thread.Sleep(betweenChopstickTime);
Console.WriteLine(name + ": Picking up right chopstick");
right.Pickup(this);
}
void ReleaseChopsticks(){
left.Putdown();
right.Putdown();
}
internal void Wait(int id){
Console.WriteLine(name
+ ": Waiting for chopstick[{0}]", id);
try {
Thread.Sleep(starvationTimeout);
Console.WriteLine(name
+ " starved to death waiting for "
+ " chopstick[{0}]", id);
Console.WriteLine("Meals served: "
+ totalMealsEaten);
myThread.Abort();
} catch (ThreadInterruptedException) {
}
}
internal void Interrupt(int id){
myThread.Interrupt();
Console.WriteLine(name
+ ": alerted to availability of "
+ "chopstick[{0}]", id);
}
}
class Chopstick {
static int counter = 0;
int id = counter++;
bool acquired = false;
Diner waitingFor = null;
internal void Pickup(Diner d){
if (acquired == true) {
waitingFor = d;
//Must wait
d.Wait(id);
}
acquired = true;
Console.WriteLine(d.Name
+ ": Got chopstick[{0}]", id);
}
internal void Putdown(){
49
Console.WriteLine(
"Chopstick[{0}] released", id);
acquired = false;
if (waitingFor != null) {
Console.WriteLine("Someone's waiting");
waitingFor.Interrupt(id);
}
waitingFor = null;
}}
ORACLE CONNECTIVITY-
Provider=MSDAORA.1;User ID=scott;PASSWORD=TIGER;Data
Source=oracle8i
50