copyright ©2004 virtusa corporation | confidential introduction to c# k. r. c. wijesinghe trainer...
TRANSCRIPT
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Introduction to C#
K. R. C. Wijesinghe
TrainerVirtusa Corporation
2Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Introduction to C#
• Fully object oriented language.
• Specially built to work with Microsoft .Net Framework.
• Uses .Net Framework class library for all its operations.
3Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Types
• Type is the main unit of .Net Applications.
• They contains
• Data (member variables).
• Possible operations on that data (methods).
• The entry point or the starting point of a C# application is a public static void Main method, defined in one of the types of the assembly.
• An assembly containing a public static void Main method has the extension "exe" and can be directly executed by typing the its name in the command line or by double clicking it in the windows explorer
4Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Basic Example 1 (The Simplest Program)
class HelloClass{ public static void Main() {
System.Console.WriteLine ("Hello World");System.Console.ReadLine ( );
}}
Output:Hello World
•Main method can be called by .Net Framework without creating an instance of the class containing its definition, as it is a static member.
•WriteLine is also a static member of Console class in System namespace.
5Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Namespaces
Namespaces are used to logically organize types so that duplication of type names in two libraries does not affect to the application.
E.g.
If you say Saman there will be many Samans comes to your mind.
If you say Saman of the 2003 Batch, Faculty of Engineering, University of Peradeniya, then the person can be uniquely identified.
Now, 2000 Batch, Faculty of Engineering, University of Peradeniya is the namespace of Saman.
6Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Basic Example 2
using System;
class HelloClass{ public static void Main() {
Console.WriteLine(“Hello World”); }}
This will produce the same output as Basic Example 1
We can tell compiler to look at System namespace if the type name is not found in the current namespace using ‘using’ keyword.
7Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Base Types
The base types defined in .Net Framework and the key words used in C# to denote them are listed here
System.SByte
System.Byte
System.Int16
System.UInt16
System.Int32
System.UInt32
System.Int64
System.UInt64
System.Char
System.Single
System.Double
System.Boolean
System.DecimalSystem.String
C# Reserved Word .Net Type
sbyte
byte
short
ushort
int
uint
long
ulong
char
float
double
bool
decimal
string
8Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Using Value Type Variables
using System;
class MainClass{ public static void Main ( ) {
int n;int m = 5;n = 6;int sum = n + m;Console.WriteLine ("{0} + {1} = {2}",n ,m ,sum);Console.ReadLine ( );
}}
Output:
6 + 5 = 11
9Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Basic Console IO Example
using System;
class MainIOClass{ public static void Main( ) {
Console.Write("Name: ");string Name = Console.ReadLine( );Console.WriteLine("Your name is {0}", Name);Console.ReadLine ( );
}}
This small program get the name of the user and print it on the screen
10Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Type Conversion Example 1
using System;
class TypeConversionClass{ public static void Main( ) {
Console.Write("N :");string stN = Console.ReadLine( );int N = Convert.ToInt32(stN);// Same as, int n = int.Parse (stN);int Res = N * 5;Console.WriteLine("{0} x 5 = {1}", N, Res);Console.ReadLine( );
}}
11Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Type Conversion Example 2
using System;
class TypeConversionClass{ public static void Main( ) {
Console.Write("N :");int N = Convert.ToInt32(Console.ReadLine( ));Console.WriteLine("{0} x 5 = {1}", N, N*5);Console.ReadLine( );
}}
12Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Using Conditions
using System;
class MainClass{ public static void Main( ) {
int n = 65;if (n > 50){ Console.WriteLine ("Congratulation, You are Pass");}else{ Console.WriteLine ("Sorry, You are Fail");}Console.ReadLine ( );
}}
Output:Congratulation, You are Pass
13Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Using Loops
using System;
class MainClass{ public static void Main( ) { int i = 1; while (i <= 5) {
Console.WriteLine({0}x 5 = {1}”, i, i*5);i++;
} Console.ReadLine( ); }}
Output:1 x 5 = 52 x 5 = 103 x 5 = 154 x 5 = 205 x 5 = 25
using System;
class MainClass{ public static void Main( ) { for(int i=1; i <= 5; i++) {
Console.WriteLine({0}x 5 = {1}”, i, i*5); } Console.ReadLine( ); }}
Output:1 x 5 = 52 x 5 = 103 x 5 = 154 x 5 = 205 x 5 = 25
14Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Creating Classes
15Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Using Classes
using System;
class MainClass{ public static void Main( ) {
Rectangle rec = new Rectangle(10, 20);float area = rec.GetArea( );Console.WriteLine(“Area = {0}”, area);Console.ReadLine( );
}}
Output:Area = 200
16Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Static Methods and Variables
• Static methods and variables belongs to the type (class), not to an instance of it.
using System;
class Class1{ private static int Count = 0; public Class1( ) { Class1.Count ++; }
public static int GetInstaceCount( ) { return Count; }}
using System;
class PropertyTest{ public static void Main ( ) {
Class1 c1 = new Class1 ( ); Class1 c2 = new Class1 ( ); Class1 c3 = new Class1 ( );
Console.WriteLine (“ Instances = {0}”, Class1.GetInstanceCount( ) );
Console.ReadLine( ); }}
17Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Properties
using System;class Circle{ private float _r; public float Radius { set {
_r = value; } get {
return _r; } }
public float GetArea ( ) { return (float) Math.PI * _r * _r; }}
using System;
class PropertyTest{ public static void Main ( ) {
Circle c = new Circle ( ); c.Radius = 5;Console.WriteLine (“ Area = {0}”, c.GetArea ( ));Console.ReadLine( );
}}
18Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Properties
using System;class Circle{ private float _D; public float Radius { set {
_D = value * 2; } get {
return _D / 2; } }
public float GetArea ( ) { return (float) Math.PI * _D * _D / 4; }}
using System;
class PropertyTest{ public static void Main ( ) {
Circle c = new Circle ( ); c.Radius = 5;Console.WriteLine (“ Area = {0}”, c.GetArea ( ));Console.ReadLine( );
}}
19Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Reference Type Variables
using System;class MainClass{ public static void Main( ) {
Rectangle rec1 = new Rectangle(10, 20);Rectangle rec2 = rec1;rec2.SetSize(2, 3);float area = rec1.GetArea( );Console.WriteLine(“Area = {0}”, area);Console.ReadLine( );
}}
Output:Area = 6
Reference type variables copy the reference (instead of values) when we use ‘=’ sign to assign a variable.
20Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Reference Types Vs. Value Types
Reference Types Value Types
Defined in the Heap Defined in the stack
Removed during the garbage collection if it is no longer referenced by any other object.
Removed when it goes out of scope.
Copies the reference when ‘=‘ sing is used.
Copies the values when ‘=‘ sign is used.
Derived from “Object” type Derived from “ValueType” type.
Required addtional memory for reference
Does not require any additional memory
Can have a default constructor. Cannot have a default constructor.
Must use new keyword to create and instance.
Using new keyword is optional.
21Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Structures
• Structures are defined in exactly the same way as classes (replacing the keyword class with struct).
• However the instances of structures will be treated as value types.
• They are suitable for light weight objects like points, rectangles, colors, etc.
• Structures cannot have default constructors.
• We can create instances of structures without using new keyword, if we do not want to call a constructor.
• We can create instances of structures with new keyword if we want to use a constructor.
22Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Using Structures
using System;
class MainClass{ public static void Main( ) { Rectangle rec1; rec1.length = 2; rec1.width = 3;
Rectangle rec2 = rec1; rec2.length = 5; rec2.width = 6;
Rectangle rec3 = new Rectangle(2,4); float area1 = rec1.GetArea( ); float area2 = rec3.GetArea( ); Console.WriteLine(“{0}, {1}”, area1, area2); Console.ReadLine( ); }}
Output:6, 8
struct Rectangle{ public float width; public float length;
public Rectangle (float l, float w) { width = w; length = l; }
public float GetArea ( ) { return length * width; } }
23Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Arrays
• Methods of defining an array
• int[] n; n = new int[3]; n[0] = 1; n[1] = 2; n[2] = 4;
• int[] n = new int[]{1, 2, 4};
• Int[] n = {1, 2, 4};
24Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Using Arrays
using System;
class MainClass{ public static void Main( ) { int[] arr = new int[]{2, 4, 6} ; for (int i=0; i < arr.length; i++) {
Console.WriteLine(“{0}: {1}”, i, arr[i]); } Console.ReadLine( ); }}
Output:
0: 2
1: 4
2: 6
using System;
class MainClass{ public static void Main( ) { int[] arr = new int[]{2, 4, 6} ; foreach (int n in arr) {
Console.WriteLine(“:{0}”, n); } Console.ReadLine( ); }}
Output:
: 2
: 4
: 6
25Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Interfaces
• Interface is a contract between a class and its client.• If a class claims that it implements a given interface then that class must
implement all the method definitions in the interface as public methods.• Interfaces are very useful to write operations which will work on any object
(instances of different classes) that support the required set of methods.• Interfaces are widely used in .Net class library.
public interface IHello
{
void SayHello (string name );
string GetHelloString (string name);
}
26Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Using Interfaces
using System;
public class TestClass: IHello{
string HelloMsg;
public TestClass(string msg){ HelloMsg = msg;}
public void SayHello (string name ){ Console.WriteLine(HelloMsg + “ “ + name);}
public string GetHelloString (string name){ return HelloMsg + ” “ + name;}
}
27Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Interfaces
interface IPrintAbout{
void PrintAbout();}
class Man: IPrintAbout{
string _name;public Man(string name){_name = name;}public void PringAbout(){Console.WriteLine( "I am {0}", _name);}
}
class Car : IPrintAbout
{
string _brand;
public Car(string brand)
{
_brand = brand;
}
public void PrintAbout()
{
Console.WriteLine(
"This is a car of type {0}", _brand);
}
}
28Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Interfaec
public static void Main(){
Car c = new Car("Bense");Man m = new Man("Saman");IPrintAbout[] a = new IPrintAbout[2];a[0] = (IPrintAbout) c;a[1] = (IPrintAbout) m;for(int i=0;i < a.length;i++){
a[i].PrintAbout();}
}
29Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Collections
• Collection objects are used to store a collection of other objects
• A collection must implement IEnumerable interface which has only one method "GetEnumerator", in order to use foreach keyword to process each element of the collection
• A collection that implement ICollection interface, contains the property "Count" in addition to the properties required for sychroniztion in multi-threaded applications.
• A collection that implements IList interface can be accessed using an indexer Eg. if the collection name is c then elements in the collection can be
accessed like c[3], c[i]In addition they contains the methods,
Add, Insert, Clear, Contain, IndexOf, Remove and RemoveAtand properties
IsFixedSize and IsReadonly
30Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Collection
• ArrayList is a widely used general purpose collection.
Using ArrayList:ArrayList lst = new ArrayList( );lst.Add (“AAA”);lst.Add (2.3);Console.Writeline (“{0}, {1}”, lst[0], lst[1]);
Note that you have to include, “using System.Collections;” statement at the top, in-order to use “ArrayList”.
• Collections can be traversed using foreach keyword as shown below.ArrayList lst = new ArrayList( );lst.Add (“AAA”);lst.Add (“BBB”);foreach (string st in lst){ Console.WriteLine (“{0}”, st)}
31Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Name-Value Collection
This is a strongly typed collection (a collection that can only be used to store given type of objects) defined in .Net class library, to store a sorted list of strings.This collection uses both the index and a key to identify an element in the collection.
NameValueCollection col = new NameValueCollection();col.Add("A", "aaa");col.Add(“C", “ccc");col.Add(“B", “bbb");
StringBuilder b = new StringBuilder("Strings:");b.Append(col[0]+",");b.Append(col["B"] +",");b.Append(col.Get("C"));Console.WriteLine (b.ToString());
32Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Other Collections
• StringCollection - This is a strongly typed collection to store strings. Other than that this is similar to an ArrayList
• ListDictionary - A collection implemented using a link list. This can be accessed only using the key
• SortedList - Store the objects as sorted list. Can be accessed using key or an indexer
• Hashtable - Stores the collection elements in a hash table. Elements can be retrieved very efficiently. However elements cannot be accessed using indexes. The object used as key must implement Object.GetHashCode and Object.Equals methods (the String class commonly used as the hash implements these methods)
• StringDictionary - Similar to Hashtable, but a strongly typed to use strings as the key
33Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Inheritance
using System;
class Man{ private string name;
public Man(string name ) { this.name = name; }
public virtual void PrintAbout( ) { Console.WriteLine (“I am ”+name); }}
using System;
class Student: Man{ private string school;
public Student (string name, string school): base (name) {
this.school = school; }
public string GetSchool() //Additional method {
return school; }
// Overloaded Method // public new void PrintAbout( ) public override void PrintAbout( ) {
base.PrintAbout( );Console.WriteLine (“My School is ”+ school);
}}
34Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Using Inherited Classes
using System;
class MainClass{ public static void Main( ) {
Student st = new Student (“Saman”, ”AAA”);Console.WriteLine (“Student says”);st.PrintAbout( );Console.WriteLine( );
Man m = st;Console.WriteLine(“Man says”);m.PrintAbout( );Console.ReadLine( );
}}
35Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Abstract Class
• A class which cannot be used to create an instance of its own.
• These classes are used as parent classes for other classes.
E.g.public abstract class Man{
protected string name;
public Man(string name) {
this.name = name; }
public abstract void PrintAbout(); }
• This will generate an error
Man m = new Man (“Saman”);
36Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Sealed Class
• Classes can be sealed, to improve the efficiency of using virtual functions.
• When a class is not sealed, and it has a virtual or an override function, the compiler has create code to call the correct function even if it is an instance of a class derived from that class.
• If the class is sealed, it is guaranteed that no other class can be derived from this class. Therefore it is not necessary to think of the possibilities of the current instance of being an instance of a class derived from that class
• This also makes it possible to inline the function code, when it is efficient to do so.
E.g.sealed class MyClass: MyBase{
}
37Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Enumerations
• Enumerations are used to represent variables which can have only a given set of values.
using System;class Man{ public enum Genders {male, female }; private string name; private Genders gender; public Man(string name, Genders gender ) { this.name = name; this.gender = gender; }
public virtual void PrintAbout( ) { Console.WriteLine (“I am ”+name);
if (gender == Genders.male)Console.WriteLine (“I am a male”);
else Console.WriteLine (“I am a female”); }}
using System;
class EnumTest{ public static void Main ( ) {
Man m = new Man (“Saman”, Man.Genders.male);
m.PrintAbout ( );Console.ReadLine( );
}}
38Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Constants
using System;class Man{ public const float UnknownHeight = -1;
private float _height = 0;
public float Height {
set{ _height = value;}get{ return _height:}
} public virtual void PrintHeight( ) { if (_height == UnknownHeight)
Console.WriteLine (“I don’t know”); else Console.WriteLine (“I am {0} feet heigh”, _height); }}
using System;
class EnumTest{ public static void Main ( ) {
Man m1 = new Man ( );Man m2 = new Man ( );Man m3 = new Man ( );
m2.Height = Man.UnknownHeight;m3.Height = 6;
m1.PrintHeight ( );m2.PrintHeight ( );m3.PrintHeight ( );
Console.ReadLine( ); }}
39Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Namespaces
• Namespaces are used to prevent naming conflicts, i.e. two classes of the same project having the same name.
using System;
namespace NSTestClasses{ class Man {
string _name;
public Man(string name){ _name = name;}
public void PrintAbout( ){ Console.WriteLine (“I am ” + _name);}
}}
using System;class EnumTest{ public static void Main ( ) {
NSTestClasses.Man m = new NSTestClasses.Man (“Saman”);m.PrintAbout ( );Console.ReadLine( );
}}
using System;using NSTestClasses;
class EnumTest{ public static void Main ( ) {
Man m = new Man (“Saman”);m.PrintAbout ( );Console.ReadLine( );
}}
40Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
String Formatting
string st1 = string.Format ("Number 1 = {0}", 342.4537);string st1 = string.Format ("Number 2 = {0:f2}", 342.4537);string st1 = string.Format ("Number 3 = {0:c2}", 342.4537);string st1 = string.Format ("Number 4 = {0:e2}", 342.4537);
Console.WriteLine (st1);
Console.WriteLine (st1);
Console.WriteLine (st1);
Console.WriteLine (st1);
These commands results in
Number 1 = 342.4537
Number 2 = 342.45
Number 3 = $342.45
Number 4 = 3.42e+002
41Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Exception Handling
• Exceptions are widely used to indicate error conditions in .Net Framework.
• try, catch structure used in exception handling enables separation of programming logic from error handling logic, which makes the program more readable
• Therefore, proper exception handling is very important in any .Net application development.
• Exceptions are a convenient way of handling error conditions in custom library development as well.
• Any class derived from Exception class can be used to handle exceptions.
42Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Handling Exceptions 1
try{
Console.Write(“N: ”);
int n = Convert.ToInt32( Console.ReadLine( ));
Console.WriteLine(“You have typed {0}”, n);
}
catch (Exception ex) // Catch if an exception of type "FormateException" is thrown
{
Console.WriteLine (ex.Message);
}
finally // Execute this code finally, whether there is an exception or not
{
Console.WriteLine (“Press a key …”);
Console.ReadLine( );
}
43Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Handling Exceptions 2
while (true)
{
try{
Console.Write(“N: ”);
int n = Convert.ToInt32( Console.ReadLine( ));
Console.WriteLine (“You have typed {0}”, n);
break;
}
catch (FormatException ex) // Catch an exception of type "FormatException"
{
Console.WriteLine (“Invalid Number”);
}
catch (Exception ex) // Catch an exception of any other type
{
Console.WriteLine (“Error: ” + ex.Message);
}
}
44Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Throwing Exceptions
class NegativeNumberException:Exception{ int _n;
public int Number { set{_n = value;} get{return _n;} }
public override string Message { get { return string.Format("{0} is a negative number",_n); } }
public NegativeNumberException(int n) { _n = n; }}
class ExceptionTest{ static int Factorial(int number) { if (number < 0) throw new NegativeNumberException(number); int fac = 1; for(int i=1;i<=number;i++) fac*=i; return fac; } public static void Main ( ) { Console.Write("N: "); try { int n =
Convert.ToInt32(Console.ReadLine( )); int m = Factorial(n); Console.WriteLine("N: {0}",m); } catch(NegativeNumberException ex) { Console.WriteLine("Error: "+ex.Message); } }}
45Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Delegates and Events
• Delegates are used to refer a static or instance member function of a class, in a given format.
• Events are member variables which store delegates, which will be executed, when a certain event has occurred.
• These delegates and events are widely used in .Net Framework, Windows and Web application developments to handle the events generated by controls.
46Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Passing By Reference
static void Swap(ref int n1,ref int n2){
int tmp = n1;n1 = n2;n2 = tmp;
}
static void SetVal(out int n){
n = 5;}
static void Main(string[] args){
int a = 1;int b = 2;int c;
Swap(ref a,ref b);SetVal(out c);Console.WriteLine("a = {0}",a);Console.WriteLine("b = {0}",b);Console.WriteLine("c = {0}",c);Console.ReadLine();
}
47Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Using Delegates
public delegate void ResultHandler (string msg);
public class MulTable{
public ResultHandler OnResult;
int _m;
public MulTable(int multiplier) { _m = multiplier }
public void Calculate(int n) { for(int i=1;i<=n;i++) { string st = string.Format(“{0}x{1}={2}”,
i, _m, i*_m); OnResult (st); } }}
using System;
class DelegateTest{ static void mt_OnResult(string msg) { Console.WriteLine(">"+msg); }
public static void Main ( ) { MulTable mt = new MulTable(5); mt.OnResult = new ResultHandler (mt_OnResult); mt.Calculate(10);
Console.ReadLine( ); }}
48Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Asynchronous Function Calls
• Asynchronous function calls will be executed in a separate thread.
• Therefore, processor intensive tasks can be executed as asynchronous function calls, so that the main thread will response to UI events, without being interrupted.
private string Inc (int n){ for (int i=0; i<n; i++) { textBox1.Text = i.ToString(); Thread.Sleep(500); } return "End";}
private void CallBack (IAsyncResult res){ IncHandle h = (IncHandle) res.AsyncState; textBox1.Text = h.EndInvoke (res);}
private delegate string IncHandle (int n);
private void button1_Click (object sender, System.EventArgs e)
{ IncHandle d = new IncHandle (this.Inc); d.BeginInvoke (10, new AsyncCallback (CallBack), d);}
49Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Using Events
public delegate void ResultHandler(string msg);
public class MulTable{
public event ResultHandler OnResult;
int _m;
public MulTable(int multiplier) { _m = multiplier }
public void Calculate(int n) { for(int i=1;i<=n;i++) { string st = string.Format(“{0}x{1}={2}”,
i, _m, i*_m); OnResult (st); } }}
using System;
class EventTest{ static void mt_OnResult1(string msg) { Console.WriteLine(">"+msg); }
static void mt_OnResult2(string msg) { Console.WriteLine("#"+msg); }
public static void Main ( ) { MulTable mt = new MulTable(5); mt.OnResult += new ResultHandler (mt_OnResult1); mt.OnResult += new ResultHandler (mt_OnResult2); mt.Calculate(10);
Console.ReadLine( ); }}
50Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Streams
• Streams is a way of representing a sequence of bytes
• Disk files, TPC/IP sockets, devices, etc. are treated as streams.
• Stream is the base class for all the classes that represent streams, in .Net Framework.
• Some classes derived from stream class• FileStream – handles files in general
• StreamWriter – Write to text files
• StreamReader – Read frome a text file
• BinaryWriter – Write to binary files
• BinaryReader – Read from binary files
51Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Using StreamWriter
using System;using System.IO;
class StreamWriterTest{
static void Main(string[] args){
StreamWriter s = new StreamWriter(@"E:\Temp\test.txt");s.WriteLine("First Line of test file");s.WriteLine("Second Line of test file");s.WriteLine("Third Line of test file");s.Close();
Console.WriteLine("Done...");Console.ReadLine();
}}
52Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Using StreamReader
using System;using System.IO;class StreamReaderTest{
static void Main(string[] args){
StreamReader s = null;try{
s = new StreamReader(@"E:\Temp\test.txt"); string st; while((st = s.ReadLine()) != null) Console.WriteLine(st);}catch(IOException ex)
{ Console.WriteLine(“IO Error: “+ex.Message);}finally{ s.Close();}Console.ReadLine();
}}
53Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Using FileStream Directly
FileStream s1 = new FileStream(@"E:\Temp\test.txt", FileMode.Open);
int n = (int)s1.Length;byte[] b = new byte[n];s1.Read(b,0,n);s1.Close();
FileStream s2 = new FileStream(@"E:\Temp\test2.txt", FileMode.Create);s2.Write(b,0,n);s2.Close();
54Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Manipulating Disk Files
E.g.1
try{ if (File.Exists (@"E:\Temp\test2.txt")) { Directory.CreateDirectory (@"E:\Temp\Temp1");
File.Copy (@"E:\Temp\test2.txt", @"E:\Temp\Temp1\test3.txt");
File.Delete (@"E:\Temp\test2.txt"); }}catch (Exception ex){ Console.WriteLine(ex.Message);}
55Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Directory Listing
try
{DirectoryInfo SmpDir = new
DirectoryInfo (@"E:\Temp");FileInfo[] SmpFiles = SmpDir.GetFiles();Console.WriteLine("Sample Files");foreach (FileInfo SmpFile in SmpFiles){
Console.WriteLine(SmpFile.FullName); //Display file name with full path}
} catch (Exception ex) { Console.WriteLine("The process failed: {0}", ex.Message); }
56Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Installing a library in GAC
• Global Assembly Cache (GAC) is the place where shared .Net assemblies are installed
• GAC can save assemblies with the same name, but with different version numbers or different produces
• Strong named assembly is an assembly signed using a digital key, so that
• The producer of the assembly can get verified
• The assembly is guaranteed to be not modified by a third party
• The assembly contains a strong name (i.e. name, version, public key, culture combination) which is globally unique
• An assembly must be strong named in order to be installed in the GAC
• Installing an Assembly in GAC
• Generate a strong name Key pairsn –k C:\Temp\virtusa.snk
• Add assembly key file attribute and compile the code [assembly: AssemblyKeyFile(" C:\Temp\virtusa.snk ")]
• Install the assembly in GAC using gacutil toolgacutil –i C:\Temp\ClassLibrary1.dll
57Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Working with Garbage Collection
• Garbage Collection Automatically cleans up the memory used by objects, when they are no longer referenced by any root object or their members.
• If you use unmanaged resources in a class, you have to release them manually in the finalized method.
• If you have a Finalize method defined in your class the garbage collection will automatically call this member before releasing its memory.
• In C#, the Finalize method calls the destructor of the class and then that of its base class and so on.
• C# programmers should not override the Finalize method. They have to write the finalization code in the destructor of the class.
• Using Finalize method reduces the performance of the garbage collection as the objects with Finalize method has to be kept in a separate queue until the Finalized methods are finished executing.
58Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Disposing
• Programmers should not call the Finalize method manually.
• If we are using important resources in a class that are needed to be released, immediately after they are no longer needed, we have to implement IDisposable interface which contains the Dispose method.
• Then the Finalize method will have to do the clean up only if the user of the class has not properly called its Dispose method.
• However, leaving the Finalized method will reduces the performance of the garbage collection.
• Therefore calling Finalized method during garbage collection can be suppressed by calling,
GC.SuppressFinalize(this); in the Dispose method.
59Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Debug and Trace classes
• These classes are defined in System.Diagnosis namespace.
• Both classes has the same methods and properties.
• Methods in Debug class will work only if “DEBUG” macro is defined. (This is defined in Debug builds by default).
• Methods in Trace class will work only if “TRACE” macro is defined. (This is defined in Visual Studio.NET projects by default).
60Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
ASSERTS
• Asserts are used to ensure that a given condition is true at a given point in the program.
• Asserts will stop the program execution temporarily, if the condition is false, and provide you with three options. They are “Abort”, ”Retry” and “Ignore”.• Abort – Stop the program execution.• Retry – Take you to the Debug mode.• Ignore – Continue with the program.
E.g.
Stop execution if Obj is nullTrace.Assert (Obj != null);
Stop execution and display the message “Out of Range” if n > 100.Trace.Assert (n > 100, “Out of Range”);
61Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Logging
• Dumping information about intermediate steps of the program to an output device, without stopping the execution.
• This is very important in locating errors in complex programs.
• The default output is going to the “Output” window of Visual Studio.NET IDE.
• It can be send to console, a file or Windows event log.
62Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Logging Example
Trace.WriteLine (“Begin Section 1”);int n = 100;Trace.Indent( );Trace.WriteLine(“Inside Section 1”);Trace.WriteLine( n );n += 100;Trace.WriteLineIf (n > 150, “n greater than 150”);Trace.Unindent( );Trace.WriteLine(“End Section 1”);
Output:
Begin Section1Inside Section 1100 n greater than 150
End Section 1
63Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Sending output to Other devices
// Output to Console
Trace. Listeners.Add (new TextWriterTraceListener (Console.Out));
// Output to a file TextWriterTraceListener TraceFile = new TextWriterTraceListener(@“C:\Temp\Test.log”); Trace.Listeners.Add (TraceFile ); ... TraceFile.Close();
// Output to event log EventLogTraceListener ELog = new EventLogTraceListener("TestLog1"); Trace.Listeners.Add (ELog);
Trace.WriteLine( “Test Log Message”);
64Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Listing Type information in an Assembly
Console.Write("Assembly Name: ");string AssemblyName = Console.ReadLine();Assembly a = Assembly.LoadFrom(AssemblyName);Type[] types = a.GetTypes();foreach (Type t in types){
Console.WriteLine(t.Name);MemberInfo[] Members = t.GetMembers();foreach(MemberInfo m in Members){ string mName = m.Name; string mType = m.MemberType.ToString(); Console.WriteLine( "\t{0}-\t{1}",mName,mType);}
}
65Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Class to be Late-Bonded
public class MyClass{
public void SayHello(){
Console.WriteLine("Hello from MyClass");}
public void PrintMessage(string msg){
Console.WriteLine("Message: "+msg);}
}
66Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Late-Binding
Assembly a = Assembly.Load("ClassLibrary1");Type t = a.GetType("ClassLibrary1.MyClass");Object obj = Activator.CreateInstance(t);
MethodInfo m1 = t.GetMethod("SayHello");m1.Invoke(obj,null);
MethodInfo m2 = t.GetMethod("PrintMessage");Object[] para = new Object[] {"Message from
Caller"};m2.Invoke(obj,para);
67Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Using Resources
• Create a project under the namespace “ConsoleApplication1”
• Add an Assembly Resource File with the name “Resource1.resx” to your project
• Add a resource string with the name "HelloString" into that resource file
ResourceManager rm = new
ResourceManager("ConsoleApplication1.Resource1", Assembly.GetExecutingAssembly());string HelloString = rm.GetString ("HelloString");Console.WriteLine(HelloString);Console.ReadLine();
68Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Creating Attributes
[AttributeUsage (AttributeTargets.Class, AllowMultiple=true)]
public class MyTestAttAttribute: Attribute{
private string _name; private int _n;
public MyTestAttAttribute (string Name) { _name = Name; } public int Number {
get {return _n;} set {_n = value;}
} public string Name {
get {return _name;} set {_name = value;}
}}
69Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Appling Attributes
[MyTestAttAttribute ("AAA",Number=56)]public class Class2{
}
Or omitting the Attribute part of the attribute name
[MyTestAtt("AAA",Number=56)]public class Class2{
}
70Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Using Attributes
Assembly a = Assembly.GetExecutingAssembly();
Type[] types = a.GetTypes();foreach (Type t in types){
MyTestAttAttribute[] attArray = (MyTestAttAttribute[]) t.GetCustomAttributes( typeof (MyTestAttAttribute),
true);Console.WriteLine (t.Name);foreach (MyTestAttAttribute att in attArray){ Console.WriteLine ("\t(Name={0},Number={1})", att.Name,
att.Number);}
}
71Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Accessing Unmanaged Libraries
• A function in an unmanaged libraries (dll files) can be mapped into a manage function using "DllImport" attribute defined in "System.Runtime.InteropServices" namespace.
public class Win32 { [DllImport("user32.dll")] public static extern int MessageBox (int hWnd, String text, String caption, uint type);}
class Class1{ static void Main () {
Win32.MessageBox(0, "Hello World", "Platform Invoke Sample", 0); }}
72Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Passing Structures 1
• We have to specify the order in which the variables should appear, using attributes, when we are passing structures as parameters.
public class Win32 {
[StructLayout (LayoutKind.Sequential)]public struct Point { public int x; public int y; public Point(int x,int y) {
this.x = x; this.y = y; }}
[StructLayout (LayoutKind.Sequential)]public struct Rect { public int left; public int top; public int right; public int bottom; public Rect(int l,int t,int r,int b) {
left = l; top = t;right = r; bottom = b;
}}
[DllImport("User32.dll")]public static extern bool PtInRect(ref Rect r, Point p);
73Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Passing Structures 2
class Class1{ static void Main(string[] args) {
Win32.Rect rec = new Win32.Rect(0,0,10,10);Win32.Point pt = new Win32.Point(5,50);
bool b = Win32.PtInRect(ref rec, pt);
if (b) Console.WriteLine("Pt In Rec");else Console.WriteLine("Pt not in Rec");
Console.ReadLine(); }}
74Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Accessing COM objects
• Right click the Project Reference tab and select "Add Reference" option
• Select COM tab
• Select a COM component that you want to use in this project and click "Select"
• Select any other COM component if required, in the same way and click on "OK" button
• This will create a managed wrapper class to access the COM object
75Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Using XML
• Processing XML can be done basically using two methods (There are some other ways as well)
• Using XmlDocuemnt class
• Using XmlTextWriter and XmlTextReader classes
• XmlDocument loads data in to a hierarchical structure in the memory. This data can be queried using XPath expressions, modified and saved in files.
• Using XmlTextReader and XmlTextWriter is a faster way to read and write xml data in files. However they can operate forward only.
76Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
XmlTextWriter
XmlTextWriter xw = new XmlTextWriter( "E:\\Temp\\Test.xml", System.Text.Encoding.UTF8);
xw.WriteStartDocument();xw.WriteStartElement ("data",
"www.virtusa.com/training");
xw.WriteComment("Test XML Comments");
xw.WriteElementString("Description","Document to test xml writer");
xw.WriteStartElement("Books"); xw.WriteStartElement("Book"); xw.WriteAttributeString("id","34"); xw.WriteEndElement(); xw.WriteStartElement("User"); xw.WriteAttributeString("id","4"); xw.WriteString("Test XML String"); xw.WriteEndElement();xw.WriteEndElement();
xw.WriteEndDocument();xw.Close();
Generated Xml File
<?xml version="1.0" encoding="utf-8"?>
<data xmlns="www.virtusa.com/training">
<!--Test XML Comments-->
<Description>Document to test xml writer</Description>
<Books>
<Book id="34" />
<User id="4">Test XML String</User>
</Books>
</data>
77Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
XmlTextReader
Example Program
double tot = 0;XmlTextReader xr = new XmlTextReader("E:\\Temp\\Bill.xml");while(xr.Read()){ if (xr.NodeType ==XmlNodeType.Element) { if (xr.Name == "item") { xr.MoveToAttribute("unit_price"); double unit_price =
double.Parse(xr.Value); xr.MoveToAttribute("amount"); double amount = double.Parse(xr.Value); double price = unit_price * amount; tot += price; } }}xr.Close();
E:\Temp\Bill.xml File
<bill> <item name="AAA"
unit_price="10" amount="2" /> <item name="BBB"
unit_price="20" amount="1" /> <item name="CCC"
unit_price="15" amount="3" /></bill>
78Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Creating XmlDocument
XmlDocument doc = new XmlDocument();
XmlElement el1 = doc.CreateElement("MyDoc"); XmlElement el2 = doc.CreateElement("E1");
el2.SetAttribute("id","1"); XmlElement el4 = doc.CreateElement("S");
el4.InnerText="Test Text"; el2.AppendChild(el4); el1.AppendChild(el2);
XmlElement el3 = doc.CreateElement("E1"); el3.SetAttribute("id","2"); el1.AppendChild(el3);doc.AppendChild(el1);doc.Save("E:\\Temp\\Test.xml");
79Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Modify XmlDocument
XmlDocument doc = new XmlDocument();
// Load xml document from a filedoc.Load("E:\\Temp\\Test.xml");
//Query nodes using XPath Expressions//This will return the Xml node E1 under the node MyDoc, //whose attribute equals to 2XmlNode nd = doc.SelectSingleNode("MyDoc/E1[@id=2]");
//Create and initialize a new xml elementXmlElement el = doc.CreateElement("S");el.SetAttribute("id","a");el.InnerText="DDD";// Add the new element to the selected nodend.AppendChild(el);
// Save the modifed XmlDocument to a filedoc.Save("E:\\Temp\\Test.xml");