Notes
-
Upload
amarimmortal -
Category
Documents
-
view
30 -
download
3
Transcript of Notes
27.01.2010Working with C#
Syntactical Rules in C#- All keywords must be in lower case- All items except keywords starts with Capital letter
o Lengtho WriteLine()
Namespace- A collection of related set of classes, structures, enumerators etc.- Examples
o Systemo System.Webo System.Windowso System.Datao System.Data.OracleClient
General Input/Output Operations in C#
System namespace provides a class as Console for general IO operations. It provides some static methods
public static void Write()public static void WriteLine()public static string ReadLine()
ExampleSystem.Console.WriteLine("Welcome to C#");
Writing First C# Program
//First.csclass First{
public static void Main(){
System.Console.WriteLine("Welcome to C#");}
}
Compiling the code
CSC First.cs First.exe
The .exe files created with .NET are not the pure binary files but they are in MSIL or CIL (Common Intermediate Language) format.It needs the .NET framework to execute. .NET framework provides a software called CLR (Common Language Runtime) to compile and execute the programs.
.exe code verifier JIT Binary Code Execution
Note: To view contents of an MSIL file use ILDASM tool (Intermediate Language De-assembler)
ILDASM First.exe
Importing the Namespace- Use using keyword
using System;class First{
public static void Main(){
Console.WriteLine("Welcome to C#");}
}
Creating and Using Aliases
- Provides a shortcut technique to provide alias names to the namespaces, class, structure etc. but not for the fields and methods.
using c=System.Console;class First{
public static void Main(){
c.WriteLine("Welcome to C#");}
}
Using Visual Basic as Language
File Extension : .vbCase Insensitive
Keyword Changes
C# VB.NETstatic Sharedvoid Subusing Imports
Syntactical ChangesNo semicolon required.Use : operator as statement terminator if writing multiple statements in the same line.No more pair of braces {}, everything closes with endUse ' or REM to create the commentsCompiler will be VBC
' First VB Program – Test.vbclass First
public shared sub Main()System.Console.WriteLine("Welcome to VB")
End SubEnd Class
VBC Test.vb Test.exe
29.01.2009
Data Types in C#
- Keywords used to define the kind of data and amount of data a variable of that type can hold
- They are of two typeso Pre-defined Typeso User Defined Types
Pre-Defined Data Types
Data types defined by a language as keyword, under stood by the compilers. They are again of two types
1. Value Types2. Reference Types
All values types are defined under .NET Framework as structure and all reference types are defined as class.
Value Types (13)
Integrals
byte – 1 byte (unsigned)sbyte - 1 byte (signed)short – 2 bytes (signed)ushort – 2 bytes (unsigned)int – 4 bytes (signed)uint – 4 byte (unsigned)long – 8 bytes (signed)ulong – 8 bytes (unsigned)
Floatingsfloat – 4 bytes (7 DP)double – 8 bytes (15 DP)decimal – 16 bytes (28 DP)
Characterschar – 2 bytes (Unicode)
Booleansbool – 1 byte
Note: Use sizeof() operator to get size of any data type
using c=System.Console;class Test{ public static void Main() { c.WriteLine("Size of bool is "+sizeof(bool)); }}
Reference Types (2)
- To manage to references o string
To hold reference of some stringo object
To hold reference of any type
User Defined Types
- Used to create your own typeso Classo Structureo Enumeratoro Delegateso Events
Note:
1. .NET Framework provides a built-in structures and classes called as Common Base Classes or Common Type System (CTS) that get mapped to some data type inside a language.
C# Type CTS Visual Basicbyte System.Byte Byteint System.Int32 Integerlong System.Int64 Longfloat System.Single Singleetc.
2. In .NET Framework 3.5 we have one more type called var to hold variant kind of data in the variable
var num=56;num=67.9;num=”string”;
Data types in Visual Basic
Value Types
Visual C# .NET Visual Basic .NET .NET Framework
Bool Boolean System.Boolean
Byte Byte System.Byte
Short Short System.Int16
Int Integer System.Int32
Long Long System.Int64
Float Single System.Single
Double Double System.Double
Decimal Decimal System.Decimal
System.DateTime Date System.DateTime
string String System.String
char Char System.Char
object Object System.Object
sbyte n/a System.Sbyte
ushort n/a System.UInt16
uint n/a System.UInt32
ulong n/a System.UInt64
Variable Declaration in Visual Basic.NET
- Use Dim keyword to declare as variable
Dim age as IntegerDim age as Integer=5Dim n,m as Integer
01.02.2010
Working with Visual Studio.NET
A GUI tool from Microsoft that is RAD (Rapid Application Development) tool for fast .NET Programming.
class Test{ public static void Main() { System.Console.WriteLine("Welcome to C#"); //System.Console.ReadKey(); }}
Press Ctrl+F5 to run the program
Importing the namespaceusing System;class Test{ public static void Main() { Console.WriteLine("Welcome to C#"); //System.Console.ReadKey(); }}
Creating Aliases
using c=System.Console;class Test{ public static void Main() { c.WriteLine("Welcome to C#"); }}
Using Expressionsusing c=System.Console;class Test{ public static void Main() { int a = 5, b = 6; c.WriteLine("Sum of " + a + " and " + b + " is " + (a + b)); c.WriteLine("Sum of {0} and {1} is {2}", a, b, a + b); string s = string.Format("Sum of {0} and {1} is {2}", a, b, a + b); c.WriteLine(s); }
}
Literals
They are the values that we use from our side for assignment or in expressions.
Integrals- Default is int- Use l or L for long and u or U for unsigned
o int num=56;o long p=56L;o uint x=56U;
- Numbers can be o Decimalo Octal – Starts with 0o Hexa Decimal – Starts with 0x or 0X
Floating Literals- Default is double- Use f or F for floats and m or M for decimal as suffix
o double n=6.7;o float m=6.7; //erroro float m=6.7F; //correct
Character Literals- Enclosed in single quotes
o char ch=’A’;o char ch=(char) 65;
String Literals- Enclosed in double quotes- Managed by String class (string data type)
o string name=”Amit”;- Use @ to neutralize the escape character
o string path=@"c:\keshav";
- Use @ to create pre-formatted strings
Note:
If @ used as prefix with a keyword then that keyword can be used as identifierdouble @if;
03.02.2010
Reading data from Keyboard
- Use ReadLine() method Console class to read the datao public static string ReadLine()
- To convert data from string to any value type use Parse() method of the data type
ExampleWrite a program to get name and age of a person and check it to be valid voter.
Names stringAge int
Solutionclass VoterTest { static void Main(string[] args) { Console.Write("Enter the Name : "); string name = Console.ReadLine(); Console.Write("Age : "); int age = int.Parse(Console.ReadLine()); if (age >= 18) Console.WriteLine("Dear {0} you can vote", name); else Console.WriteLine("Dear {0} you cannot vote", name); } }
Getting input from command line
- When we run a program from Command Prompt and pass data at that prompt, it goes to Main() under string []args variable
o public static void Main(string []args)- Example
VoterCmd Rakesh 45
args[0] Rakeshargs[1] 45
Solution
//Using Command Line Inputusing System;class VoterCmd{
public static void Main(string []args){
if(args.Length<2){
Console.WriteLine("Syntax is : VoterCmd <name> <age>");return;
}string name=args[0];int age=int.Parse(args[1]);if (age >= 18)
Console.WriteLine("Dear {0} you can vote", name); else
Console.WriteLine("Dear {0} you cannot vote", name);
}}
Operators
int num=5 << 2; //20
OperatorsUsing ternary operator
Write a program to input the basic salary of a person from keyboard and print the DA based on following conditions using ternary operator (?:)
85% for basic >=1000060% for basic >=5000 else 50%
Hint: variable=condition?statatement for true : statement for false;
Switch case
- Every case including default must have the break or goto case- Allows int, char, enums and strings
class SwitchTest { public static void Main() { Console.Write("Enter a character : "); char ch = Console.ReadLine().ToUpper()[0]; switch (ch) { case 'A': case 'E' : case 'I' : case 'O' : case 'U': Console.WriteLine("{0} is a vowel", ch); break; default: Console.WriteLine("{0} is a consonent", ch); break; } } }
Adding a new class in same project
- to add a new class in same projecto Project Add Class…
Dealing with Multiple classes having Main() in same project
- Specify the class name from where to start the executable program from o Project Project Property Startup Object Class name
Dealing with multiple classes having Main() in same program- When we write a program having multiple class and many of them have the
entry points use /main:classname to specify the entry point at compile time with CSC
Example//MultiMain.csclass First{
public static void Main(){
System.Console.WriteLine("Calling from First");}
}
class Second{
public static void Main(){
System.Console.WriteLine("Calling from Second");}
}
05.02.2010Arrays
- A variable that can hold similar kind of multiple elements or homogenous group of elements
- Arrays can be of two typeso Single Dimensionalo Multi Dimensional
- Multi Dimensional again divided into two typeso Rectangular Arrayo Jagged Array or Complex Array or Array within array
Single Dimensional Array
- Use new keyword to create an arrayo int []num=new int[5];
- Now num has five elements num[0] to num[4]- We can Array class to advance operations on arrays
o Array.Sort(num);
Using foreach loop
- Used to work with arrays and collections without knowing size of array or collection and array indexes.
foreach(datatype variable in array or collectionname){
//statements}
Example class Program { static void Main(string[] args) { int[] num = new int[5]; for (int i = 0; i < num.Length; i++) { Console.Write("Enter number {0} : ", i + 1); num[i] = int.Parse(Console.ReadLine()); } Array.Sort(num); for (int i = 0; i < num.Length; i++) { Console.WriteLine(num[i]); }
foreach(int x in num) Console.WriteLine(x); } }
Rectangular Array
- A multi dimensional array where each row has equal number of columns- Also called as block matrix
int [,]num=new int[2,3];
Exampleclass RectangularArray { public static void Main() { int[,] num = new int[2, 3]; Console.WriteLine("Length is {0}", num.Length); Console.WriteLine("Rows are {0}", num.GetLength(0)); Console.WriteLine("Columns are {0}", num.GetLength(1));
num[0, 0] = 56;
} }
Jagged Array or Complex
- An array within array- It allows to create an array having equal or un-equal number of elements in
each row
int [][]num=new int[3][];
num[0]=new int[3];num[1]=new int[4];num[2]=new int[5];
num[0][0]=56;
Methods inside a class
- A class can have different methods and they can be called from other methods using different types
o Pass by input or pass by value (default)o Pass By Output (out keyword)o Pass by Reference (ref keyword)o Pass by Address (when using pointers)o Pass by params (params keyword)
To pass dynamic number of arguments
Passing arguments by params
- Allows to pass dynamic number of arguments inside a function- Use params keyword with such kind of argument
Exampleclass ParamsTest { public static void Sum(params double[] num) { double s = 0; foreach (double temp in num) s += temp; Console.WriteLine("Sum is {0}", s); } public static void Main() { Sum(4, 5, 6, 7, 8, 9); } }
Passing arguments to get an output
- Use out keyword in formal parameters as well as actual parameters
ExampleCreate a method that gets a number and returns the square and cube of that
number.
class OutTest { public static void ManyWorks(int n, out int sq, out int cb) { sq = n * n; cb = n * n * n; } public static void Main() { int x=5, y, z; ManyWorks(x, out y, out z); Console.WriteLine("Square is {0} and Cube is {1}", y, z); } }
Passing arguments by Reference- Use ref keyword in both the places- Variables must be initialized
class RefTest { public static void ManyWorks(int n, ref int sq, ref int cb) { sq = n * n; cb = n * n * n; } public static void Main() { int x = 5, y=0, z=0; ManyWorks(x, ref y, ref z); Console.WriteLine("Square is {0} and Cube is {1}", y, z); }
}
08.02.2010
Using Pointers in C#
- When using pointers in C#, the code is called as unsafe or unmanaged code- Such code get placed in separate area of memory called as un-managed area- Use unsafe keyword to define such areas in the program code- Use /unsafe switch while compilation with CSC
using System;class PointerTest { unsafe public static void ManyWorks(int n, int *sq, int *cb) { *sq = n * n; *cb = n * n * n; } public static void Main() { int x = 5, y=0, z=0;
unsafe {
ManyWorks(x, &y, &z); }
Console.WriteLine("Square is {0} and Cube is {1}", y, z); } }
Using Pointers in Visual Studio.NET Projects- When using pointers in Visual Studio Projects, check the checkbox
o [ ] Allow Unsafe codeo Project Project Properties Build
Application Development Models in .NET
There are two models
1. Single Executable Model2. Component Object Model (COM)
In case of single executable model, all classes get placed in single executable file, which makes the file bulky and increases the load time and memory consumption.
In case of COM, we can place the classes in different library files called Dynamic Link Library and give reference of the libraries into an executable file, giving smaller code for executable, less load time.
Example 1: Using Single Executable File
using c=System.Console;using System;class MyMaths{
public static double CubeRoot(double n){
return Math.Pow(n,1.0/3);}
}
class Test{
public static void Main(){
double num=5.6;c.WriteLine("Cube of {0} is {1}",num,MyMaths.CubeRoot(num));
}}
Example 2: Creating and using Dynamic Link Library
Write a program having a set of classes to be used as library. Use /t:library switch with CSC to compile a file as library. To use the dynamic link library in other programs use /r:filename.dll as reference.
All classes of a library to accesses outside the library must be public.
//MyLib.csusing System;public class MyMaths{
public static double CubeRoot(double n){
return Math.Pow(n,1.0/3);}
}
CSC /t:library MyLib.cs
Using a library
using c=System.Console;class Test{
public static void Main(){
double num=5.6;c.WriteLine("Cube of {0} is {1}",num,MyMaths.CubeRoot(num));
}
}
Creating a Class Library from Visual Studio
- Create a new project as class library- Define the namespaces, classes etc.
Giving reference of a DLL in Visual Studio
- Give the reference usingo Project Add Reference….
- Select Browse…- Select the file name and Ok- Import the namespace and use it
Note: When we do not specify any namespace name on a class, it goes to global namespace.
Using ILDASM Tool
- A tool to view contents of an assembly- It is called as Intermediate Language De-Assembler
12.02.2010
OOPs (Object Oriented Programming System)
- It is a system or methodology for better project management- It has certain components called pillars of OOPs
o Encapsulationo Abstractiono Polymorphismo Inheritance
- It is based on concept of class and object
What is a class?
A set of specifications about an entity to create similar set of objects. It defines the data elements (fields) and the methods that can be applied directly or by the objects.
Use class keyword to declare a class.
class <classname>{
//elements or members}
Types of Members inside a class
- Members can be of two typeso Static or Class Memberso Non-Static or Instance Members
Static Members or Class Members
- Can be accessed using a class only- Use static keyword with such members
Non-static or instance member- Always need an object to call such members- It is by default
What is Object?
A real entity create based on class specifications. To create an object we need a constructor.
What is a constructor?
Special method inside a class which has some features- Same name as class name- No return type- Used to initialize fields of a class- If no constructor is created the default constructor is created automatically- If we create any parameterized constructor then default constructor is not
created automatically, we have to create it- Can be overloaded- Constructor can be private as well
class Employee{ int empid,basic; string name; public static void LeaveInfo() { System.Console.WriteLine("EL : 5, CL:20, ML:14"); } public Employee(int empid, string name) { this.empid = empid; this.name = name; } public Employee(int empid, string name, int basic) { this.empid = empid; this.name = name; this.basic = basic; } public void ShowInfo() {
System.Console.WriteLine("Employee Id : " + empid); System.Console.WriteLine("Name : " + name); System.Console.WriteLine("Basic : " + basic); }}
class AbcIndia{ public static void Main() { Employee.LeaveInfo(); Employee x = new Employee(123, "Amit Verma", 5000); x.ShowInfo(); }
}
Kinds of elements inside a class
A class can have different elements- Field
o To hold some data- Methods
o To perform some action- Properties
o Special procedures that looks like fields- Indexer
o Allows to use an index number with the object to access some array or collection kind of information from a class
- Delegateo Allows to execute the methods indirectly
- Inner classeso A class within a class
Types of fields
- Used to hold some data- Can be of three types
o Variables (default)o Constants – use const keywordo Read Only – Use readonly keyword
15.02.2010
Types of Methods
Methods can be of two types1. Special
a. Constructorb. Destructor
2. Generala. Concrete Methodb. Abstract Method
c. Sealed Methods
Concrete Methods- Have the definition and can be called
void Show(){
System.Console.WriteLine(“Hello”);}
Abstract Methods- A method having the signature but no body contents- Can be written at two places
o Inside a classo Inside an interface
- If created inside a class use abstract keyword and such class must be declared as abstract. Abstract class can never be instantiated. Such methods get overridden in child class while inheritance.
- If created inside an interface, it is by default abstract and no abstract keyword is required.
abstract class X{
public abstract void Show();}
interface Y{
void Show();}
Sealed Methods
- Such method can never be overridden in child class- Use sealed keyword with such methods
Properties
- Special procedures that looks like field for outside world- A property can of three types
o Read Only (get)o Write Only (set)o Read/Write (set,get)
- A property has two blockso seto get
- Use value as reserve word input a value from outside
Syntax 1
<scope> <return type> <propertyname>{
set{
variable=value;}get{
return variable;}
}
Syntax 2 (Framework 3.0+)
<scope> <return type> <propertyname>{
get;set;
}
Example
using System;using System.Collections.Generic;using System.Linq;using System.Text;
namespace Batch02_1502{ class Program { static void Main(string[] args) { //Employee e1 = new Employee("Amit Kumar", 8000); //Console.WriteLine("Salary of {0} is for basic {1} is {2}", e1.getName(),e1.getBasic(), e1.getSalary()); //Employee e2 = new Employee(); //e2.setName("Rohit Kumar"); //e2.setBasic(6700);
//Console.WriteLine("Salary of {0} is for basic {1} is {2}", e2.getName(), e2.getBasic(), e2.getSalary());
Employee e3 = new Employee(); e3.Name = "Neeraj Verma"; e3.Basic = 9000; Console.WriteLine("Salary of {0} for Basic {1} is {2}", e3.Name, e3.Basic, e3.Salary); } } class Employee { string name; int basic; public Employee() { } public Employee(string name, int basic) { this.name = name; this.basic = basic; } public void setName(string name) { this.name = name; } public string getName() { return name; } public void setBasic(int basic) { this.basic = basic; } public int getBasic() { return basic; } public double getSalary() { return basic * 2.6; } public string Name {
set { name = value; } get { return name; } } public int Basic { set { basic = value; } get { return basic; } } public double Salary { get { return basic * 2.6; } }
}
}
Indexer
- A anonymous property that allows to access some array or collection value of an object using an index number with the object where object is not an array
- Use this keyword along with the index number in place of property name
Example 1 string s = "Amit";
char ch = s[1]; Console.WriteLine(ch);
Example 2
using System;using System.Collections.Generic;using System.Linq;using System.Text;
namespace Batch02_1502{ class IndexerTest { public static void Main() { //string s = "Amit"; //char ch = s[1]; //Console.WriteLine(ch); Student s = new Student(); s.Name = "Amit Verma"; string[] m = { "9876544", "924444", "90324324" }; s.Mobiles = m; Console.WriteLine("Second mobile of {0} is {1}", s.Name, s[1]); } } class Student { public string Name { get; set; } public string[] Mobiles { get; set; } public string this[int i] //Indexer { get { return Mobiles[i]; } } }}
Delegates
- Special class that allows to invoke a method indirectly- Use delegate keyword to declare a delegate
delegate <return type> <delegatename> (arguments);
using System;using System.Collections.Generic;using System.Linq;using System.Text;
namespace Batch02_1502{ class DelegateTest { delegate void MyDlg(int x, int y); public static void Sum(int a, int b) { Console.WriteLine("Sum is " + (a + b)); } public static void Product(int a, int b) { Console.WriteLine("Product is " + (a * b)); } public static void Main() { MyDlg d1 = new MyDlg(Sum); //d1(3, 4); MyDlg d2 = new MyDlg(Product); //d2(5, 6); MyDlg d3 = d1 + d2; d3(4, 5); MyDlg d4 = d3 - d1; d4(6, 7); } }}
17.02.2010
OOPs components
Encapsulation
- Combing all the members at once place, none of the members should be accessible outside without permission
- All members inside a class are private by default
Abstraction or Data Hiding
- Defines the abstraction layers on different members of a class- It controls the visibility of class itself and its members- C# allows five abstraction layers
Private (default) Within the class
Public Anywhere access
Protected In child class of same or other assembly
Internal In same assembly only
Protected Internal Direct access in same assembly and can be inherited in
same or different assembly
Project File
- A file having extension of .csproj or .vbproj- It contains information about the files in a project
Solution File
- A file having .sln extension that managed multiple projects
Example
Create a Project as Project1 under a Solution AbstractionTest
File New Project
Adding a new project in same solutionFile Add New Project
Project2
In Project1, Create a class as Abc and five fields in five different scopes.
public class Abc { private int a; public int b; protected int c; internal int d; protected internal int e; }
Create an object inside Main() of Project1 and check which members are visible (b,d,e)
Build this project to make the .EXE file
Now add the reference of Project1.exe into Project2
Now create an object of Abc class of Project1 inside Main() of Project2
Now see which members are visible (only b)
Now create another class Xyz and inherit Abc into that class using : operator. Then create a constructor and check which members are avaible (b,c,e)
class Xyz : Abc{
publi Xyz(){}
}
Polymorphism
- When an item can be allowed to perform more than one task is called as polymorphism
- It is a concept that get implemented using overloadingo C# allows two kind of overloading
Method Overloading Operator Overloading
Method Overloading
- Multiple methods having the same name but different number of arguments or type of arguments
class Xyz { int n; public Xyz() { } public Xyz(int n) { this.n = n; } public double SquareRoot() { return Math.Pow(n, 1.0 / 2); } public static double SquareRoot(int n) { return Math.Pow(n, 1.0 / 2); } }
Operator Overloading
When an operator can be used for multiple activities on different objects, is called as operator overloading.
Use an operator to be overloaded with operator keyword
A method works behind the scene using an anonymous method.
using System;
class Size { int feet, inch; public Size(int f, int i) { feet = f; inch = i; } public static Size Add(Size x, Size y) { int f = x.feet + y.feet; int i = x.inch + y.inch; if (i >= 12) { f++; i = i - 12; }
return new Size(f, i); //Instance }
public static Size operator +(Size x, Size y) { int f = x.feet + y.feet; int i = x.inch + y.inch;
if (i >= 12) { f++; i = i - 12; }
return new Size(f, i); //Instance } public void ShowSize() { Console.WriteLine("Size is {0} feet and {1} inch", feet, inch); }
}
class Program { static void Main(string[] args) { Size s1=new Size(5,8); //Object Size s2 = new Size(8, 9); //Size s3 = Size.Add(s1, s2); Size s3 = s1 + s2; s3.ShowSize(); } }
19.02.2010
Inheritance
A system that provides re-usability of code.
C# allows only single inheritance.
In .NET all classes are inherited from System.Object class by default.
Use : operator to inherit a class into other class.
Classes can be at three levels Parent classes Base class Child class
class X{}
class Y : X{}
If Y is child class of X, X is base class of Y and Object is the Parent class.
Use this keyword to refer object of current class and base keyword to refer object of base class.
Example
class Num2{ int a, b; public Num2(int a, int b) { this.a = a; this.b = b; } public int p2() { return a * b; }}
class Num3 : Num2{ int c;
public Num3(int x, int y, int z) : base(x,y) { c = z; } public int p3() { return p2() * c; }}
class InhTest{ public static void Main() { Num3 x = new Num3(4, 5, 6); System.Console.WriteLine(x.p3()); }}
Note:
In inheritance, a parent can hold reference to its childs can invoke all those methods of child, whose signature is provided from parent to the child.
Method Hiding
- A method in parent class re-written in child class with same signature and different body contents, is called as method hiding
- It is implicit- Use new keyword to define it explicity- Such methods do not participate in Runtime
Polymorphism
class A { public void Show() { Console.WriteLine("Calling from A"); } } class B : A {
public void Show() { Console.WriteLine("Calling from B"); } } class C : B { public void Show() { Console.WriteLine("Calling from C"); } public void Hi() { Console.WriteLine("Hi to all"); } }
class HideTest { public static void Main() { A p; p = new A(); p.Show(); p = new B(); p.Show(); p = new C(); p.Show(); } }
Method Overriding
- An abstract or virtual method of a class, re-written in child class with same signature and different body contents is called as method overriding
- Use override keyword to override a method- Such method participate in Runtime
Polymorphism or Dynamic Method Dispatch (DMD)
class A
{ virtual public void Show() { Console.WriteLine("Calling from A"); } } class B : A { override public void Show() { Console.WriteLine("Calling from B"); } } class C : B { override public void Show() { Console.WriteLine("Calling from C"); } public void Hi() { Console.WriteLine("Hi to all"); } }
class HideTest { public static void Main() { A p; p = new A(); p.Show(); p = new B(); p.Show(); p = new C(); p.Show(); } }Runtime Polymorphism
- When a reference of parent class is allowed to access methods of child whose signature is provided from parent to the child is called as runtime polymorphism.
- To achieve it, the methods in parent class must be abstract or virtual.
- Use override keyword to override a method
22.02.2010
Virtual methods
A method of a class having some body contents and allowed to be overridden in child class. Use virtual keyword to declare such methods as virtual.
Such methods can be hidden or overridden in child class. To override a method in child class use override keyword. By default is hiding. Use new keyword to explicitly defining the hiding.
Abstract MethodA method of a class having the signature but no body contents. It can be declared inside a class or interface. If used inside a class the use abstract keyword and no keyword is required for interfaces.
Such methods are made for overriding purpose only. Such method can be overridden in child class without using override keyword.
Abstract class
A class that can never be instantiated. They are used for inheritance purpose only.An abstract class may or may not have any abstract method.
But if a class contains any abstract method, it must be declared as abstract.
abstract class Common{ public string Name { get; set; } public string Email { get; set; } public Common(string name, string email) { Name = name; Email = email; }}
class Student : Common
{ public int RollNo { set; get; } public string Course { get; set; } public Student(int rno, string name, string email, string course) :base(name,email) { RollNo = rno; Course = course; }}
class AKGEC{ public static void Main() { Student s = new Student(123, "Amit Verma", "[email protected]", "MCA"); System.Console.WriteLine("Name is {0} Course is {1}", s.Name, s.Course); }}
Sealed Methods
- A method that can never be overridden- Use sealed keyword with such methods- sealed can never be used with new-
class First { virtual public void Show() { Console.WriteLine("I am First"); } } class Second : First { sealed public override void Show() { Console.WriteLine("I am second"); } }
Partial class
- A class that can be spreaded in multiple files and can be combined at the time of compilation
//part1.cs
partial class A{
…}
//part2.cs
partial class A{
…}
CSC part1.cs part2.cs
Defining the output file name
- Use /out:filename with CSC
CSC /out:test.exe part1.cs part2.cs
24.02.2010Exception HandlingString HandlingCollectionsGenericsBoxing and Unboxing
Exception Handling
- A system to pass a message from the place some runtime error has occurred to the place some method get called
- Each exception is class inherited from Exception class- Each exception class provides Message property to given a runtime error- C# provides four keyword for exception handling
o tryo catcho throwo finally
- try-catch is a block of statement to execute some commands and trap the runtime error and report it
- finally is again a block used with try to always execute some statements irrespective of exception
- A try can have many catch statement but only on finally block that must be last block in try
try{
Statements;}catch(classname ref){
//decision}…finally{
//statement always executed}
Example
Write a program to input two integers and print division of that numbers.using System;class Program { static void Main(string[] args) { Console.Write("Enter two numbers : "); try { int x = Convert.ToInt32(Console.ReadLine()); int y = Convert.ToInt32(Console.ReadLine()); int z = x / y; Console.WriteLine("division is {0}", z); } catch (FormatException ex) { //Console.WriteLine(ex.Message); Console.WriteLine("Sorry! Only Numbers are allowed"); } catch (DivideByZeroException ex) { Console.WriteLine("Sorry! Denominator cannot be zero"); } catch (Exception ex) { Console.WriteLine("Error found. Call on 8989898989"); //Console.WriteLine(ex); }
} }
Creating Custom Exceptions
- Each exception is a class child of Exception classo Create a class to send as message inheriting from Exception classo Override the Message property
- Create another where we have to throw this exception o Use throw keyword to throw the exception
- Use try-catch to catch the exception while using it
Test Case
Create a class a LowBalanceException to send a message as "Insufficient Funds… Check you account" class LowBalanceException:Exception { public override string Message { get { return "Insufficient Funds… Check you account"; } } }
Create a class as Customer having a method as Withdraw() and throw this exception is amount withdrawn is more than balance.
class Customer { string name, balance; public Customer(string name, int opamt) { this.name=name; this.balance = opamt; } public void Deposit(int amount) { balance += amount; } public void Withdraw(int amount) { if (amount > balance) throw new LowBalanceException(); balance -= amount; } public void ShowBalance() { Console.WriteLine("Balance of {0} is {1}", name, balance); } }
Create a class for a bank e.g. HDFC to use the customer class for their customerclass HDFC { public static void Main() { Customer c1 = new Customer("Rakesh", 5000); c1.Deposit(4000); c1.ShowBalance(); try { c1.Withdraw(30000); c1.ShowBalance(); } catch (LowBalanceException ex) { Console.WriteLine(ex.Message); }
} }
String Handling
Strings in C# are managed as- Immutable or fixed size- Mutable or expandable
System.String class or (string datatype) manage immutable strings and System.Text.StringBuilder class manages mutable strings.
String class provides basic operations on strings
string ToUpper()string ToLower()int Lengthint IndexOf(string searchstring)
returns -1 if not foundstring [] Split(params char ch[])void Replate(char toreplace, char byreplace)bool StartsWith(string s)bool EndsWith(string s)string Trim()
using System;using System.Text;class StringTest { public static void Main() { string s = "Amit Kumar"; Console.WriteLine(s.Length); Console.WriteLine(s.ToUpper()); Console.WriteLine(s.ToLower()); int p = s.IndexOf("Kumar"); if (p == -1) Console.WriteLine("Not found"); else Console.WriteLine("found at " + p);
string str = "amit,vikas;rohit;rahul,keshav"; string[] ar = str.Split(';',','); foreach (string x in ar) Console.WriteLine(x); string str1=str.Replace(',', ';'); Console.WriteLine(str1);
StringBuilder sb = new StringBuilder(); sb.Append("Amit"); sb.Append(" Kumar"); string abc = sb.ToString(); Console.WriteLine(abc);
} }
03.03.2010GUI ProgrammingBuilding Windows Applications using .NET Framework
- Every GUI Application must have at least one Windows Form- A class inherited from System.Windows.Forms.Form class is called as
Windows form- It works like a container for other controls- Create a new project as Windows Forms Application
Windows used in GUI Development in Visual Studio IDE1. Form Window2. Property Window3. Code Window4. Solution Explorer5. Toolbox Window6. Command Window7. Immediate Windows
Every component and container has a fixed set of - Properties- Methods- Events
Properties are used to hold the values. Can be of two types1. Design Time Property (Property Window)2. Runtime Property (Code Window)
a. Used with some event
Events are the moments generated using a keyboard, mouse or some system activity. We can use the events from Property Window.
- KeyUp- KeyDown- KeyPress- MouseOver- MouseOut- Click- DoubleClick- MouseUp- MouseDown- Load- UnLoad- Tick
Common Properties on Controls
- Nameo Every control must have a unique nameo Use Hungarian notation to manage the control names to show its purpose
and type, given by Charles Simony of Hungary.
o Use three character prefix in name to define the type of control along with purpose of control
TextBox txt Form frm Button cmd or btn Checkbox chk Etc.
- BackColor- ForeColor- Font- Size- Dock- Text
Using is operator
- Use to compare the object with the class name
private void MakeNumber(object sender, EventArgs e) { if (sender is Button) { this.Text = "It is a button"; Button b=(Button)sender; //casting textBox1.Text += b.Text; } else if (sender is TextBox) { this.Text = "It is text box"; } }
Using sender arguments- defines the current control on which an event has occurred
Using EventArgs argument - Used to provided some information and take the instructions
private void frmFirst_MouseMove(object sender, MouseEventArgs e) { this.Text = e.X + "," + e.Y; }
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { int num = (int)e.KeyChar; //this.Text = num.ToString(); if(! (num == 8 || num == 46 || (num >= 48 && num <= 57))) { e.Handled = true; } }
Enumerators
- A system to define the names to the values- It is a user defined data type- Use enum keyword to define the enumerators- Default data type is int- Values starts with 0 and incremented by 1
enum <enumname>:<datatype>{name=value…}
Example
enum Security:byte { Low, Medium, High }
private void button10_Click(object sender, EventArgs e) { Security s = Security.High; int x = (int)s; this.Text = x.ToString(); }
Real Example
When a user closes a form, ask the user to close the form or not. Show a dialog to get the response. It answer is no then stop the closing of the form.
Hint: Use MessageBox.Show() method to the dialog. It returns a value as enumerator called DialogResult. Use FormClosing event of the form.
private void frmFirst_FormClosing(object sender, FormClosingEventArgs e) { DialogResult ans = MessageBox.Show("Quit the application", "Quit", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (ans == DialogResult.No) e.Cancel = true; }
05.03.2010
General controls used for User Interaction
Label control- To show some text
o Texto TabIndex
- Use & to make the hot key
TextBox control- To create a single text field, password field and multiline text field
o Texto PasswordCharo Multiline=true/falseo Scrollbarso MaxLengtho ReadOnlyo TabIndexo Cut()o Copy()o Paste()
Button control- To create the push buttons
o Texto TabIndexo Imageo TextAligno ImageAlign
- Use & to make the hotkey
Test ExampleWrite a GUI Program to input a number and show Square root and Cube Root of that number in other text box.
ToolTip control- To provide tooltips on different control
o IsBallon=true/false
LinkLabel control- To show a hyper link- We can activate a website or some other program using it
ExampleSystem.Diagnostics.Process.Start("http://www.yahoo.com");
Checkbox control
- To select none or all itemso Texto Imageo ImageAligno TextAligno Checked
Exampleprivate void chkAgree_CheckedChanged(object sender, EventArgs e) { if (chkAgree.Checked) cmdNext.Enabled = true; else cmdNext.Enabled = false; }
RadioButton control- To select only one item from group
o Texto Imageo ImageAligno TextAligno Checked
- To group the controls use Panel or GroupBox control from Containers section
PictureBox control- To show an image
o Imageo SizeModeo BorderStyle
Working with Dialogs
- A window that do not have minimize and maximize buttons- To create general dialogs use MessageBox.Show() method- Dialogs can be of two types
o Simple Message Dialogso Responsive Dialogs
Simple Dialogs
MessageBox.Show(string message, string title,MessageBoxButtons.OK, MessageBoxIcon icon)
ExampleMessageBox.Show("Data has been saved", "Save",MessageBoxButtons.OK,MessageBoxIcon.Information);
Response Dialogs
- To get a response from a dialog as DialogResult
Dialog Controls- Special controls provided under Dialogs sections
o FontDialogo ColorDialogo OpenFileDialogo SaveFileDialogo FolderBrowserDialog
- All such controls provide ShowDialog() method
OpenFileDialog control or SaveFileDialog Control- Gives a file name to open
o FileNameo Filter
Loading Image dynamically into a picture box- Get the image from the open dialog box and use Image class with FromFile()
method to load the image
pictureBox1.Image=Image.FromFile(openFileDialog1.FileName);
08.03.2010
Color Dialog
- To select a coloro Coloro FullOpen=true/false
private void button1_Click(object sender, EventArgs e) { colorDialog1.FullOpen = true; colorDialog1.ShowDialog(); textBox1.ForeColor = colorDialog1.Color; }
Font Dialog- Gives a fonts and color
o Coloro Fonto ShowColor=true/false
private void button2_Click(object sender, EventArgs e) { fontDialog1.ShowColor = true; fontDialog1.ShowDialog(); textBox1.ForeColor = fontDialog1.Color; textBox1.Font = fontDialog1.Font; }
Creating Shortcut key
private void Form1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.F4 && e.Control==true) //Ctrl+F4 { fontDialog1.ShowColor = true; fontDialog1.ShowDialog(); textBox1.ForeColor = fontDialog1.Color; textBox1.Font = fontDialog1.Font; } }
Note: Set KeyPreview property as true to invoke the shortcuts on form
RichTextBox control
- Allows to work with selected portion of texto Texto Fonto ForeColoro SelectionColoro SelectionFonto SelectedTexto Cut()o Copy()o Paste()o LoadFile()o SaveFile()o SelectAll()
private void button4_Click(object sender, EventArgs e) { colorDialog1.FullOpen = true; colorDialog1.ShowDialog(); richTextBox1.SelectionColor = colorDialog1.Color; }
private void button3_Click(object sender, EventArgs e) { fontDialog1.ShowColor = true; fontDialog1.ShowDialog(); richTextBox1.SelectionColor = fontDialog1.Color; richTextBox1.SelectionFont = fontDialog1.Font; }private void button6_Click(object sender, EventArgs e) { saveFileDialog1.Filter = "Text Files|*.txt;*.cs;*.java;*.c;*.cpp"; saveFileDialog1.ShowDialog(); richTextBox1.SaveFile(saveFileDialog1.FileName,RichTextBoxStreamType.PlainText); }
private void button5_Click(object sender, EventArgs e) { openFileDialog1.Filter = "Text Files|*.txt;*.cs;*.java;*.c;*.cpp"; openFileDialog1.ShowDialog(); richTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
}
Folder Browser Dialog
- To select a folder or create a new foldero SelectedPatho RootDirectory
private void button7_Click(object sender, EventArgs e) { folderBrowserDialog1.ShowDialog(); this.Text = folderBrowserDialog1.SelectedPath; }
Adding new forms
Project Add Windows Form…
Making a form as startup form
Select Solution Explorer Program.cs Application.Run()Create object of the startup formConnecting Forms
- Create a button or Menu then create an object of the form to be invoked and use Show() method to show the form
private void button1_Click(object sender, EventArgs e) { Form1 f = new Form1(); f.Show(); }
Creating Menus
Menus can be of two types1. Menu Strip2. Context Menu Strip
They are provided under Menus and Toolbars Section
To apply a context menu use ContextMenuStrip property of the control.
10.03.2010
Combo Box control
- Provides data input as well as data selection- Provides single selection only- It has a collection called as Items
o A collection is a dynamic set of objectso Every collection provides Add() method and Count property
o We can also use methods like Remove(), RemoveAt()- Properties
o Texto SelectedItemo SelectedIndexo DropDownStyleo Sorted
ListBox control- To select one or more items- It has a collection called as Items
o A collection is a dynamic set of objectso Every collection provides Add() method and Count propertyo We can also use methods like Remove(), RemoveAt()
- Propertieso Texto SelectedItemo SelectedIndexo DropDownStyleo Sortedo SelectionMode
- Methodso bool GetSelected(int index)
private void Form1_Load(object sender, EventArgs e) { for (int i = 1; i <= 31; i++) comboBox2.Items.Add(i); comboBox2.SelectedIndex = 0;
for (int i = 1; i <= 31; i++) listBox1.Items.Add(i); }
private void button2_Click(object sender, EventArgs e) { for (int i = 0; i < listBox1.Items.Count; i++) { if (listBox1.GetSelected(i)) { listBox2.Items.Add(listBox1.Items[i]); }
} for (int i = listBox1.Items.Count - 1; i >= 0; i--) { if (listBox1.GetSelected(i)) { listBox1.Items.RemoveAt(i); }
} }
Date Time Picker control
- Allows selection of date and timeo Formato CustomFormat
Use codes like d, D, m, M, y, h, s Example
dd-MMM-yyyyo ShowUpDowno ShowCheckBoxo Checkedo Value
Example private void button3_Click(object sender, EventArgs e) { MessageBox.Show(dateTimePicker1.Value.ToString("dd-MMM-yyyy")); }
Timer Control
- to do certain operation after given interval of time- It is provided under Components section
o Interval Time in milliseconds
o Enabled=true/false- Event
o Tick
Assignment
Create a text box and two buttons (Start, Stop)
When start button is clicked will start numbering from 1When Stop button is clicked it will stop the numbering and when change the Start button text will change to ReStart. When ReStart button is pressed the process will continue again from 1
Creating toolbars
- Use ToolStrip control from Menus and Toolbars- Define the kind of button and its Image and ToolTipText
Creating Status Bar
- Use StatusStrip control- It again has Items collection- To define the custom size to section set AutoSize property False-
private void timer1_Tick(object sender, EventArgs e) { lblTimer.Text = DateTime.Now.ToLongTimeString(); statusStrip1.Items[1].Text = DateTime.Now.ToLongTimeString(); }
private void Form1_MouseMove(object sender, MouseEventArgs e) { string location = e.X + "," + e.Y; statusStrip1.Items[0].Text = location; }
Kind of Application Models
Applications are build using two models1. SDI (Single Document Interface)2. MDI (Multiple Document Interface)
12.03.2010Revision PointsPropertiesIndexerDelegatesMutable Strings (System.Text.StringBuilder)Operator Overloading
public void Save(object send, EventArgs e) { MessageBox.Show("Data saved"); } private void DelegateTest_Load(object sender, EventArgs e) { button1.Click += new EventHandler(Save); }
Dynamic generation of controls and data collection
public partial class Form2 : Form { int start, gap; int i; public Form2() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) { TextBox t = new TextBox(); t.Name = "txtNum" + i++; t.Size = new Size(100, 20); t.Location = new Point(50, start); Controls.Add(t); start = start + gap; }
private void Form2_Load(object sender, EventArgs e) { start = 100; gap = 30;
}
private void button2_Click(object sender, EventArgs e) { foreach (object c in Controls) { if (c is TextBox) { TextBox t = (TextBox)c; MessageBox.Show(t.Text); } }
} }
15.03.2010
Creating MDI Applications
- An application that contains the main form and child forms- To make a form as MDI From set its IsMdiContainer property as true- To make a form as child form set its MdiParent property- To set the layout of child forms use LayoutMdi() method of the parent form- Use enumerator MdiLayout to select a layout like Cascade, Tile Horizontal
etc.- To get reference of the current form use ActiveMdiChild property of the
parent form- To get reference of specific control from the current child form use Controls
collection
Test Case
Write an MDI application to create a Smart Pad that allows working on multiple text files
Note: Use MdiParent component from Project Mdi Parent Form
Adding other components into Toolbox
- Add new components from ToolBox itself- Example
o Add the FileListBox, DriveListBox and DirListBox controls
FileListBox Pattern FileName Path
DirListBox Path
DriveListBox Drive
Creating Web Browsers
- Use WebBrowser control- Use Navigate() method to open a website or webpage-
19.03.2010
Database Programming in .NET (ADO.NET)
- ADO.NET is ActiveX Data Objects for .NET- A collection of classes under .NET framework for database management
Classes are categorized in two categories
1. Generalized classeda. For any database
2. Specialized classesa. For specific database
All classes are mainly categorized in five namespaces
System.DataProvides common classes for all database e.g. DataTable, DataSet, DataView etc.
System.Data.OdbcFor any database using Data Source Name (DSN)
System.Data.OleDbFor any database without using Data Source Name
System.Data.OracleClientOnly for Oracle
System.Data.SqlClientOnly for MS Sql Server
Main databases used with .NET1. MS Access2. Oracle3. SQL Server
Requirements for database programming
1. Database2. Technology3. Information about how to reach with database
a. Data Source=filename or ip address or server nameb. User Id or uid=login namec. Password or pwd=passwordd. Database or Initial Catalog=datbasenamee. DSN=dsn namef. Integrated Security=true/falseg. Provider=driver name
4. Knowledge of SQL Statements
Database Programming with MS Access
Step 1
Create a blank database file. E.g b02db.mdb
Step 2
Create the required tables.
For exampleEmployee (empid-N-PK, name- T, email-T)
Step 3
Create a data source name (DSN) from control panel Administrative tools ODBC System DSN Add… - Microsoft Access Driver (*.mdb) Select the database and define the DSN Name e.g. b02access
Step 4
Create a data entry form using C#
Step 5
Import the namespace System.Data.Odbc
Step 6
Create an object of OdbcConnection class. Specify the database information with ConnectionString property. Open the connection.
OdbcConnection cn = new OdbcConnection();cn.ConnectionString = "Dsn=b02access";cn.Open();
Step 7
Create the SQL statement be executed and test it
string sql = "INSERT INTO employee VALUES(" + txtEmpId.Text + ",'" + txtName.Text + "','" + txtEmail.Text + "')";
Step 8
Create an object of OdbcCommand class. Define the Connection and CommandText properties.
OdbcCommand cmd = new OdbcCommand(); cmd.CommandText = sql; cmd.Connection = cn;
Step 9
Execute the command based on its typeCommands can be of two types
1. Select typea. ExecuteReader() – for recordsb. ExecuteScaler() – for single value
2. Non-Select Typea. ExecuteNonQuery()
Another Method
private void button1_Click(object sender, EventArgs e) { OdbcConnection cn = new OdbcConnection("Dsn=b02access"); cn.Open();
string sql = "INSERT INTO employee VALUES(" + txtEmpId.Text + ",'" + txtName.Text + "','" + txtEmail.Text + "')"; OdbcCommand cmd = new OdbcCommand(sql,cn); cmd.ExecuteNonQuery(); cn.Close();
MessageBox.Show("Record Saved", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information); ClearAll(); }
private void ClearAll() { txtEmpId.Clear(); txtName.Clear(); txtEmail.Clear(); txtEmpId.Focus();
}
Creating Formatted SQL Statements
- Use Format() method of String class to format the statements and use them
string sql = string.Format("INSERT INTO employee VALUES({0},'{1}','{2}')", txtEmpId.Text, txtName.Text, txtEmail.Text);
Using Place Holders in SQL Statements
- Use ? in place of data and provide the data later on using Parameters collection of OdbcCommand object.
- Use AddWithValue() method to pass the data with fieldname and value
ExampleOdbcConnection cn = new OdbcConnection("Dsn=b02access"); cn.Open();
string sql = "INSERT INTO employee VALUES(?,?,?)";
OdbcCommand cmd = new OdbcCommand(sql, cn); cmd.Parameters.AddWithValue("empid", txtEmpId.Text); cmd.Parameters.AddWithValue("name", txtName.Text); cmd.Parameters.AddWithValue("email", txtEmail.Text);
cmd.ExecuteNonQuery(); cn.Close();
MessageBox.Show("Record Saved", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
Using MS Access with OleDB Technology
- Create the connection string usingo Tools Connect to Database…
- Select the database file and type as MS Access file
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\Batches2010\02\b02db.mdb
- Use Namespace as System.Data.OleDbo OleDbConnectiono OleDbCommand
OleDbConnection cn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\Batches2010\02\b02db.mdb"); cn.Open();
string sql = "INSERT INTO employee VALUES(?,?,?)";
OleDbCommand cmd = new OleDbCommand(sql, cn); cmd.Parameters.AddWithValue("empid", txtEmpId.Text); cmd.Parameters.AddWithValue("name", txtName.Text); cmd.Parameters.AddWithValue("email", txtEmail.Text);
cmd.ExecuteNonQuery(); cn.Close();
MessageBox.Show("Record Saved", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
Making dynamic path for the MS Access file
- Place the data file in same folder having the executable file- Use Application.StartupPath property to get the path of that folder
OleDbConnection cn = new OleDbConnection(); cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + @"\b02db.mdb"; cn.Open();
Using SQL Server 2005
- Start the SQL Server software- Select Windows Authentication or SQL Server Authentication- Create a Database from Databases section
o Create your tables- Create a login and password to allows access of this database
o Select securityo At the General Page
Create new login, define password and select the default databaseo Select User Mapping Page
Select your database and give rights as db_owner then Ok
Information required to connect with database
Data Source=PERSONALUser Id=b02Password=1234Database=batch02
Name Space: System.Data.SqlClientClasses : SqlConnection, SqlCommand
While passing the parameters use @ with the parameters names.
Creating and using Stored Procedures in SQL Statements
- Create a stored procedure for database operations from Databases database name Programmability Stored Procedures
CREATE PROCEDURE SaveEmployee@empid int,@name varchar(50),@email varchar(50)
ASBEGIN
INSERT INTO employee VALUES(@empid,@name,@email);ENDGOSelect the procedure and press F5
Using the procedure in programming
private void button1_Click(object sender, EventArgs e) { try { SqlConnection cn = new SqlConnection(); cn.ConnectionString = "Data Source=Personal;Initial Catalog=batch02;User ID=b02;Password=1234"; cn.Open();
SqlCommand cmd = new SqlCommand(); cmd.Connection = cn; cmd.CommandText = "SaveEmployee"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@empid", txtEmpId.Text); cmd.Parameters.AddWithValue("@name", txtName.Text); cmd.Parameters.AddWithValue("@email", txtEmail.Text);
cmd.ExecuteNonQuery(); cn.Close();
MessageBox.Show("Record Saved"); } catch (SqlException ex) { MessageBox.Show("Sorry! Employee Id Already Exist"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); }
}
Saving Images to Database
- Select a image into a PictureBox- Save that image from PictureBox to another class in memory called as
MemoryStream class of System.IO namespace- Get data in byte array format from memory stream and save that data to the
disc MemoryStream ms = new MemoryStream(); picPhoto.Image.Save(ms, picPhoto.Image.RawFormat); byte[] imgdata = ms.GetBuffer();
Example
Student (rollno-N, name-VC, photo-Image)
Create procedure and execute it
CREATE PROCEDURE SaveStudent@rollno int,@name varchar(50),@photo Image
ASBEGIN
INSERT INTO student VALUES(@rollno,@name,@photo);
ENDGO
Create a form having a photo
To pass the Image type parameter to the SqlCommand use Add() rather than AddWithValue()
Add() method required as SqlParameter class type object
26.03.2010
Using Oracle as Database
Get information
1. Data Source=<server name> e.g. Ora2. User Id=<login> e.g. scott3. Password=<password> e.g. tiger
NoteUse : operator in place of @ while using parameters.
Namespace: System.Data.OracleClient
To use this namespace give reference of System.Data.OracleClient.dll
ExampleOracleConnection cn = new OracleConnection();cn.ConnectionString = "Data Source=ora;User Id=scott;Password=tiger";cn.Open();
string sql = "INSERT INTO employee values(:empid,:name,:email)";
OracleCommand cmd = new OracleCommand(sql,cn);cmd.Parameters.AddWithValue(":empid", txtEmpId.Text);cmd.Parameters.AddWithValue(":name", txtName.Text);cmd.Parameters.AddWithValue(":email", txtEmail.Text);cmd.ExecuteNonQuery();cn.Close();MessageBox.Show("Record Saved");
Reading data from database- Data can be read using two methods
o Connected Modeo Disconnected Connected Mode
In connected mode, can be read until the connection is open and front-end is connected with back-end. Only one record can be read at one time. Current value inside the record is available.
In disconnected mode, data can be read from database and stored inside a container on the client like DataTable, DataSet etc. Data is available at the client side even after closing the connection.
Reading data in connected mode
- Create a SELECT command- It can be of two types
o Returning a single values or scalar valueo Returning a set of records
- Use methods depending on type of SELECT commando object ExecuteScaler()o xxxDataReader ExecuteReader()
- xxx can be replaced with Sql, Oracle, Odbc and OleDb
Methods of DataReaders
1. bool Read()a. returns true if record is available to read and false if no more records
Indexer to read data
object objectname[int columnindex]object objectname[string columnname]
Propertiesbool HasRows
Exampleusing System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Data.OracleClient;
namespace Batch02_2602{
public partial class frmReadData : Form { OracleDataReader dr; OracleConnection cn; public frmReadData() { InitializeComponent(); }
private void cmdNext_Click(object sender, EventArgs e) { if (dr.Read()) { txtEmpId.Text = dr[0].ToString(); txtName.Text = dr[1].ToString(); txtSalary.Text = dr[2].ToString(); } }
private void frmReadData_Load(object sender, EventArgs e) { cn = new OracleConnection(); cn.ConnectionString = "Data Source=ora;User Id=scott;Password=tiger"; cn.Open();
string sql = "Select count(*) from emp"; OracleCommand cmd = new OracleCommand(sql, cn); int count =Convert.ToInt32(cmd.ExecuteScalar()); lblCount.Text = "Total records : " + count;
sql = "select empno, ename, sal from emp"; cmd.CommandText = sql; dr = cmd.ExecuteReader(); if (dr.Read()) { txtEmpId.Text = dr[0].ToString(); txtName.Text = dr[1].ToString(); txtSalary.Text = dr[2].ToString(); }
}
private void frmReadData_FormClosing(object sender, FormClosingEventArgs e) { cn.Close(); }
}}
Searching a record
private void button1_Click(object sender, EventArgs e) { string sql = "select empno, ename, sal from emp where empno=:empno"; OracleCommand cmd = new OracleCommand(sql, cn); cmd.Parameters.AddWithValue(":empno", txtEmpId.Text); dr = cmd.ExecuteReader(); if (dr.Read()) { txtName.Text = dr[1].ToString(); txtSalary.Text = dr[2].ToString(); } else { MessageBox.Show("Invalid Employee Number"); } }
Reading images from database
Read the data from database and convert into byte array.Create a MemoryStream type object and pass the byte array to that stream.Create an image using the stream data with FromStream() method of Image class
byte []data=(byte []) dr["photo"];MemoryStream ms=new MemoryStream(data);picPhoto.Image=Image.FromStream(ms);ms.close();
Creating Connection String without server name and security informationcn.ConnectionString = "Data Source=.;Database=batch02;Integrated Security=true";
29.03.2010
Reading data in disconnected mode
- Data can be held on the client side even after closing the connection- To store the data in memory at the client side use containers like
DataTable To hold result of single query
DataSet To hold results of one or more queries
- Use data adapter type classes to get data and fill that data into the containerso xxxDataAdapter
sting sql=”Select * from tablename”;SqlDataAdapter da=new SqlDataAdapter(sql,cn);DataTable dt=new DataTable();da.Fill(dt);cn.close();
- DataTable is a collection of Rows and Columns- Using data binding we can see the whole table data on screen in tabular format
using DataGridView control- Use DataSource property to define the source of data as DataTable or
DataView
DataView class- Used to re-filter or re-sort data already in memory inside a DataTable
DataView dv=new DataView(dt);
- Use RowFilter and Sort properties to define the condition and the field name to sort the datao RowFilter=”condition”o Sort=”fieldname [DESC]”
Test Application
Read all records from emp table of Oracle with fields empno, name and salary in Grid Format.
- Create a form and place a DataGridView control on the form. On load event read all data into a DataTable the give it to DataGridView using DataSource property
- All data managed by DataTable is in XML format- Use method of DataSet class to read and write XML files- A data set is a collection of data tables (DataTables)- DataSet provides methods
o WriteXml()
o ReadXml()Test Case
Create a table Course having fields1. CCode – PK – Auto Generated2. CourseName
Create another table Branches having fields1. BCode-PK – Auto Generated2. CCode-FK3. BranchName
Back-End : SQL Server
31.03.2010
Data Binding in Combo Box
- To link data to a combo box in such a way, one data get displayed and other data is used for storing in database
- Propertieso DataSource=<data table or data view>o DisplayMember=<field name to display data>o ValueMember=<fieldname to save data in database>o SelectedValue
To get the selected values from value member
Placing the connection string outside the forms
- Use Application Configuration File (App.Config) to hold the application related setting
- It is an XML file used for configuration settings- If not found in project, add it
o Project Add New Item… Application Configuration Fileo Now add the connection string information
<?xml version="1.0" encoding="utf-8" ?><configuration> <appSettings> <add key="cstr" value="Data Source=.;Integrated Security=true;Database=batch02"/> </appSettings></configuration>
Reading connection information from App.Config inside a form
- Import the System.Configuration namespace- Use ConfigurationSettings class with AppSettings property
SqlConnection cn = new SqlConnection();cn.ConnectionString = ConfigurationSettings.AppSettings["cstr"];cn.Open();
Changing display of a field name
- Use As clause in SQL Statemetns
string sql = "Select CCODE AS [Course Code], CourseName as [Course Name] from course";
Creating Master/Detail form
- Allows to select a value rather than typing
Creating Setup of a Project
- In Main Project change Debug mode to Release mode- Provide the software information and Icon from Project Properties
Assembly Info Icon
- Add a new project as Setup Project from File Add… New Project Setup and Deployment Setup Project
- Select Setup Project from Solution Explorero Select its properties
Add Project Output Ok- Create the shortcut of primary output from Application Folder and drop into
Program Menu and Desktop folders- Add a file as Icon file (*.ico) in application folder- Rename the Shorcuts on Menu and Desktop and assign the Icon- Build the Project