0 ratings0% found this document useful (0 votes) 345 views100 pagesSunbeam .Net Framework Notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
PRASANNA,
@ SsunBeam
Prasanna
Wadekar SI702484O7 = gr
ve
LEARNING INMTIATIVE,
Institute of Information Technology
Waniwnancics
Session
+ Introduction to .Net Framework
Objectives of .NET Framework 4.5
The .NET Framework is a technology that supports building and running the next generation of applications and XML Web
services.
‘The .NET Framework is designed to fulfil the following objectives:
To provide a consistent object-oriented programming environment whether object code is stored and executed
locally, executed locally but Internet-cistributed, or executed remotely.
To provide a code-execution environment that-minimizes software deployment and versioning conflicts
To provide 8 code-execution environment that promotes safe execution of code, including cade created by an
Unknown or semi-trusted third party.
To provide a code-execution environment that eliminates the performance problems of scripted or interpreted
environments.
To make the developer experience consistent across widely varying types of applications, such as Windows-based
applications and Web-based applications,
To build all communication on industry standards to ensure
with any other code.
i code based on the NET Framework can integrate
.NET Framework Context
‘SunBeam Institute of Information Technology, Pune, Karad Paget@& sunBeam Fz
— Institute of Information Technology -
sd)
LEARNING INITIATIVE
Baume
Dot Net Framework Components
Sipnis rensiy.
(08)
Development in NET Framework 4.5
‘The NET Framework is a development platform for building apps for Windows, Windows Phone, Windows Server, and
Microsoft Azure.
Visual Studio is an Integrated Development Environment.
Application Life Cycle Management (ALM) can be managed using Visual Studio NET
Design Develop —Test Debug Deploy
‘SunBeam Institute of Information Technology, Pune, Karad Page 2
RMN
2
|@ CYUNBEAM
Institute of Information Technology
ve
LEARNING INITIATIVE
Rawaeud
Session
+ Visual Studio .NET 2013 as IDE Tool
‘The Design goals are:
Maximize Developer Productivity
Simplify Server based Development
Deliver Powerful Design, Development Tools
RAD (Rapid Application Development Tool) for the next generation internet solutions
Enhanced RAD Support for creating Custom components for Business solutions.
Tools for creating Rich Client Applications
Tools for creating ASP.NET web sites
‘Tools for Creating S-a-a-S modules
‘Tools for connecting remote servers
Tools for Cloud Connectivity
Tools for Data Access
Tools for Creating, Developing, Testing and Deploying Solutions.
Help and Documentation
Multiple .NET Language Support
Visual Studio Solutions and Projects
Visual Studio Solution consist of multiple Projects
Visual Studio Project consist of Source code, Resources,
C# as .NET Programming Language
C++ Heritage
Namespaces, Pointers (in unsafe code),
Unsigned types, etc.
Increased Productivity
Short Learning curve
C#t isa type safe Object Oriented Programming Language
# is case sensitive
Interoperability
C# can talk to COM, DLLs and any of the .NET Framework languages
Structure of first C# program
using System;
// ® “Hello World!” program in C#
public class HelloWorld
{ public static void Main ()
4
Console.WriteLine (“Hello, World”);
SunBeam Institute of Information Technology, Pune, Karac
Page 3@® SUNBEAM ve
= Institute of Information Technology feed QTE
amanuanns
Passing Command Line Arguments
using System;
/* Invoke exe using console */
public class HelloWorld
{
public static void Main (string [] args)
{
Console.WriteLine ("parameter count = {0}, args.Length) ;
Console.WriteLine ("Hello {0}”, args [0]);
Console.ReadLine ();
y
i
Execution of .NET Application
C# code is compiled by CSC.exe (C# compiler) into assembly as Managed code.
Managed code is targeted to Common Language Runtime of .NET Framework
Common Language Runtime converts MSIL cade into Platform dependent executable code (native code) for targeted
‘operating System.
Application is executed by Operating System as Process.
C# Types
AC Program is a collection of types
Structure, Cases, Enumerations, Interfaces, Delegates, Events
Ci provides a set of predefined types
eg. it, byte, char, string, object, et
Custom types can be created.
‘data and code is defined within a type.
No global variables, no global function.
‘Types can be instantiated and used by
Calling methods, setters and getters, etc.
‘Types can be converted from one type to another.
‘Types are organized into namespaces, files, and assemblies.
‘Types are arranged in hierarchy.
a
‘SunBeam Institute of Information Technology, Pune, Karad Page 4G sunBeam
Institute of Information Technology LEARNING INITIATIVE
Gane menus
In .NET Types are of two categories
Value Type
Directly contain data on Stack.
|
I
|
|
Primitives: int num; float speed;
Enumerations: enum State (off, on}
Structures: struct Point {int x, 'y 3}
Reference Types
Contain reference to actual instance on managed Heap.
Root object
String string
Classes class Line: Shape{ }
Interfaces interface IDrawole {..)
Arrays string [] names = new string[10];
Delegates delegate void operation();
Type Conversion
Implicit Conversion
No information loss
Occur automatically
Explicit Conversion
Require a cast
May not succeed
Information (precision) might be lost
Ent x=543454;
7 //implicit conversion
| iong y=
short z=(short)x; //explicit conversion
double d=1. 3454545345;
float £= (float) d; //explicit conversion
long 1= (long) d__// explicit conversion |
——— — —_<<_<_—_———- nh nS
‘SunBeam Institute of Information Technology, Pune, Karad Page SG@ SUNBEAM
Institute of Information Technology LEARRMG RIATIVE
aan rd
Constants and read only variables
7/ This example illustrates the use of constant data and readonly fields.
using System;
using System. Text;
namespace ConstData
{
class MyMathClass
{
public static readonly double PI;
static MyMathClass ()
{ PI = 3.14; }
)
class Program
{
static void Main(string[] args)
t
Console.WriteLine ("*#*** Fun with Const ****#\n") ;
Console.WriteLine ("The value of PI is: {0}", MyMathClass.PI) ;
// Brroz! Can't change a constant!
/] MyMathClass.PT = 3.1444;
LocalConstStringVariable() ;
3
static void LocalConststringVariable()
4
// B® local constant data point
const string fixedStr = "Fixed string Data";
Console.WriteLine(fixedstr) ;
// Bxror!
//fixedStr = "This will not work!";
SunBeam institute of Information Technology, Pune, Karad Page 6Institute of Information Technology
& SUNBEAM
LEARNING INITIATIVE
Gua
Enumerations.
Enumerations are user defined data Type which consist of 2 set of named integer constants.
enum Weekdays { Mon, Tue, Wed, Thu, Fri, Sat}
Each member starts from zera by default and is incremented by 1 for each next member.
Using Enumeration Types
Weekdays day-Weekdays.Mon;
Console.writeLine("(@)", day); //Displays Mon
Structures
Structure is a value type that is typically used to encapsulate small groups of related variables.
[public struct Point
| ( public int x;
| public int y;
Arrays
Declare
int [] marks;
Allocate
int (] marks= new int[9];
Initialize
int [] marks=new int [] (1, 2, 3, 4, 5, 6, 7, 9}:
int [] marks=(1,2,3,4,5,6,7,8,9}7
Access and assign
Marks2[i] = marks {i};
Enumerate
foreach (int i in marks) (Console.WriteLine (i); }
SunBeam Institute of Information Technology, Pune, Karad
Page 7@ sunBeam [39
===" Institute of Information Technology oe
Gawain
Params Keyword
It defines a method that can accept a variable number of arguments.
static void ViewNames (params string [] names)
i
Console.WriteLine ("Names: {0}, (1), (2)”,
names [0], names [1], names [2]);
)
public static void Main (string [] args)
{
ViewNames("Nitin”, “Nilesh”, “Rahul”);
ref and out parameters
void static Swap (ref int nl, ref int n2)
{
int temp snl; ni=n2; n2=temp;
)
void static Calculate (float radius, out float area, out float circum)
4
Area=3.14£ * radius * radius;
Circum=2*3.14£ * radius;
}
public static void Main ()
£
Aint x=10, y=20;
Swap(ref x, ref y);
float area, circum;
calculate (5, out area, out circum);
»
unBeam Institute of Information Technology, Pune, Karad Page 8|
Institute of Information Technology
G SUNBEAM
¥
LEARNING INTTIATIVE
ats
Session 3:
Execution Process in .NET Environment
Sample] —
waa
~ @O
—— 7 -
source [EPH foxemus |
[coe | vice | HE
.NET Assembly
A Logical unit of Deployment on .NET Platform.
Components of Assembly
+ Manifest
+ Metadata
‘Types of Assemblies
Private Assembly (bin folder)
Shared Assembly (GAC)
System.Data.
‘Systern. Drawing. =100)
return 0;
else
return titles [index];
|
|
set{
if (! index <0 || index >=100)
return 0;
else
titles [index] =value;
}
|
}
public static void Main ()
{ Books mybooks=new Books ();
Mybooks [3] ="Mogali in Forest”;
,
—_———
SunBeam Institute of Information Technology, Pune, Karad Page 16SUNBEAM
Institute of Information Technology
LEARNING INTIATIVE
NET FRAMEWORK
Singleton class
public class OfficeBoy
{ private static OfficeBoy _ref = null;
| private int val;
| private OfficeBoy() { _val = 10; }
public int val ( get { return val; }
| t if (_ref == null)
_ref = new OfficeBoy() ;
return _ref;
~ |
set ( val = value; }
)
public static OfficeRoy Getobject ()
i
|
|
|
f |
static void Main(string[] args)
| { OfficeBoy sweeper, waiter;
string s1; float £1;
|
aweeper-Val = 60; |
| Console.WriteLine ("Sweeper Value {0}", sweeper.Val) ; |
Console.WriteLine("Waiter Value : {0}", waiter.Val);
sl = sweeper.Val.ToString() ;
£1
|
(float) sweeper Val; |
sweeper.Val = int.Parse(s1);
sweeper.Val = Convert. ToInt32(s1) ;
= SunBieam institute of Information Technology, Pune, Karad Page 17@ SUNBEAM
Institute of Information Technology LEARNING INITIATIVE
Renae ruius
+ Arrays
Multidimensional Arrays (Rectangular Array)
[ int [ , 1] mtrx = new int (2, 317
| can initialize declaratively
int [ , ] mtrx = new int [2, 3] { (10, 20, 30}, (40, 50, 60} }
‘An Array of Arrays
int [] [ ] mtrxj = new int [2] Ul; _ ]
|
| Jagged Arrays
i
Must be initialize procedurally.
—_—
SunBeam Institute of Information Technology, Pune, Karad Page 18SUNBEAM
Institute of Information Technology
aiwaerains
Nullable Types
LEARNING INITIATIVE
class DatabaseReader
public int? numericValue
public bool? boolValue
public int? GetIntFromDatabase ()
public bool? GetBoolFromDatabase ()
{ return numericValue;
{ return boolvalue;
public static void Main (string{] args)
DatabaseReader dr = new DatabaseReader () ;
// Get int from ‘database’
dr. GetIntFromDatabase () ;
Af (i-HasValue)
Console. Writebine ("Value of ‘i!
Console. WriteLine ("Value of is undefined.
// Get bool from
bool? b = dr.GetBoolFromDatabase () ;
if (b != null)
Console.WriteLine("Value of 'b!
Console.WriteLine ("Value of is undefined.) ;
// 1 the value from GatIntFromDatabase()is null,assign local variable to 100.
int? myData = dr.GetIntFromDatabase() ?? 100; .
Console.WriteLine ("Value of myData: {0}", myData.Value) ;
static void LocalNullableVariables
// Define some local nullable types
int? nullableint
double? nullableDouble
beol? nullableBool
char? nullableChar 5
int?[] arrayOfNullableints
// Define some local nullable types using Nullable.
Nullable nullablernt
Nullable nullableDouble
Nullable nullablezool
Nullable nullableChar =
Nullable[] arrayOfNullabletInts
new int? [10];
new int?[10];
es:
‘Suneam Institute of Information Technology, Pune, Karad@ SUNBEAM a
Institute of Information Technology LEARNING REVIATIEZ
faeries
Session
+ Overloading
Method Overloading
Overloading is the ability to define several methods with the same name, provided each method has a
different signature
public class MathEngine
{
public static double FindSquare (double number) { // logic defined }
public static double FindSquare (int number) { // another logic defined }
}
public static void Main ()
4
double res= MathEngine.FindSquare (12.5) ;
doublé num= MathEngine.FindSquare (12) ;
)
Operator Overloading
Giving additional meaning to existing operators.
‘Technique that enhance power of extensibility
public static Complex Operator + (Complex cl, Complex c2)
{
Complex temp= new Complex ();
temp.real = cl.real+ c2.real;
templ.imag = cl.image + c2.imag;
return temp,
)
public static void Main ()
t
Complex o1= new Complex (2, 3);
new Complex (5, 4);
1+ 02;
Console.WriteLine (03.real +“ “ + 03.imag);
‘SunBeam Institute of information Technology, Pune, Karad Page 20
9
Fe
7
|
|
|
|
|&® SUNBEAM
Institute of Information Technology LEEANGRTATIE
Nati waaureins
operator overloading restrictions
Following operetors cannot be overloaded,
Conditional logical 8&8, |]
Array indexing operator []
Cast Operators ()
Assignment operators +=,
=n i>, NeW, I5, sizeof, typeof
‘The comparison operator, if overloaded, must be overloaded in pairs.
== is overloaded then != must also be overloaded
‘SunBeam Institute of Information Technology, Pune, Karad Page 21,
ge 20Institute of Information Technology
G SUNBEAM
|
|
C # Reusability
Inheritance
Provides code reusability and extensibility.
Inheritance is a property of class hierarchy whereby each derived class inherits attributes and methods of its base class.
Every Manager is Employee.
Every Wage Employee is Employee.
Glass Employee
{public double Calculatesalary ()
{return basic_sal + hrat da ;}
}
class Manager: Employee
{
public double CalculateIncentives ()
t
//code to calculate incentives
Return incentives;
)
| | static void Main ()
oo ee a one tagse I
double Inc=mgr. CalculateIncentives ();
double sal=mgr. CalculateSalary ();
SS
‘SunBeam Institute of Information Technology, Pune, Karad Page 22® SUNBEAM
Institute of Information Technology LEARNING INITIATIVE
i
Constructors in Inheritance
class Employee
{ public Employee ()
{Console.WriteLine ("in Default constructor”) j}
ass public Employee (int eid,
| {Console.WriteLine (“in Parameterized constructor”) ;}
,
class Manager: Employee
\«
| public Manager (): base (QQ (.---}
public Manager (int id): base (id)..) (o+-)
| )
‘SunBeam Institute of Information Technology, Pune, Karat Page 23,
Page 22& sunBeEsam
=< Institute of Information Technology
sureeain LEARNING INITIATIVE
Na wears
Polymorphism :
Ability of diferent objects to responds tothe same message in diferent ways called Polymorphism, .
norse.Neve(); _
'
car.-Move(); le
|
eroplane.Hove(); |
2erop °0 lk,
| Virtual and Override
| Polymorphism is achieved using virtual methods and inhertance ,
| (ira) Keyword is used to define 9 method in base dass and overde Keyword is used in derived dass °
Glass Euployee 7 — ke
|
{ public virtual double Calculatesalary ()
/ {return basic_sal+ hra + da
; } > |
@
class Manager: Employee |
{
public override double Calculatesalary ()
{return (basic_salt hra + da + allowances) ;}
staic void Main ()
{ Employee mgr= new Manager () ;
Double salary= mgr. CalculateSalary ();
Console.WriteLine (salary);
——_— —————— — Oe
‘SunBeam Institute of Information Technology, Pune, Karad Page24 SU!*
SUNBEAM ae
Institute of Information Technology
LEARNING INITIATIVE
Shadowing
Hides the base class member in derived class by using keyword new.
class Employee |
)
clase Salestmployee ‘Employee
{ double sales, comm;
public new double CalculateSalary ()
in |
static void Main ()
| | eetuen basic salt (eales * comm) +)
|
| Double salary= sper.CalculateSalary ();
{ SalesEmployee sper= new Salesimployee () ;
| |
|
Console .WriteLine (salary);
| -— a |
|
__|
Pepe ns Sunbeam institute of Information Technoley, Pune, Karad Page 25& sunBeam
4
= Institute of Information Technology = ansne
| |
Sealed class
Sealed class cannot be inherited
sealed class SinglyList
(
public virtual double add ()
{// code to add a record in the linked list}
y
public class StringSinglyLis
{
public override double Add ()
>> ve
inglyList
{ // code to add a record in the String linked list}
st
[=
‘SunBeam Institute of Information Technology, Pune, Karad Page 26"age 26
Hs
SUNBEAM F
Institute of Information Technology oes
Gaeuusens
Concrete class vs. abstract classes
.
Concrete class
Class describes the functionality of the objects that it can be used to instantiate,
Abstract class
Provides all of the characteristics ofa concrete class except that it does not permit objec instantiation
‘an abstract cass can contain abstract and non-abstract methods.
‘estract methods do not have implementation.
abstract class Employee
{ public virtual double Calculatesalary ()
{ return basic +hra + da
public abstract double CalculateBonus ()
class Manager: Employee
{public override double CalculateSalary();
{ return basic + hra + da + allowances ;}
public override double CalaculateBonus ()
static void Main ()
(| Manager mgr=new Manager ()
double bonus=mgr. CalaculateBonus ();
double Salary=ngr. Calculatesalary ();
‘SunBleam Institute of information Technology, Pune, Karad Page27Gq sunBeam
= Institute of Information Technology ceareene SeTATTE
Object class
Object class methods
public bool Equals(object)
protected void Finalze()
public int GetHashCode()
public System. Type GetType() }
protected object MemberwiseClone()
|
+public string ToString()
1g Object.
Polymorphism u:
‘The ability to perform an operation on an object without knowing the precise type of the object
[wold Display (object 0)
{
Console.WriteLine (o.ToString ()) i
}
public static void Main ()
{ Display (34);
Display ("Transflower”) ; :
Display (4.453655) ;
Display (new Employee (“Ravi”, “Tambade”) ; |
‘SunBeam Institute of Information Technology, Pune, Karad Page 28_ 7
@ SUNBEAM a
Institute of Information Technology LEARNING INTUATIVE
Wamaeouaens
Session 6:
Interface Inheritance
For loosely coupled highly cohesive mechanism in Application.
An interface defines a Contract
‘Text Editor uses Spelichecker as interfaces.
EnglishSpellChecker and FrenchSpeliChecker are implementing contract defined by SpeliChecker interface.
interface ISpeliChecker
{ ArrayList CheckSpelling (string word) ;}
class EnglishspellChecker:ISpelichecker
ArrayList CheckSpelling (string word)
{// return possible spelling suggestions}
hy
class Frenchspel checker: ISpell checker
n
| ArrayList CheckSpelling (string word)
|
| {// return possible spelling suggestions}
|
Ip
—— |etass rexteaitor
\
public static void Main()
{ ISpelichecker checker= new EnglishSpellchecker ();
| ArrayList wordsschecker. checkspelling (“FLewer")
,
)
a cof information Technology, Pune, Kaa Page 1SG@ SUNBEAM
Institute of Information Technology
ne
sureeam LEARNING INITIATIVE
|ET FRAMEWORK. a
| Explicit Interface Inheritance
interface IOrderDetails { void ShowDetails() +}
| interface IcustomerDetails { void Showdetails() ;}
| class Transaction: TorderDetails,’ ICustomerbetils
{
void IorderDetails. ShowDetails() '
{ // implementation for interface IOrderDetails ;}
void ICustomerDetails. ShowDetails()
{ // implementation for interface IOrderDetails ;} f
y
1 public static void Main()
t
Transaction obj = new Transaction();
TorderDetails od = obj;
od. ShowDetails () ;
ICustomerDetails cd = obj;
ed. ShowDetails();
a
SunBeam Institute of Information Technology, Pune, Karad Page 20@ SUNBEAM
— Institute of Information Technology LEARNING RETiATVE]
Wadi’
Abstract class vs. Interface
c Abstract class —Tinterface ]
Methods [Atleast one abstract method | All methodS are abstract
—— [Best suited for | Objects closely related in hierarchy. [Contract based provider model__|
[Multiple] Not supported Supported
a _ | _
‘Component ‘By updating the base class all derived classes | Interfaces are immutable ‘
Versioning | are automatically updates. el
|
|
|
|
|
|
|
|
|
————
=== SunBeam Institute of Information Technology, Pune, Karad Page 31
Page 30rE
G SUNBEAM be
= Institute of Information Technology Leaning NITATIVE |
' anid B
~ RI
Building cloned Objects Pe
class StackClass: ICloneable _ — [Rem
{ int size; int [] sArr;
public StackClass (int s) ( size=s; sArr= new int [sizel; }
public’ object Clone() syst |
Type |
StackClass s = new StackClass (this. size) ; |
syst |
this.sArr.CopyTo(s.sArr, 0); Cont :
| t
| ; fa
} fas
Me:
public static void Main() Le
|‘ StackClass stackl = new StackClass (4);
Stackl [0] = 89; i
StackClass stack2 = (StackClass) stackl.Clone (); :
3
‘SunBeam Institute of Information Technology, Pune, Karad Page 32 SunBeas
¥ =
Sed
LEARNING INTIATIVE
qa Wau waa
Reflection
G SUNBEATN
Institute of Information Technology
Reflection is the ability to examine the metadata in the assembly manifest at runtime,
Reflection is useful in following situations:
‘+ Need to access attributes in your programs metadata.
+ To examine and instantiate types in an assembly.
+ To build new types at runtime using classes in System.Reflection.Emit namespace.
+ To perform late binding, accessing methods on types created at runtime.
System. Type class
Type class provides access to metadata of any .NET Type.
System. Reflection namespace
Contains classes and interfaces that provide a managed view of loaded types, methods and fields
‘These types provide ability to dynamically create and invoke types.
Description __ -
Performs reflection on a module:
‘Load assembly at runtime and get its type _
‘Obtains information about the attributes of @ member and provides access to
member metadata,
Le
‘SunBeam Institute of Information Technology, Pune, Karad Page 33
Page 32SUNBEAM
Institute of Information Technology i eared RETR
' Btiaaawasuns 5
BindingFlags.InvokeMethod | BindingFlags.Instance, null, ob}, args); jeny,
break; Cold
} mist |
Come
Assembly class cecal
- _ —— ue
Methodinfo method;
AColb
string methodName; cal
object result = new object (); Syste |
The bi
object [] args = new object [] (1, 2};
Assembly asm = Assembly.LoadFile (@”c:/transflowerLib.d11”) ; janet |
for
| type [] types= asm.Gettypes(); °
co
foreach (type t in types) iu
Arca
{ (method = t.GetMethod (methodName) 7 ee
: i aera
_ | Collec
string typeName= t.FullName;
object obj= asm.CreateTnatance (typeName) ; Allow ¢
result = t.InvokeMenber (method.Nane, BindingFlags.Public | Inter
TEnur
i
string res = result.ToString();
Console.WriteLine ("Result is: (0}", res); Icom, |
qiet
MemberInfo ciass
"Base class for all members of the class
| Parameterinfo, FieldInfo, EventInfo, PropertyInfo, MethodInfo, Constructorinfo, etc.
————————
Sun
‘SunBeam Institute of Information Technology, Pune, Karad Page H sunBea= Institute of Information Technology
Rosas
SUNBEAM
LEARNING INTIATIVE
new int[5]
{ 22,11,33,44,55 };
fonsole.WriteLine( “\t {0}", i); }
ray .Reverse (intArray) ;
© collection Interfaces
‘Allow collections to support a different behavior
Interface Description
Fenumer tor: Supports @ simple iteration over collection
gs);
Ténunerable ‘Supports foreach semantics
collection
I
Tist Represents a collection of objects that could be accessed by index.
IComaprable Defines a generalized comparison method to create a type-specific
comparison
Comparer
Exposes a method that compares two objects,
qictionary Represents a collection of Key and value palts
=== _SinBeam institute of Information Technology, Pune, Karad
Pope ne | Sb ea Fmatio iy, Pune, Kai
Defines size, enumerators and synchronization methods for all collections.
Page 35,1
@ sunBeam
Institute of Information Technology LEARHNG BETTIE '
Taal z i
Im
Implementing IEnumerable Interface
[public class Team:IEnumerable ~ ines
{
private player [] players; [pai
public Team () \«
} ¢
| Players= new Player [3]; as
Players [0] = new Player ("Sachin”, 40000) ; es
Players[1] = new Player ("Rahul”, 35000); )
Players [2] new Player ("Mahindra”, 34000); f
) ial
public IEnumertor GetEnumerator ()
{
Return players .GetEnumerator () ;
| public static void Main()
(
{haan radia = new Toan();
foreach (Player ¢ in India)
t i
Console.WeiteLine (c.Name, ¢.Runs) ; |
, |
u |
‘Sune
‘SunBeam Institute of Information Technology, Pune, Karad Page 3@ SUNBEAM
Institute of Information Technology LEARNS TTLATEE
al Wi wae cous
|
Implementing ICollection Interface
To determine number af elements in a container.
lity to copy elements into System. Array type
rICollection
public class Tean
fl
private Players [] players;
public Team() (0...)
public int Count (get {return players.Count ;}
// other implementation of Team
)
public static void Main()
{
Team India = new Team ();
foreach (Player c in India)
(
Console.WriteLine (c.Name, c.Runs) ;
|
2 a _
ee
‘SunBeam Institute of Information Technology, Pune, Karad Page 37
Page 366 sunBeEam
Institute of Information Technology
LEARNING INITIATIVE
sen
Implementing IComparable Interface
public class Player: ICoi
{
‘able
int IComparable.CompareTo (object obj)
{
Player temp= (Player) obj;
if (this. Runs > temp.Runs)
return 1;
if (this. Runs < temp.Runs)
return -1;
else
return 0;
}
)
public static void Main()
Team India = new Team();
// ada five players with Runs
Arary.Sort (India) ;
// display sorted Array
)
SunBeam Institute of Information Technology, Pune, Karad
Usir
“E
wes
|
t
|a
LEARNING INTIATIVE
a | Gaienas
Institute of Information Technology
G@ SUNBEAM
Using Iterator Method
if
| |psbasc ctase tone |
[|
public Team ()
| t
| Players= new Player (31;
1] Players(0} = new Player ("Sachin”, 40000) ;
| Players {1} = new Player (*Rahul”, 35000) ;
| Players[2] = new Player ("Mahindra”, 34000) ;
| | ,
{
| | public rEnumertor GetEnumerator ()
Pit
| foreach (Player p in players) |
{yield return p ;}
public static void Main()
{ Team India = new Team();
foreach(Player c in India)
Console.WriteLine(c.Name, c.Runs);
of Information Technology, Pune, Karad Page 396& sunBeam
Institute of Information Technology
i,
»
fide.
LEARNING INITIATIVE
Glenna’
Collection Classes
ArrayList class
Represents lst which is similar to a single dimensional array that can be resized dynamically.
RrrayList countries = new ArrayList ();
countries .Add (“India”) ;
countries .Add (“USA”) ;
countries .Add ("UK") 7
countries Add (“China”) ;
countries Add ("Nepal”’
Console.WriteLine("Count: {0}, countries. Count);
foreach (object obj in countries)
t
Console.WriteLine("{0}", 0b3);
Stack class
Represents a simple Last- In- First- Out (LIFO) collection of objects.
Stack numStack = new Stack()7
numStack . Push (23) ;
numStack . Push (34) ;
numStack . Push (76) ;
numStack. Push (9) ;
onsole.WriteLine ("Element removed”, numStack.Pop()) i
Queue class’
_ Represents a first in, first-out (FIFO) collection of objects.
Queue myQueue = new Queue ();
myQueue .Enqueue (“Nilesh”) ;
myQueue .Enqueue ("Nitin”) ;
myQueue. Enqueue (“Rahul”) ;
myQueue . Enqueue ("Ravi") ;
Console.WriteLine("\t Capacity: {0}, myQueue.Capacity)
iriteLine(" (Dequeue) \t {0}, myQueue.Dequeue()) i
Karad
Page
pel eerenepren ere inennecee greene ame cemmmpmcemseste bre
Has
Rep,
Fact
‘SunB@ SUNBEAM
Institute of Information Technology LERRANG RATTIE
Buses
HashTable class
Represents a collection of Key/ value pairs that are organized based on the hash code of the key.
Each element is 2 key/ value pair stored in a DictionaryEntry object,
Hashtable h = new Hashtable ();
h.Add("mo”, “Monday”) ;
|R.ada(vtu”, Tuesday”) 7
h.Add("we”, “Wednesday”) ;
| rrictionaryEnumerator e= h. GetEnumerator( ); |
while (e.MoveNext( ))
{
| Console.WriteLine(e.Key + “\t” + e.Value) ;
| )
|
‘SunBeam Institute of Information Technology, Pune, Karad Page 41
Page 40'
i
@& SUNBEAM
Institute of Information Technology
LEARNING INITIATIVE
|ET FRAMEWORK.
+ Generics
‘Are classes, structures, interfaces and methods that have placeholders (type parameters) for one or more of the types
they store or use.
class HashTable
4
public HashTable() ;
public object Get (K) ;
public object Add(K, V);
»
HashTable addressBook;
AddressBook.Add (“Amit Bhagat”, 44235) ;
int extension = addressBook.Get ("shiv Khera”)
List class
Represents 2 strongly typed list of objects that can be accessed by index.
Generic equivalent of ArrayList class.
Tist months = new List (0);
months .Add (“January”) ;
months .Add ("February")
months .Add (“April”) ;
months .Add ("May") 7
months .Add (“June”) ;
foreach (string mon in months)
Console.writeLine (mon) ;
Months. Insert (2,”March”) 7
‘SunBeam Institute of Information Technology, Pune, Karad
Page a2
al
;© Page 42
& SUNBEAM :
Institute of Information Technology LEARNING WITIATR
VE
List of user defined objects
lass Employee
{
int eid;
string ename;
//appropriate constructor and properties for Employee Entity
4
public int Compare (Employee e1, Employee 2)
{ int ret = e1.Name.Length.CompareTo (e2.Name. Length) ;
return ret;
)
y
| public static void Main Q)
|Listeenployee>listi = new List ()
[asses Add (new Employee (1, “Raghu”) ;
List Add(new Employee (2, “Seeta”) ;
Listl Add (new Employee (3, °Neil”) ;
Listi Add (new Employee (4, “Leela”) ;
| empComparer ec = new EmpComparer () 7
| nist1.Sort (ec) ;
| goreach (Employee e in list1)
Console. WriteLine(e.Id + ™
}
“+ @.Name) ;
‘SunBeam Institute of Information Technology, Pune, Karad
Page 43Presanng
Wodelca
Stack class
Stack();
numStack. Push (23) ;
numStack . Push (34) ;
mumStack. Push (65) ;
| Console.WriteLine ("Element removed: “, numstack. Pop()) ;
Queue class
Queue q = new Queue();
q.-Enqueue ("Message") ;
q-Enqueue ("Message2”) ;
q.Enqueue ("Message3") ;
Console.WriteLine ("First message: (0}”, q.Dequeue()) ;
| console.WriteLine ("The element at the head is (0}”, q-Peek());
| tenumerator e= q.GetEnumerator () ;
while (¢.MoveNext ())
Console.Writebine(e.Current)
LinkedList class
Represents a doubly linked List
Each node is on the type LinkedListNode
[Linkedbist 11= new LinkedList () ;
Ll.AddFirst (new LinkedListNode (“Apple”) )
| ta -addPirst (new LinkedListNode ("Papaya”)) j
Ll. AddPirst (new LinkedListNode("Orange”)) ;
L1.AddFirst (new LinkedListNode("Banana”)) ;
LinkedListNode node=11.First;
Console.WriteLine (node. Value) ;
| console .WriteLine (node.Next Value) ;
—$—$—$—— — ————————
‘SunBeam Institute of Information Technology, Pun‘ Page 44@ SUNBEAM
Institute of Information Technology
LEARNING INTIATIVE
| Gwe reas
Dictionary class.
| Represents a caletion of keys and values
Keys cannot be duplicate,
| phones.Add(1, “James”) ;
Li] [Preiss caaacan) iSey)
| phones[16] = “Aishwarya”;
if (!phone.ContainsKey (4))
phones .Add(4,"Tim") ;
Console.WriteLine ("Name is {0}”, phones [4]);
7 Console.WriteLine ("Name {0}”, phones [12]);
|
|
|
i
I
Ld
‘SunBeam Institute of Information Technology, Pune, Karad Page 4Si
& SUNBEAM
Institute of Information Technology LeARNnG eTTWE
Gaaueaen
Session 8:
+ Custom Generic Types
Generic function
public static class MyGenericMethods
{
public static void Swap(ref T a, ref T b)
t Fl
Console.WriteLine ("You sent the Swap() method a {0}", typeof(T));
T temp; temp = a; a = b; b = temp;
d
public static void DisplayBaseClass()
{Console.WriteLine("Base class of {0} is: {1}.",typeof(T),
typeof (T) .BaseType) ;
}
)
static void Main(string[] args)
{ // Swap 2 ints.
int a = 10, b = 90;
Console-WriteLine ("Before swap: (0), {1}", a, b);
Swap (ref a, ref b);
Console.WriteLine ("After swap: (0), (1)", a, b);
Console.WriteLine() ;
// Swap 2 strings
string s1 = "Hello", s2 = "There"
Console.WriteLine("Before swap: {0} {1}!", sl, s2);
Swap(ref sl, ref s2);
Console.WriteLine("After swap: (0} {1}!", sl, 82);
Console.WriteLine() ;
// Compiler will infer System.Boolean
bool bi=true, b2=false;
Console.WriteLine("Before swap: {0}, {1}", bl, b2);
Swap (ref bl, ref b2);
Console.WriteLine("After swap: {0}, {1}
Console.Writebine() ;
bl, b2);
—_—— |
SunBeam Institute of Information Technology, Pune, Karad Page 46|
—_—_
‘page 46
G SUNBEAM
— Institute of Information Technology
LEARNING INITIATIVE
Gime
7/ Must supply type parameter if the method does not take params
DisplayBaseClass ()
| Sigpraysacectasscsteing> ()
} >
static void Swap(ref T a, ref Tb)
{
Cénsole.WriteLine ("You sent the Swap() method a {0}", typeof (T));
‘T temp; temp = a; a = b; b = temp;
}
static void DisplayBaseClass()
‘
| console WriteLine("Base class of {0} is: (1).",
| typeof (2), typeof (1) -Baseype) ;
)
‘SunBeam Institute of Information Technology, Pune, Karad
Page 47| 77 ® generic Point structure
G&G SUNBEAM
=, Institute of Information Technology LEARAREG ATATWE
Wawasan
‘Custom Structure
public struct Point
{// Generic state date.
private T xPos;
private T yPos;
// Generic constructor.
public Point(T xVal, T yval)
{ xPos = xVal; yPos = yval; }
// Generic properties
public TX
{ get { return xPos; } set { xPos = value; } =}
public T ¥
{ get { return yPos; } set { yPos = value; } }
public override string ToString()
{return string.Format("[{0}, (1}]", xPos, yPos); }
// Reset fields to the default value of the type parameter.
public void ResetPoint ()
{ xPos = default(T); yPos = default(T); }
‘SunBeam Institute of Information Technology, Pune, Karad Page 48 |¥
SUNBEAM a
Institute of Information Technology
LEARNING INTIATIVE
Giannis
static void Main(string[] args)
// Point using ints.
Point p = new Point(10, 10);
Console.WriteLine ("p.ToString()=(0}", p.ToString()) ;
p-ResetPoint() ;
Console.WeiteLine ("p.ToString()=(0}", p.ToString()) ;
// Point using double.
Point p2 = new Point(5.4, 3.3);
Console. WriteLine ("p2.ToString()=(0}", p2.ToString());
p2.ResetPoint ();
Console. WriteLine("p2.ToString()=(0}", p2.ToString()) ;G SUNBEAM
Institute of Information Technology
LEARNING INTIATIVE,
‘Custom Generic collection class
public class Car
{ public string PetName; public int Speed;
public Car(string name, int currentSpeed)
{ PetName = name; Speed
public Car() { }
currentSpeed; }
lpublic class SportsCar : Car
{ public sportsCar(string p, int s): base(p, s) ( }
// Assume additional SportsCar methods
,
public class Minivan : Car
{ public MiniVan(string p, int s) : base(p, 5) { }
// Assume additional Minivan methods.
// Custom Generic Collection
public class CarCollection> : Ignumerable where T : Car
new List();
{ private List<1> arCars
public T GetCar(int pos) { return arCars[pos]; }
public void AddCar(T c) { arCars.Add(c); }
public void Clearcars() { arCars.Clear(); }
public int Count { get { return arCars.Count; }
‘SunBeam Institute of Information Technology, Pune, Karad|
|
Institute of Information Technology
G SUNBEAM
// TEnumerable extends TEnumerable,
IEnumerator IEnumerable.GetEnumerator ()
{return arCars.GetEnumerator(); }
IEnumerator IEnumerable.GetEnumerator ()
{ return arCars.GetEnumerator(); }
| public void PrintPetName(int pos)
{Console .WriteLine(arCars[pos].PetName); }
)
| static void Main(string{] args)
| { // Make a collection of cars
| CarCollection myCars = new CarCollection(
myCars.AddCar (new Car("Alto", 20));
myCars.AddCar (new Car("i20", 90));
|| foreach (Car ¢ in myCars)
| { Console.WriteLine("PetName: {0}, Speed: (1}",
i }
|
CarCollection myAutos = new CarCollection can hold any type deriving from Car
>)
{ Console.WriteLine("Type: (0}, PetName: {1}, Speed: (2}",
c.Speed) ;
Page st: @ SUNBEAM
=, Institute of Information Technology LEARNING INTIATIVE
Madison
Exceptions Handling
‘Abnormalities that occur during the execution of a program (runtime error).
[NET framework terminates the program execution for runtime error.
2.9. divide by Zero, Stack overflow, File reading error, loss of network connectivity
vechaniem o dete ard tale runtime et.
- So
int a, b
console. Weitenine (My progran starts”);
i try |
{ poe
10/b; |
; ||
exten inceeption’ 6} |
{
Console.WriteLine(e.Message) ;
}
console.WeiteLine(*Remaining program’); |
: }
NET Bxeéption sae
‘SystemException ___ | Formatxception i
RiginontBseopeion Tadexoutofexception
See ae pucoption | TnvalidGastexpression
See eatenixception —[Tivalidoperationtxception
toreteeption Nollkefesencenaception
Sividsbyrerorsception Gutottensryerception
; [StackoverflowException I
| ‘SunBeam Institute of Information Technology, Pune, Karad Page 52!@ SUN BeaAm ,
= Institute of Information Technology eo
|
|
q Wai serns
User Defined Exception classes
Application spectic class can be created using ApplicationException class.
Glass StackFullException:ApplicationException
{
public string message;
| public StackFullmxception (string msg) |
4
Message = msg:
>
U |
public static void Main(string [] args)
(
| stackclass stack:
new StackClass (); |
{ stackl.Push (54);
stack! Push (24) ; |
stack1. Push (53) ; :
stack1. Push (89) ; |
i
atch (StackFullException s)
Console. WriteLine(s.Message) ;
‘SunBeam Institute of Information Technology, Pune, Karat
Page 53| Institute of Information Technology LEARNING INITIATIVE '
|
Session 9:
+ Attributes
@ SsunBeam
Declarative tags that convey information to runtime.
Stored with the metadata of the Element
INET Framework provides predefined Attributes
“The Runtime contains code to examine values of attributes and to act on them
‘Types of Attributes
Standard Attributes
Custom Attributes
INET framework provides many pre-defined attributes.
General Attributes
1 COM Interoperability Attributes
‘Transaction Handling Attributes
Visual designer component- building attributes
[Serializable]
public class Employee
Standard Attributes
1t '
[NonSerialized]
public string name;
|
|
‘SunBeam Institute of Information Technology, Pune, Kared Page 54Institute of Information Technology LEARNS TeTTRTIE
Custom Attributes
& SUNBEAM
User defined class which can be applied as an attribute on any .NET compatibility Types like:
Class
Constructor
Delegate
Enum
Event
Field
Interface
Method
Parameter
Property
Return Value
Structure
Attribute Usage
AttributeUsuageattribute step 1
It defines some of the key characteristics of custom attribute class with regards to its application , inheritance, allowing
‘multiple instance creation, etc.
[ [AttributeUsuage (AttributeTargets.All, Inherited= false,
[ALlowMultiple=true) }
AttributeUsuageattribute step 2
Designing Attribute class
Attribute classes must be declared as public classes,
All Attribute classes must inherit direct or indirectly from System.attribute «
[[attribateUsuage (AttributeTargets All, Inherited= false,
| AllowMultiple=true) } |
| public class MyAttribute:System.Attribute
(
‘SunBeam Institute of Information Technology, Pune, Karad Page SS|
:
4
|
SUNBEAM ve
ii.
Institute of Information Technology (EAR NETTIE
Wwe
AttributeUsuagedttribute step 3
Defining Members
‘tributes are initialized with constructors in the same way as traditional classes.
public MyAttribute (bool myValue) a
t
this.myValue = myValue;
d
Attribute properties should be declared as public entities with description of the data type that will be returned.
public bool MyProperty
{
get { return this. MyValue ;}
set (this. MyValue= value ;}
)
Applying Custom Attribute
Custom attribute is applied in following way.
Retrieving Custom Attributes
[Developer (“Ravi Tanbade”, “I"]
| public class Employee
[¢
}
public static void Main()
(
Employee emp = new Employee ();
Type t = emp.GetType() ;
foreach (Attribute a in t.GetCustomAttributes (true) )
t
Developer r= (Developer) a;
//Recess r.Name and r.Level
»
——
‘SunBeam Institute of Information Technology, Pune, Karad Page 56@ SUNBEAM
= Institute of Information Technology LEARNS OTT
1 NET FRAMEWORK
Delegates
A delegate isa reference to a method
‘Al delegates inherits from the System. delegate type
It's foundation for Event Handling
Delegate Types
Unicast (Single cast)
— Multicast Delegate
Unicast (Single cast) Delegate
‘Steps in using delegates
—] i. Define delegate
li, Create instance of delegate
strDelegate strDel =new strDelegate (strobject .ReverseStr) ;
| string str=strDel (“Hello Transflower”) ;
| // of use this Syntax
string str =strDel.Invoke ("Hello Transflower”) ;
Multicast Delegate
If amutticast delegate derives from System. MulticastOelegate class.
It provides synch-onous way of invoking the methods in the invocation list.
Generally multicast delegate has void as their return type.
a
| delegate void strDelegate (string str);
| steDelegate delegateob3 ;
| strDelegate Upperob} = new strDelegate (obj-UppercaseStr) ;
u
||| secperegate towerobj = new stedelegate (obj Lowercasestr) ;
| detegateob3=vpperob3;
delegateobj+
owerob3;
|| [dotegateob) (“Welcome to Transflower);
i
FETE | SunBear institute oF information Technotogy, Pune, Kared Page 57
Page.|
|
G&G SUNBEAM
<= Institute of Information Technology
suneeam LEARNING INITIATIVE
Gaauuaiics
Delegate chaining
Instances of delegate can be combined together to form a chain
Methods used to manage the delegate chain are
© Combine method
+ Remove method
//ealculator is a class with two methods Add and Subtract
Calculator obj1 = new Calculator () ;
CalDelegate [] delegates = new CalDelegate[];
{ new CalDelegate (obj1.Add) ,
new CalDelegate (Calculator. Subtract) );
CalDelegate chain = (CalDelegate) delegate. Combine (delegates) ;
Chain
(CalDelegate) delegate.Remove(chain, delegates [0]);
Asynchronous Delegate
It is used to invoke methods that might take long time to complete.
‘Asynchronous mechanism more based on events rather than on delegates
delegate void strbelegate (string str);
public class Handler
{
public static string UpperCase(string s) {return s. ToUpper() ;
}
strDelegate caller = new strDelegate (handler. UpperCase) ;
TAsyncResult result = caller.BeginInvoke("transflower”, null, null);
Wb vies
String returnValue = caller.EndInvoke (result) ;
ee
‘SunBeam Institute of Information Technology, Pune, Karad“age SB
@ SUNBEAM
Institute of Information Technology
LEARNING INITIATIVE
Genoa’
Anonymous Method
Iti called as inline Delegate,
It isa block of code that is used as the parameter for the delegate
[detegate string strDelegate(string str);
ype static void Main()
I
stzDelegate upperStr = delegate (string s)
)
{zeturn s.ToUpper ()
———————
SunBeam Institute of Information Technology, Pune, Karad
Pages@® SUNBEAM
Institute of Information Technology LEMAR
Gaiam
Session 10:
Events
‘An Event is an automatic notification that some action has occurred.
‘An Event is built upon Delegate
public delegate void Accountoperation () ;
public class Account
{private int balance;
public event Accountoperation UnderBalance;
public event AccountOperation OverBalance;
public Account() {balance = 5000 ;}
public Account (int amount) (balance = amount ;}
public void Deposit (int amount)
{ balance = balance + amount;
if (balance > 100000) { OverBalance(); } |
,
public void Withdraw(int smount)
{balancesbalance-amount; |
if(balance < 5000) { UnderBalance () ;}
—
‘SunBeam Institute of Information Technology, Pune, Kared Page 6Institute of Information Technology —
|ET-FRAMEWORK
class Program
& SUNBEAM ° wa
{ static void Main(string [] args) |
{Account axisBankaAccount = new Account (15000) ; F
//register Event Handlers
axisBankAccount .UnderBalance+=PayPenalty;
axisBankAccount . UnderBalance+=BlockBankAccount ;
axisBankAccount . OverBalance+=PayProfessionalTax;
axisBankAccount.OverBalancet= PayIncomeTax; |
axisBankAccount Withdraw (15000) ;
Console. ReadLine () ;
y
//Perform Banking Operations |
//Ewent handlers
| static void PayPenalty()
{Console.WriteLine("Pay Penalty of 500 within 15 days"); —}
static void BlockBankAccount ()
{Console.WriteLine("Your Bank Account has been blocked") ;}
{Console.WriteLine("You are requested to Pay Professional Tax") ;}
static void PayIncomeTax ()
(Console.WeiteLine("You are requested to Pay Income Tax as 7S") ;} |
| static void PayProfessionalTax()
|
‘SunBeam Institute of Information Technology, Pune, Karad Page 61SUNBEAM
Institute of Information Technology a TH
Placement lative
MS.NET
Windows Forms.
Winforms used to build traditional Desktop applications,
‘The WinForm API supports RAD (Rapid Application Development) and relies extensively
on properties to enable you to tailor the WinForm to your needs.
Microsoft has supplied its default libraries under the System.Windows.Forms namespace
‘The assembly being System.dil and System.Windows.Forms.dil.
Event Driven Applications
Individual user actions are translated into “events”,
Events are passed one by one to application for processing.
GUI based Events
Mouse Move, Mouse Click, Mouse double Click,Key press, Button click, Menu Selection
Change in Focus, Window Activation
Code-behind
Events are handled by methods that live behind visual interface
Known as “code-behind”
Developer job is to program these events.
GUI (Graphics User Interface) applications are based on the notion of forms and controls.
‘A form represents a window
‘A form contains zero or more controls
————
‘SunBeam Institute of Information Technology, Pune, Page 1“see
MS.NET.
First WinForm Application
qq SsuNBeam
Institute of Information Technology
Placenent nitive
using System.Windows.Forns ;
public class Forml : Form
{ public static void Main()
( //Run the Application
Application.Run(new Forml()) ;
GDI+
GDI+ resides in System.Drawing.dil assembly.
All GDI+ classes are reside in the
System.Drawing, System.Text, System.Printing,
System. Internal , System.Imaging,
System.Drawing2D and System.Design namespaces.
The Graphics Class
‘The Graphics class encapsulates GDI+ drawing surfaces. Before drawing any object (for
example circle, or rectangle) we have to create a surface using Graphics class. Generally we
use Paint event of a Form to get the reference of the graphics. Another way is to
‘override OnPaint method.
private void fozml_Paint (object send
PaintiventArgs e)
‘SunBeam Institute of Information Technology, Pune, Karad
Page 2
ISUNEEA
Institute of Information Technology da ag
Graphics class's method:
mn
Placement hate
DrawAre [Draws an arc from the specified ellipse.
DrawBezier | Draws a cubic bezier curve. -
| DrawBeziers Draws a series of cubic Bezier curves.
DrawClosedcurve | Draws a closed curve defined by an array of points,
Drawcurve Draws a curve defined by an array of points. 7
| Deawellipse Draws an ellipse. _
Drawimage [Draws an image. 7 -
DrawLine Draws a line. _
DeawPath Draws the lines and curves defined by a GraphicsPath.
DrawPie Draws the outline of a pie section.
DrawPolygon Draws the outline of a polygon.
DeawRectangle | Draws the outline of arectangle.
DrawString Draws a string.
FillEllipse Fills the interior of an ellipse defined by a bounding rectangle.
Filipath Fills the interior of @ path. |
FillPie Fills the interior of a pie section
FillPolygen Fills the interior of a polygon defined by an array of points. |
FillRectangle | Fills the interior of a rectangle with a Brush. “|
Filinectangles | Fills the interiors of a series of rectangles with @ Brush, al
Filikegion Fills the interior of a Region,
——$——————————
‘SunBeam Institute of Information Technology, Pune, Karad Page 3SUNBEAM yo j
Institute of Information Technology Kan tT
GDI Objects
After creating a Graphics object, you can use it draw lines, fil shapes, draw text and so on.
The major objects are:
Brush | Used to fill enclosed surfaces with patterns, colors, or bitmaps.
Pen _ | Used to draw lines and polygons, including rectangles, arcs, and pies
Font | Used to describe the font to be used to render text
Color | Used to describe the color used to render a particular object. In GDI+
color can be alpha blended
Pen pn = new Pen( Color.Blue );
Pen pn = new Pen( Color.Blue, 100 );
The Font Class
The Font class defines a particular format for text such as font type, size, and style
attributes. You use font constructor to create a font.
Initializes a new instance of the Font class with the specified attributes,
Font font = new Font ("Times New Roman”, 26);
The Brush Class
‘The Brush class is an abstract base class and cannot be instantiated. We always use its
derived classes to instantiate a brush object, such as SolidBrush, TextureBrush,
RectangleGradientBrush, and LinearGradientBrush.
LinearGradientBrush 1Brush = new LinearGradientBrush (rect,
Color.Red, Color. Yellow,LinearGradientMode.BackwardDiagonal) ;
1/08
Brush brsh = new SolidBrush(Color.Red), 40, 40, 140, 140);
The SolidBrush class defines a brush made up of a single color. Brushes are used to fill
‘graphics shapes such as rectangles, ellipses, pies, polygons, and paths.
The TextureBrush encapsulates a Brush that uses an fills the interior of a shape with an
image.
‘The LinearGradiantBrush encapsulates both two-color gradients and custom multi-color
gradients.
aaaP NNR nenpeunennrenereerees—eceuieeeee= eee
SunBeam Institute of Information Technology, Pune, Karad Page 4SUNBEAM m «a
Institute of Information Technology
Mi
Ga
Rectangle Structure
angle (Point, Size);
public Rectangle(int, int, int, int);
Point
Point ptl = new Point( 30, 30);
Point pt2 = new Point( 110, 100);
Drawing a rectangle
protected override void OnPaint (PaintventArgs pe)
{
Graphics g = pe.Graphics ;
Rectangle rect = new Rectangle(50, 30, 100, 100);
LinearGradientBrush 1Brush = new LinearGradientBrush (rect,
Color.Red, Color. Yellow, LinearGradientMode.BackwardDiagonal)
g.FillRectangle(1Brush, rect);
b
Drawing an Arc
Rectangle rect = new Rectangle(50, 50, 200, 100);
protected override void OnPaint (PaintEventArgs pe)
{
Graphics g = pe.Graphics ;
Pen pn = new Pen( Color.Blue );
Rectangle rect = new Rectangle(50, 50, 200, 100);
g.DrawArc( pn, rect, 12, 84);
)
Drawing a Line
protected override void OnPaint (PaintBventArgs pe)
{
Graphics g = pe.Graphics
Pen pn = new Pen( Color.Blue );
// Rectangle rect = new Rectangle(50, 50, 200, 100);
Point ptl = new Point( 30, 30);
Point pt2 = new Point( 110, 100);
g.Drawhine( pn, ptl, pt2 );
}
‘SunBeam Institute of Information Technology, Pune, Karad Page SSUNBEAM
Institute of Information Technology tae. 48
Placement tive
Drawing an Ellipse
protected override void OnPaint (PaintEventArgs pe)
4
Graphics g = pe.Graphics ;
Pen pn = new Pen( Color.Blue, 100 );
Rectangle rect = new Rectangle(50, 50, 200, 100);
g.DrawEllipse( pn, rect );
)
The FillPath
protected override void OnPaint (PaintBventArgs pe)
t
Graphics g = pe.Graphics;
g.FillRectangle(new SolidBrush (Color.White), ClientRectangle) ;
GraphicsPath path = new GraphicsPath (new Point(] {
new Point (40, 140), new Point (275, 200),
new Point (105, 225), new Point(190, 300),
new Point (50, 350), new Point (20, 180), },
new bytel] {
(byte) PathPointType. Start,
(byte) PathPointType Bezier,
(byte) PathPointType.Bezier,
(byte) PathPointType.Bezier,
(byte) PathPointType.Line,
(byte) PathPointType.Line,
ne
PathGradientBrush pgb = new PathGradientBrush (path) ;
pgb.SurroundColors = new Color{] (
Color.Green,Color.¥ellow,Color.Red, Color.Blue,
Color.Orange, Color.White, };
g-Fillpath(pgb, path);
y
Drawing Text and Strings
protected override void OnPaint (Paintiventargs pe)
{
Font fnt = new Font("Verdana", 16);
Graphics g = pe.Graphics;
g.DrawString ("GDI+ Worl:
»
, fat, new SolidBrush (Color.Red), 14,10);
SS
‘SunBeam Institute of Information Technology, Pune, Karad Page 6SUNBEAM 7
aA
institute of Information Technology Macks 4 a
Placemeat Ita
.NET Data Access
ADO.NET
A rich set of classes, interface, structures and enumerated types that manage data access
from different types of data stores
ADO.NET Features
‘© A robust connected, disconnected Data Access Model
‘© Integrated XML support
© Data from varied Data Sources
© Familiarity to ADO programming mode! (unmanaged environment)
© Enhanced Support
Connected vs. Disconnected Architecture
Connected Disconnected
State of Constantly kept Opened Closed once data is fetched
Connection in cache at client side,
‘Scalability Limited — [More
Current Data Always available Not up to date
ADO.NET components
-NET Data Providers
‘Allow users to interact with different types of data sources.
ODBC Providers
OLEDB Providers
SQL Data Providers
Oracle Data Providers
DataSets
Explicitly designed for disconnected architecture
ADO.NET Interfaces
IDbConnection : Represents an open connection to a data source.
IDbCommand : Represents an SQL statement that is executed while connected to
a data source,
IDataReader : Provides a means of reading one or more forward-only streams of
result sets obtained by executing a command at a data source.
‘IDataAdapter: Provides loosely coupled Data Access with Data Sources.
SunBeam Institute of Information Technology, Pune
Poge 7SUNBEAM W@ |
Institute of Information Technology Ais
i rite
Has the responsibility of establishing connection with the data source.
Connection has to be explicitly closed in finally block.
‘SqlConnection conSql= new SqlConnection();
consql.ConnectionString = “server=DatabaseServer; Initial Cetalog=
Transflower; user id= sa; password=sa;
conSql.Open() ;
Command Object
Used to specify the type of interaction to perform with the database like select, insert,
update and delete.
Exposes properties like:
CommandText
CommandType
Connection
Exposes several execute methods like
ExecuteScalar()
ExecuteReader()
ExecuteNonQuery() |
i
<< -.
‘SunBeam Institute of information Technology, Pune, Karad PagesSUNBEAM
ae
Institute of Information Technology Aue, aa
Placement rive
//inserting Data |
string insertString = “insert inte dept (deptId,deptName,loc) values |
(10, /Metg’ , Mumbai’);
string updatestring = “update dept set deptName=’Marketing’ where
deptName=" Mktg’ ;
string deletestring = “delete from dept where deptName=' ABC’;
conSql.open() ;
sqlCommand ond= new SqlConmand(insertString, conSql) ;
end ExecuteNonQuery () ; _
Getting Single Value
SqiGonnand cndSqi = new SqiCommand();
emdSql.Connection = conSql;
emdSq).CommandText = “Select Count (*) from emp”;
int count = (int) emdSql.ExecuteScalar();
MessageBox. Show (count. ToString()) 7
The DataReader Object
Used to only read data in forward only sequential manner.
string queryStr = “Select deptName, loc from dept”
conSql. Open) ;
sqlConmand cmdSql = new SqlCommand(queryStr, conSql) ;
SqlDataReader dataReader= cmdSql.ExecuteReader () ;
while (dataReader .Read())
MesageRox.Show("Last Name is “+ dataRead[0] .ToString()) ;
MessageBox. Show ("First Name is “+ dataRead[1] .ToString()) ;
)
dataReader.Close() ;
—_—
‘SunBeam Institute of Information Technology, Pune, Karad PageSuUNBESEAM
institule of Information Technology ‘Maa i
Placement niiatve
Adding parameters to Command
conSql.open()?
SqlCommand cmd = new SqlCommand("select * from emp where empNo
=@eno”, consql) ;
SqlParameter param = new SqlParametez() ;
param. ParameterName = “@eno”;
param.Value = 100;
cmd. Parameters .Add (param) ;
SqlDataReader reader =cnd.ExecuteDataReader () ;
white (reader.Read())
(
//pisplay data
Calling a Stored Procedure
//Stored Procedure in SQL Server
CREATE PROCEDURE DeleteEmpRecord (¢eno)
AS delete from emp where empno = Geni
RETURN
//C# Code
SqlCommand cmd = new SqlCommand (“DeleteEmpRecord”, consq) ;
cmd.Commandtype = Conmandtype. StoredProcedure;
omc. Parameters .Add( new SqlParameter("@eno”, 100) ;
Multiple Que
Multiple queries can be executed using a single command object.
[ Sqlcommand cmd = nen
new SqlCommand(“select * from dept; select * from
emp”, consql) ;
SqlDataReader reader =cmd.BxecuteDataReader ();
/Icode to access first result set
bool result = dr.NextResult() ;
// code to access next result set
——————
‘SunBeam Institute of Information Technology, Pune, Karad Page 10. SUNRBEaAm °
Institute of Information Technology wa. FH
Placement iritisive
Disconnected Data Access
Data Adapter
Represents a set of data commands and a database connection that are used to fill the
dataset and update a sql server database.
Forms a bridge between a disconnected ADO.NET objects and a data source.
Supports methods
Fil
Update ();
string salStr= “SELECT * FROM Orders”;
SqlAdapter da = new SqlAdapter (sqlStr, con);
DataAdapter Properties
SelectCommand
Insertcommand
DeleteCommand
UpdateCommand
da.SelectCommand.CommandText = “SELECT customerID , ContactName ma
Customers”;
Saicommand cmd = new SqlCommand (“INSERT inte Customers (CustomerID,
CompanyName) VALUES (898, ‘Sunbeam’
da.InsertCommand = command;
‘SunBeam Institute of information Technology, Pune, Karad Page 11,r SUNBEAM W 4
== Institute of Information Technology ia.
ein
DataSet
Main object of disconnected architecture
Can store tables with their schema at client side.
[Peon]
ee
‘SunBeam Institute of information Technology, Pune, Karad Page 12,r
SUNBEAM
Institute of Information Technology
Role of CommandBuilder Object
‘Automatically generates Insert, Update, Delete queires by using SelectCommand property of
DataAdapter
‘GqiConnection con = new SqlConnection ("server=databaseServer;
Initial Catalog= Transflower; userid=sa; password=sa") ;
SqlDataAdapter da= new SqlDataAdapter
sqiconandbuiider endbuilder= new SqlConmandsutlder (da)
DataSet ds= new DataSet (); |
Da.Fill(ds, “Cusomters”) :
Constraints
Constraints restrict the data allowed in a data column or set of data columns.
Constraint classes in the System.Data namespace
UniqueConstraint
ForeignkeyConstraint
Using existing primary Key constraint
‘il1Schema (ds, jource, Customers”);
typ
or
da.MissingSchemaaction = AddWithKey;
da.Fill (ds, Customers");
‘SunBeam Institute of Information Technology, Pune, Karad, Page 13,fe, mW! TEBE AM
Institute of Information Technology
ADO.NET and XML
With ADO.NET it is easy to
Convert data into XML
Generate a matching XSD schema
Perform an XPath search on a result set.
Interact with an ordinary XML document through the ADO.net.
DataSet XML Methods
Getmi()
GetXmiSchema()
Readxml()
ReadXmiSchema()
Writexmi()
WritexmiSchema()
InferxmlSchema()
Concurrency in Disconnected Architecture
Disadvantage of disconnected architecture
© Conflict can occur when two or more users retrieve and then try to update
data in the same row of a table
‘0 The second use’s changes could overwrite the changes made by the first
user.
Solutions -
Optimistic concurrency
Retrieves and updates just on row at a time
te me serra mam
‘SunBeam Institute of Information Technology, Pune, Karad Page 14
|
|SUNBEAM
institute of Information Technology
MS.NET
File Handling and Serial
Input and Output operation in C#
1/0 in C# is stream based.
Stream is flow of data from a source to a receiver through a channel.
Two types of Streams
Byte Streams
Character Streams
Three predefined streams are
Console.Out
Console.In
Console.Error
System.IO Namespace
File 10 using System.IO:
System.10 namespace defines all the stream classes,
File System Classes |
(Coretoy J} tere)
| |____.{ FileStream |
Directoryinfo }-———| = —
| ____[ Filesystemints }
(“owen ——~
| Driveinfo_+——4
i — GZipStream
Path —} _f
C= saa
(Fie }—— J L____{ Defiatestream
——
SunBeam Institute of Information Technology, Pune, Karad Page 15SUNBEAM
Institute of Information Technology
Directory Class
Static class and helps to manage a single directory.
ia.
Placement Iitatve
Bering DirectoryName = @”C:\MyDirectory”;
if (Directory. Exists (DirectoryName) )
(MessageBox. Show ("Exists") }
else
{Directory.CreateDirectory (DirectoryName) ;
MessageBox. Show (“Created”) ;
,
DirectoryInfo Class
Extends the FileSystemInfo class.
Performing operations such as copying, moving, renar
19, creating, and deleting,
‘string DirectoryName = @”C:\MyDirectory”
if (Directory. Exists (DirectoryName) )
{ MessageBox.Show("Exists”); —}
else
a.create();
MessageBox. Show ("Created") ;
Driveinfo and Path Class
Drivelnfo class
Models a drive and gives its information
string 3 = @"C:\"F
DriveInfo d = new DriveInfo(s) ;
MessageBox.Show (d.AvailableFreeSpace.ToString (), 4.
Path class
Used to manage file and directory paths.
{ DixectoryInfo d= new DirectoryInfo (DizectoryName) ;
MessageBox.Show (Path.GetPileName(s)) 7
MessageBox.Show (Path.GetTempPath ()) :
‘SunBeam Institute of Information Technology, Pune, Karad
CF String s = @”C:\temp\MyData.text\machine. config”;
Page 16SuNBEAM
Institute of Information Technology ha re
File Class
Static class and helps to manage a single file
“string FileName = @”C:\MyFile.dat";
if (File.Exists (FileName))
4
: |
MessageBox.show ("Ceéated”) |
Other File System Classes
DeflatesStream
GZipStream
SerialPort
FileSysteminfo
Stream class
Stream is an abstract base class for all other stream classes
Common 1/0 Stream Classes
(Sn)
_ —
[cormsiean') iC =
(esteem }
‘SunBeam Institute of Information Technology, Pune, Karad Page 17SUNBEAM
Institute of Information Technology
wid
Placement Iriaive
Used to perform operations liked read, write, open, and close operations on files on a file
system.
For better performance, FileStream class buffers input and output.
aryReader and BinaryWriter Class
BinaryReader class is used to read data in binary files.
BinaryWriter class is used to write data to binary files.
:
i
The Character Stream Wrapper Classes
TextReader
Abstract class to read sequential series of characters
Inherited by
StreamReader
StringReader
TextWriter
Abstract class to write sequential series of characters
Inherited by
StreamWriter
StringWriter
StreamReader
Used to read data from stream.
‘StreamReader sx = StreamReader (@”c:\PilelO.txt “);
MessageBox.Show (sr.ReadToEnd() .ToString()) ;
sr.Close ();
StreamWriter Class
Used to write data to a stream.
StreanWriter sw = new StreanWriter (@”C:\FileIO. txt”) ;
sw. Write (“Pransflower") ;
sw.Close() i
—
‘SunBeam Institute of Information Technology, Pune, Karad Page 18SUNBEAM
Institute of Information Technology
Serialization
Persistence is mapped by using serialization
Serialization is a process of converting data into portable format
— Cc
[meer }- [Sa
Serialization Process
‘Type of Serialization
Binary Serialization
‘System.Runtime.Serialization.Formatters.Binary
XML Serialization
‘System.Xml.Serialization
SOAP Serialization
‘System.Runtime. Serialization.Formatters.Scap
[NonSerialized] attribute
Indicates that a field of a serializable class should not be serialized
To reduce the size of the serialized object add the [NonSerialized] attribute to the member
For example
[NonSerialized] public string Name;
‘SunBeam Institute of Information Technology, Pune, Karad Page 194
|
SUNBEAM A
Institute of Information Technology
Plscement itiatve
Garbage Collection
com
Programmatically implement reference counting and handle circular
references
CH
Programmatically uses the new operator and delete operator
Visual Basic
Automation memory management
Manual vs. Automatic Memory Management
‘Common problems with manual memory management
Failure to release memory
Invalid references to freed memory
‘Automatic memory management provided with .NET Runtime
Eases programming task
Eliminates a potential source of bugs.
Garbage Collector
Manages the allocation and release of memory for your application.
Application Roots.
Identifies live object references or application roots and builds their graph
2, Objects not in the graph are not accessible by the application and hence considered
garbage.
Finds the memory that can be reclaimed.
Move all the live object to the bottom of the heap, leaving free space at the top.
Looks for contiguous block objects & then shifts the non-garbage objects down in
memory.
6. Updates pointers to point new locations.
a
‘SunBeam Institute of Information Technology, Pune, Karad Page 20
I.- SUNBEAM a
institute of Information Technology fas 4 :
Placement
[geepetationt |
[>= “Objects that
survive cc
Generation 0 |
| “Short lived
objects
Resource Management Types
plicit Resource Management
With Finalize () method.
Will be required when an object encapsulates unmanaged resources like: file, window or
network connection.
Explicit Resource Management
By implementing IDisposable Interface and writing Dispose method.
Implicit Recourse Management with Finalization
Writing Destructors in C#:
Class car
(
~car () //destructor
{ // cleanup statements}
‘SunBeam Institute of Information Technology, Pune, Karad Page 21,m 4 :
SUNBEAM Af
Institute of Information Technology
Placement ri
Resource Management
Implement IDisposable Interface.
Defines Dispose () method to release allocated unmanaged resources.
— Clean up of unmanaged resources
Resoureetieoner = ae 9
f [eer
eho + Fle handles
Mp TF -Windownendos
1 Resoorcedaner
jemacneamene + Developer can explicit clean up
‘unmanaged resources
a cn
‘SunBeam Institute of Information Technology, Pune, Karad Page 22,