Professional Documents
Culture Documents
C# PDF
C# PDF
TM HIU NGN NG C# V
VIT MT NG DNG MINH HA
N TT NGIP
Li cm n
c th hon tt c bi n ny, trc tin phi k n cng sc ca thy
Nguyn Tn Trn Minh Khang. Chng em knh li cm n n thy tn tnh hng
dn v gip trong thi gian thc hin n ny.
Chng em xin t lng bit n su sc i vi gia nh ng vin, to iu kin
thc hin tt bi n. Xin cm n cha, m, anh, ch, em!
Chng em cng xin chn thnh cm n n cc thy c khoa Cng ngh thng tin
trng i hc Khoa hc T nhin Thnh ph H Ch Minh truyn t nhng kin
thc, kinh nghim qu bu cho chng em trong qu trnh hc tp ti trng.
Chng em cng xin chn thnh cm n n cc bn b gip ti liu, trao i hc
thut mi c th thc hin n ny. Xin gi li cm n n cc bn H Ngc Huy,
Trn Th Anh, Bi Thanh Tun...
Mc lc
Li cm n .......................................................................................................... ..........3
Mc lc........................................................................................................... ...............4
Tm tt ...................................................................................................................... ....1
Phn
1
Tm hiu ngn ng C#.............................................................................. .....................1
Chng 1 C# v .Net Framework............................................................................ ..2
1.1 Nn tng ca .NET .......................................................... ...............................2
1.2 .NET Framework........................................................................... ..................3
1.3 Bin dch v ngn ng trung gian (MSIL) .......................................... ............4
1.4 Ngn ng C#...................................................................... .............................5
Chng 2 Khi u.................................................................................. .................6
2.1 Lp, i tng v kiu.................................................................................. ...6
2.2 Pht trin Hello World............................................................................ ......8
Chng 3 Nhng c s ca ngn ng C#................................ ...............................12
3.1 Cc kiu............................................................................................ .............12
3.2 Bin v hng................................................................................. .................14
3.3 Biu thc......................................................................... ..............................16
3.4 Khong trng........................................................................ .........................16
3.5 Cu lnh................................................................................................... ......16
3.6 Ton t................................................................................................ ...........19
3.7 To vng tn............................................................................... ...................21
3.8 Ch th tin x l.............................................................................. ..............22
Chng 4 Lp v i tng.......................................................... ..........................24
4.1 nh ngha lp............................................................................. ..................24
4.2 To i tng............................................................... .................................25
4.3 S dng cc thnh vin tnh.................................................................. .........27
4.4 Hy i tng........................................................................................ ........29
4.5 Truyn tham s.................................................................... ..........................30
4.6 Np chng phng thc v hm dng....................................... ....................32
4.7 ng gi d liu vi property .................................................................... ...33
Chng 5 Tha k v a hnh............................................................................... ..35
Tm tt
ti ny tp trung tm hiu ton b cc khi nim lin quan n ngn ng C#.
Bi v C# c Microsoft pht trin nh l mt thnh phn ca khung ng dng
.NET Framework v hng Internet nn ti ny bao gm hai phn sau:
Phn 1: Tm hiu v ngn ng C#
Vic tm hiu bao gm c cc kin thc nn tng v cng ngh .NET Framework,
chun b cho cc khi nim lin quan gia C# v .NET Framework. Sau tm
hiu v b c php ca ngn ng ny, bao gm ton b tp lnh, t kha, khi
nim v lp trnh hng i tng theo C#, cc h tr lp trnh hng
component ... Sau cng l cch lp trnh C# vi ng dng Window cho my
bn v C# vi cc cng ngh hin i nh ASP.NET. ADO.NET, XML cho lp
trnh Web.
Phn 2: Xy dng mt ng dng
Phn ny l bo co v ng dng minh ha cho vic tm hiu trn. Tn ng
dng l Xy dng mt Website dy hc C#. y l ng dng Web ci t bng
ngn ng C# v ASP.NET. Trong ASP.NET c dng xy dng giao din
tng tc vi ngi dng; cn C# l ngn ng lp trnh bn di. ng dng c
thao tc c s d liu (Microsoft SQL Server) thng quan m hnh ADO.NET.
Phn 1
Tm hiu ngn ng C#
Chui
Chui
Chui
Thnh phn quan trng nht ca .NET Framework l CLR, n cung cp mi trng
cho ng dng thc thi, CLR l mt my o, tng t my o Java. CLR kch hot
i tng, thc hin kim tra bo mt, cp pht b nh, thc thi v thu dn chng.
Trong Hnh 1-1 tng trn ca CLR bao gm:
Cc lp c s
Cc lp d liu v XML
Cc lp cho dch v web, web form, v Windows form.
Cc lp ny c gi chung l FCL, Framework Class Library, cung cp API hng
i tng cho tt c cc chc nng ca .NET Framework (hn 5000 lp).
Cc lp c s tng t vi cc lp trong Java. Cc lp ny h tr cc thao tc nhp
xut, thao tc chui, vn bn, qun l bo mt, truyn thng mng, qun l tiu trnh
v cc chc nng tng hp khc
Trn mc ny l lp d liu v XML. Lp d liu h tr vic thao tc cc d liu
trn c s d liu. Cc lp ny bao gm cc lp SQL (Structure Query Language:
ngn ng truy vn c cu trc) cho php ta thao tc d liu thng qua mt giao tip
SQL chun. Ngoi ra cn mt tp cc lp gi l ADO.Net cng cho php thao tc
d liu. Lp XML h tr thao tc d liu XML, tm kim v din dch XML.
Trn lp d liu v XML l lp h tr xy dng cc ng dng Windows (Windows
forms), ng dng Web (Web forms) v dch v Web (Web services).
Chui
1.4 Ngn ng C#
C# l mt ngn ng rt n gin, vi khong 80 t kho v hn mi kiu d liu
dng sn, nhng C# c tnh din t cao. C# h tr lp trnh c cu trc, hng i
tng, hng thnh phn (component oriented).
Trng tm ca ngn ng hng i tng l lp. Lp nh ngha kiu d liu mi,
cho php m rng ngn ng theo hng cn gii quyt. C# c nhng t kho dnh
cho vic khai bo lp, phng thc, thuc tnh (property) mi. C# h tr y
khi nim tr ct trong lp trnh hng i tng: ng gi, tha k, a hnh.
nh ngha lp trong C# khng i hi tch ri tp tin tiu vi tp tin ci t nh
C++. Hn th, C# h tr kiu su liu mi, cho php su liu trc tip trong tp tin
m ngun. n khi bin dch s to tp tin su liu theo nh dng XML.
C# h tr khi nim giao din, interfaces (tng t Java). Mt lp ch c th k
tha duy nht mt lp cha nhng c th ci t nhiu giao din.
C# c kiu cu trc, struct (khng ging C++). Cu trc l kiu hng nh v b gii
hn.Cu trc khng th tha k lp hay c k tha nhng c th ci t giao
din.
C# cung cp nhng c trng lp trnh hng thnh phn nh property, s kin v
dn hng khai bo (c gi l attribute). Lp trnh hng component c h tr
bi CLR thng qua siu d liu (metadata). Siu d liu m t cc lp bao gm cc
phng thc v thuc tnh, cc thng tin bo mt .
Assembly l mt tp hp cc tp tin m theo cch nhn ca lp trnh vin l cc th
vin lin kt ng (DLL) hay tp tin thc thi (EXE). Trong .NET mt assembly l
mt on v ca vic ti s dng, xc nh phin bn, bo mt, v phn phi. CLR
cung cp mt s cc lp thao tc vi assembly.
C# cng cho truy cp trc tip b nh dng con tr kiu C++, nhng vng m
c xem nh khng an ton. CLR s khng thc thi vic thu dn rc t ng cc
i tng c tham chiu bi con tr cho n khi lp trnh vin t gii phng.
Chui
Chng 2 Khi u
Chng ny ta s to, bin dch v chy chng trnh Hello World bng ngn ng
C#. Phn tch ngn gn chng trnh gii thiu cc c trng chnh yu trong
ngn ng C#.
V d 2-1 Chng trnh Hello World
class HelloWorld
{
static void Main( )
{
// s dng i tng console ca h thng
System.Console.WriteLine("Hello World");
}
}
Sau khi bin dch v chy HelloWorld, kt qu l dng ch Hello World hin th
trn mn hnh.
Chui
2.1.2 Cc ghi ch
C# c ba kiu ghi ch trong c hai kiu rt quen thuc ca C++ l dng: "//" v
"/* */". Ngoi ra cn mt kiu ghi ch na s trnh by cc chng k.
V d 2-2 Hai hnh thc ghi ch trong C#
class HelloWorld
{
static void Main( ) // y l ghi trn mt dng
{
/* Bt u ghi ch nhiu dng
Vn cn trong ghi ch
Kt thc ghi ch bng */
System.Console.WriteLine("Hello World");
}
}
Chui
Chui
Chui
10
Chui
Cch dng trnh g ri hon ton ging vi trnh g ri trong VS 6.0. N cho php
ta dng li mt v tr bt k, cho ta kim tra gi tr tc thi bng cch di chuyn
chut n v tr bin. Ngoi ra, khi g ri ta cng c th xem gi tr cc bin thng
qua ca s Watch v Local.
chy trong ch g ri ta chn Debug Start hay nhn F5, mun chy tng
bc ta bm F11 v chy vt qua mt phng thc ta bm F10.
11
Chui
3.1 Cc kiu
C# buc phi khai bo kiu ca i tng c to. Khi kiu c khai bo r rng,
trnh bin dch s gip ngn nga li bng cch kim tra d liu c gn cho i
tng c hp l khng, ng thi cp pht ng kch thc b nh cho i tng.
C# phn thnh hai loi: loai d liu dng sn v loi do ngi dng nh ngha.
C# cng chia tp d liu thnh hai kiu: gi tr v tham chiu. Bin kiu gi tr
c lu trong vng nh stack, cn bin kiu tham chiu c lu trong vng nh
heap.
C# cng h tr kiu con tr ca C++, nhng t khi c s dng. Thng thng con
tr ch c s dng khi lm vic trc tip vi Win API hay cc i tng COM.
Kch thc
(byte)
M t - gi tr
Kiu .Net
byte
Byte
Khng du (0..255)
char
Char
M k th Unicode
bool
Boolean
sbyte
Sbyte
C du (-128 .. 127)
short
Int16
C du (-32768 .. 32767)
ushort
Uint16
Khng du (0 .. 65535)
int
Int32
C du (-2147483647 .. 2147483647)
12
Chui
uint
Uint32
Khng du (0 .. 4294967295)
float
Single
double
Double
decimal
Decimal
Int64
S nguyn c du (- 9223372036854775808 ..
9223372036854775807)
Uint64
long
ulong
8
8
Ngha
\
\
\\
\0
\a
\b
\f
\n
\r
\t
\v
du nhy n
du nhy i
du cho ngc \
Null
Alert
li v sau
Form feed
xung dng
v u dng
Tab ngang
Tab dc
13
Chui
3.2.2 Hng
Hng l mt bin nhng gi tr khng thay i theo thi gian. Khi cn thao tc trn
mt gi tr xc nh ta dng hng. Khai bo hng tng t khai bo bin v c thm
t kha const trc. Hng mt khi khi ng xong khng th thay i c na.
const int HANG_SO = 100;
Kt qu
Thu Hai = 0
Thu Bay = 5
14
Chui
3.2.4 Chui
Chui l kiu dng sn trong C#, n l mt chui cc k t n l. Khi khai bo
mt bin chui ta dng t kho string. V d khai bo mt bin string lu chui
"Hello World"
string myString = "Hello World";
3.2.5 nh danh
nh danh l tn m ngi lp trnh chn i din mt kiu, phng thc, bin,
hng, i tng ca h. nh danh phi bt u bng mt k t hay du _.
nh danh khng c trng vi t kho C# v phn bit hoa thng.
15
Chui
cng nh
x
32;
3.5 Cu lnh
Cng nh trong C++ v Java mt ch th hon chnh th c gi l mt cu lnh
(statement). Chng trnh gm nhiu cu lnh, mi cu lnh kt thc bng du ;.
V d:
int x; // l mt cu lnh
x = 23; // mt cu lnh khc
16
Chui
}
Kt qu:
In Main! Calling SomeMethod( )...
Greetings from SomeMethod!
Back in Main( ).
hoc
if ( biu thc logic )
khi lnh 1;
else
khi lnh 2;
Biu thc la chn l biu thc sinh ra tr nguyn hay chui. Switch s so snh
biu_thc_la_chn vi cc biu_thc_hng bit phi thc hin vi khi lnh
no. Lnh nhy nh break, goto thot khi cu switch v bt buc phi c.
17
Chui
int nQuyen = 0;
switch ( sQuyenTruyCap )
{
case Administrator:
nQuyen = 1;
break;
case Admin:
goto case Administrator;
default:
nQuyen = 2;
break;
}
3.5.3 Lnh lp
C# cung cp cc lnh lp ging C++ nh for, while, do-while v lnh lp mi
foreach. N cng h tr cc cu lnh nhy nh: goto, break, continue v return.
Khc vi while khi lnh s c thc hin trc, sau biu thc c kim tra.
Nu biu thc ng khi lnh li c thc hin.
18
Chui
3.6 Ton t
Cc php ton +, -, *, / l mt v d v ton t. p dng cc ton t ny ln cc bin
kiu s ta c kt qu nh vic thc hin cc php ton thng thng.
int a = 10;
int b = 20;
int c = a + b; // c = 10 + 20 = 30
C# cung cp cp nhiu loi ton t khc nhau thao tc trn cc kiu bin d liu,
c lit k trong bng sau theo tng nhm ng ngha.
Bng 3-3 Cc nhm ton t trong C#
Nhm ton t
Ton t
ngha
Ton hc
+ - * / %
Logic
Ghp chui
ghp ni 2 chui
Tng, gim
++, --
Dch bit
<< >>
Quan h
Gn
= += -= *= /= %= &=
|= ^= <<= >>=
php gn
Ch s
[]
p kiu
()
Indirection v
Address
* -> [] &
19
Chui
3.6.6 Th t cc ton t
i vi cc biu thc ton, th t u tin l th t c qui nh trong ton hc.
Cn th t u tin thc hin ca cc nhm ton t c lit k theo bng di y
Bng 3-4 Th t u tin ca cc nhm ton t (chiu u tin t trn xung)
Nhm ton t
Ton t
ngha
Primary (chnh)
Unary
+ - ! ~ ++x x (T)x
Nhn
* / %
Cng
+ -
cng, tr
Dch bt
<< >>
Quan h
Bng
== !=
bng, khc
&
V trn bit.
XOR
OR
20
Chui
iu kin AND
&&
iu kin OR
||
iu kin
?:
iu kin tng t if
Assignment
= *= /= %= += -= <<=
=>> &= ^= |=
ngha:
Nu biu thc iu kin ng th thc hin biu thc 1.
Nu sai th thc hin biu thc 2.
3.7 To vng tn
Nh c gii thch trong phn tch v d HelloWorld, vng tn l mt cch t chc
m ngun thnh cc nhm c ng ngha lin quan. V d:
Trong m hnh kin trc 3 lp (3 tng, ting Anh l 3 tier Architecture) chia mt
ng dng ra thnh 3 tng: tng giao din, tng nghip v v tng d liu
(Presentation, Bussiness v Data). Ta c th chia d n thnh 3 vng tn tng ng:
Presentation, Bussiness v Data. Cc vng tn ny cha cc lp thuc v tng ca
mnh.
Mt vng tn cha cc lp v cc vng tn con khc. Vy trong v d trn ta s to
mt vng tn chung cho ng dng l MyApplication v ba vng tn kia s l ba
vng tn con ca vng tn MyApplication. Cch ny gii quyt c trng hp
nu ta c nhiu d n m ch c 3 vng tn v dn n vic khng bit mt lp
thuc vng tn Data nhng khng bit thuc d n no.
S o c a y v u n g te n
M y A p p lic a t i o n
P r e s e n ta tio n
v u n g te n c o n
C a c l p
B u s s in e s s
v u n g te n c o n
C a c l p
D a ta
v u n g te n c o n
C a c l p
Vng tn con c truy xut thng qua tn vng tn cha cch nhau bng du chm.
khai bo vng tn ta s dng t kha namespace. V d di y l 2 cch khai
bo cc vng tn trong v d trn.
21
Chui
Cch 1
namespace MyApplication
{
namespace Presentation
{
// khai bo lp
// khai bo vng tn con
}
namespace Bussiness
{
// khai bo lp
// khai bo vng tn con
}
namespace Data
{
// khai bo lp
// khai bo vng tn con
}
}
Cch 2
namespace
{
// khai
// khai
}
namespace
{
// khai
// khai
}
namespace
{
// khai
// khai
}
MyApplication.Presentation
bo lp
bo vng tn con
MyApplication.Bussiness
bo lp
bo vng tn con
MyApplication.Data
bo lp
bo vng tn con
3.8 Ch th tin x l
Khng phi mi cu lnh u c bin dch cng lc m c mt s trong chng
c bin dch trc mt s khc. Cc cu lnh nh th ny gi l cc ch th tin
x l. Cc ch th tin x l c t sau du #.
22
Chui
#if DEBUG
// m ngun c bao gm trong chng trnh
// khi chy di ch debug
#else
// m ngun c bao gm trong chng trnh
// khi chy di ch khng debug
#endif
//... cc on m ngun khng nh hng tin x l
Trnh bin dch nhy n cc on tho iu kin tin bin dch bin dch trc.
3.8.2 Hy mt nh danh
Ta hy mt nh danh bng cch dng #undef. B tin x l duyt m ngun t
trn xung di, nn nh danh c nh ngha t #define, hy khi gp #undef
hay n ht chng trnh. Ta s vit l:
#define DEBUG
#if DEBUG
// m ngun c bin dch
#endif
#undef DEBUG
#if DEBUG
// m ngun s khng c bin dch
#endif
khi ny VS.NET cho php ng hoc m vng m ny. V d trn ang trng thi
m. Khi trng thi ng n vh sau
ng m mt on m
23
Chui
Chng 4 Lp v i tng
i tng l mt tr c th c to ra, lu gi v s dng. Trong C# tt c cc bin
u l i tng. Cc bin kiu s, kiu chui u l i tng. Mi mt i
tng u c cc bin thnh vin lu gi d liu v c cc phng thc (hm)
tc ng ln bin thnh vin. Mi i tng thuc v mt lp i tng no . Cc
i tng c cng lp th c cng cc bin thnh vin v phng thc.
4.1 nh ngha lp
nh ngha mt lp mi vi c php nh sau:
[attribute][b t truy xut] class nh danh [:lp c s]
{
thn lp
}
V d 4-5 Khai bo mt lp
public class Tester
{
public static int Main( )
{
...
}
}
24
Chui
Gii thch
public
Truy xut mi ni
protected
internal
protected internal
4.2 To i tng
To mt i tng bng cch khai bo kiu v sau dng t kho new to nh
trong Java v C++.
25
Chui
Gi tr mc nh
s (int, long, )
bool
false
char
\0 (null)
enum
Tham chiu
null
26
Chui
}
}
Kt qu:
11/16/2000 16:21:40
4.2.2 Khi to
Ta c th khi to gi tri cc bin thnh vin theo mun bng cch khi to n
trong constructor ca lp hay c th gn vo trc tip lc khai bo. Vi gi tr khi
to ny th khi mt i tng khai bo kiu ca lp ny th gi tr ban u l cc gi
tr khi to ch khng phi l gi tr mc nh.
27
Chui
{
public void SomeMethod(int firstParam, float secondParam)
{
Console.WriteLine(
"Here are the parameters received: {0}, {1}",
firstParam, secondParam);
}
}
public class Tester
{
static void Main( )
{
int howManyPeople = 5;
float pi = 3.14f;
MyClass mc = new MyClass( );
mc.SomeMethod(howManyPeople, pi);
}
}
Trong v d trn phng thc Main() l tnh v phng thc SomeMethod() khng
l tnh.
28
Chui
}
private static int instances = 0;
}
public class Tester
{
static void Main( )
{
Cat.HowManyCats( );
Cat frisky = new Cat( );
Cat.HowManyCats( );
Cat whiskers = new Cat( );
Cat.HowManyCats( );
}
}
Kt qu:
0 cats adopted
1 cats adopted
2 cats adopted
4.4 Hy i tng
Ging vi Java, C# cng cung cp b thu dn rc t ng n s ngm hy cc bin
khi khng dng. Tuy nhin trong mt s trng hp ta cng cn hy tng minh,
khi ch vic ci t phng thc Finalize(), phng thc ny s c gi bi b
thu dn rc. Ta khng cn phi gi phng thc ny.
4.4.1 Hy t ca C#
Hy t ca C# cng ging nh hy t trong C++. Khai bo mt hy t theo c
php:
~<nh danh>() {}
29
Chui
class Tester
{
public static void Main( )
{
using (Font theFont = new Font("Arial", 10.0f))
{
// s dng theFont
} // phng thc Dispose ca theFont c gi
Font anotherFont = new Font("Courier",12.0f);
using (anotherFont)
{
// s dng anotherFont
} // phng thc Dispose ca anotherFont c gi
}
}
30
Chui
Date =
Hour =
Minute
Second
}
// bin
private
private
private
private
private
private
dt.Day;
dt.Hour;
= dt.Minute;
= dt.Second;
}
public class Tester
{
static void Main( )
{
System.DateTime currentTime = System.DateTime.Now;
Time t = new Time(currentTime);
t.DisplayCurrentTime( );
int theHour = 0;
int theMinute = 0;
int theSecond = 0;
t.GetTime(ref theHour, ref theMinute, ref theSecond);
System.Console.WriteLine("Current time: {0}:{1}:{2}",
theHour, theMinute, theSecond);
}
}
Kt qu:
11/17/2000 13:41:18
Current time: 13:41:18
31
Chui
32
Chui
// trong thn ca mt hm
DocGia dgMoi = new DocGia();
// s dung property set
dgMoi.HoTen = "Nguyn Vn A";
// s dng property get
string ten = dgMoi.HoTen; //ten c gi tr "Nguyn Vn A"
33
Chui
}
// to mt c tnh
public int Hour
{
get { return hour; }
set { hour = value; }
}
// cc bin thnh vin kiu private
private int year;
private int month;
private int date;
private int hour;
private int minute;
private int second;
}
public class Tester
{
static void Main( )
{
System.DateTime currentTime = System.DateTime.Now;
Time t = new Time(currentTime);
t.DisplayCurrentTime( );
int theHour = t.Hour;
System.Console.WriteLine("\nRetrieved the hour: {0}\n",
theHour);
theHour++;
t.Hour = theHour;
System.Console.WriteLine("Updated the hour: {0}\n",
theHour);
}
}
4.7.3 Cc trng ch c
C# cung cp t kho readonly khai bo cc bin thnh vin. Cc bin khai bo
kiu ny ch cho php gn gi tr cho bin mt ln vo lc khi to qua constructor.
34
Chui
5.2 S k tha
Trong C#, mi quan h chi tit ho l mt kiu k tha. S k tha khng cho mang
ngha chi tit ho m cn mang ngha chung ca t nhin v mi quan h ny.
Khi ta ni rng ListBox k tha t Window c ngha l n chi tit ho Window.
Window c xem nh l lp c s (base class) v ListBox c xem l lp k tha
(derived class). Lp ListBox ny nhn tt c cc c tnh v hnh vi ca Window v
chi tit ho n bng mt s thuc tnh v phng thc ca n cn.
35
Chui
}
// ListBox k tha t Window
public class ListBox : Window
{
// thm tham s vo constructor
public ListBox(
int top,
int left,
string theContents):
base(top, left) // gi constructor c s
{
mListBoxContents = theContents;
}
// to mt phng thc mi bi v trong
// phng thc k tha c s thay i hnh vi
public new void DrawWindow( )
{
base.DrawWindow( ); // gi phng thc c s
System.Console.WriteLine ("Writing string to the listbox:
{0}", mListBoxContents);
}
private string mListBoxContents; // bin thnh vin mi
}
public class Tester
{
public static void Main( )
{
// to mt th hin c s
Window w = new Window(5,10);
w.DrawWindow( );
// to mt th hin k tha
ListBox lb = new ListBox(20,30,"Hello world");
lb.DrawWindow( );
}
}
Kt qu:
Drawing Window at 5, 10
Drawing Window at 20, 30
Writing string to the listbox: Hello world
36
Chui
5.2.2 Gi hm dng lp c s
Trong V d 5-4 lp ListBox tha k t Window v c hm dng ba tham s. Trong
hm dng ca ListBox c li gi n hm dng ca Window thng qua t kho
base nh sau:
public ListBox( int top, int left, string theContents):
base(top, left) // gi constructor c s
5.3 a hnh
a hnh l vic lp B tha k cc c tnh t lp A nhng c thm mt s ci t
ring. a hnh cng l cch c th dng nhiu dng ca mt kiu m khng quan
tm n chi tit.
37
Chui
38
Chui
{
Console.WriteLine("Writing string to the listbox: {0}",
listBoxContents);
}
private string listBoxContents; // new member variable
}
public class Button : Window
{
public Button( int top, int left): base(top, left)
{
}
// implement the abstract method
public override void DrawWindow( )
{
Console.WriteLine("Drawing a button at {0}, {1}\n", top, left);
}
}
public class Tester
{
static void Main( )
{
Window[] winArray = new Window[3];
winArray[0] = new ListBox(1,2,"First List Box");
winArray[1] = new ListBox(3,4,"Second List Box");
winArray[2] = new Button(5,6);
for (int i = 0;i < 3; i++)
{
winArray[i].DrawWindow( );
}
}
}
ngha s dng
39
Chui
Equals
GetHashCode
GetType
ToString
Finalize()
Xo sch b nh ti nguyn
MemberwiswClone
40
Chui
41
Chui
5.7 Lp lng
Lp c khai bo trong thn ca mt lp c gi l lp ni (inner class) hay lp
lng (nested class), lp kia gi l lp ngoi (outer class). Lp ni c thun li l
truy cp c trc tip tt c cc thnh vin ca lp ngoi. Mt phng thc ca
lp ni cng c th truy cp n cc thnh vin kiu private ca cc lp ngoi. Hn
na, lp ni n n trong lp ngoi so vi cc lp khc, n c th l thnh vin kiu
private ca lp ngoi. Khi lp ni (vd: Inner) c khai bo public, n s c truy
xut thng qua tn ca lp ngoi (vd: Outer) nh: Outer.Inner.
V d 5-9 Cch dng lp ni
using System;
using System.Text;
public class Fraction
{
public Fraction(int numerator, int denominator)
{
this.numerator=numerator;
this.denominator=denominator;
42
Chui
}
// Methods elided...
public override string ToString( )
{
StringBuilder s = new StringBuilder( );
s.AppendFormat("{0}/{1}",
numerator, denominator);
return s.ToString( );
}
internal class FractionArtist
{
public void Draw(Fraction f)
{
Console.WriteLine("Drawing the numerator: {0}",
f.numerator);
Console.WriteLine("Drawing the denominator: {0}",
f.denominator);
}
}
private int numerator;
private int denominator;
}
public class Tester
{
static void Main( )
{
Fraction f1 = new Fraction(3,4);
Console.WriteLine("f1: {0}", f1.ToString( ));
Fraction.FractionArtist fa = new Fraction.FractionArtist();
fa.Draw(f1);
}
}
43
Chui
N chuyn tham s lhs v pha tri ton t v rhs v pha phi ca ton t.
C php C# cho php np chng ton t thng qua vic dng t kho operator.
6.3 S hu ch ca cc ton t
Cc ton t c np chng c th gip cho on m ngun ca ta d nhn hn, d
qun l v trong sng hn. Tuy nhin nu ta qu lm dng a vo cc ton t qu
mi hay qu ring s lm cho chng trnh kh s dng cc ton t ny m i khi
cn c cc nhm ln v v na.
44
Chui
Bng cch np chng phng thc ny, ta cho php lp Fraction a hnh vi tt c
cc i tng khc. Ni dung ca Equals() ta cn phi m bo rng c s so snh
vi i tng Fraction khc. Ta vit nh sau:
public override bool Equals(object o)
{
if (! (o is Fraction) )
{
return false;
}
return this == (Fraction) o;
}
45
Chui
{
Console.WriteLine("In Fraction Constructor(int, int)");
this.numerator=numerator;
this.denominator=denominator;
}
public Fraction(int wholeNumber)
{
Console.WriteLine("In Fraction Constructor(int)");
numerator = wholeNumber;
denominator = 1;
}
public static implicit operator Fraction(int theInt)
{
System.Console.WriteLine("In implicit conversion to Fraction");
return new Fraction(theInt);
}
public static explicit operator int(Fraction theFraction)
{
System.Console.WriteLine("In explicit conversion to int");
return theFraction.numerator / theFraction.denominator;
}
public static bool operator==(Fraction lhs, Fraction rhs)
{
Console.WriteLine("In operator ==");
if (lhs.denominator == rhs.denominator &&
lhs.numerator == rhs.numerator)
{
return true;
}
// code here to handle unlike fractions
return false;
}
public static bool operator !=(Fraction lhs, Fraction rhs)
{
Console.WriteLine("In operator !=");
return !(lhs==rhs);
}
public override bool Equals(object o)
{
Console.WriteLine("In method Equals");
if (! (o is Fraction) )
{
return false;
}
return this == (Fraction) o;
}
public static Fraction operator+(Fraction lhs, Fraction rhs)
{
Console.WriteLine("In operator+");
if (lhs.denominator == rhs.denominator)
{
return new Fraction(lhs.numerator+rhs.numerator,
lhs.denominator);
}
// simplistic solution for unlike fractions
// 1/2 + 3/4 == (1*4) + (3*2) / (2*4) == 10/8
int firstProduct = lhs.numerator * rhs.denominator;
46
Chui
}
public class Tester
{
static void Main( )
{
//implicit conversion to Fraction
Fraction f1 = new Fraction(3);
Console.WriteLine("f1: {0}", f1.ToString( ));
Fraction f2 = new Fraction(2,4);
Console.WriteLine("f2: {0}", f2.ToString( ));
Fraction f3 = f1 + f2;
Console.WriteLine("f1 + f2 = f3: {0}", f3.ToString( ));
Fraction f4 = f3 + 5;
Console.WriteLine("f3 + 5 = f4: {0}", f4.ToString( ));
Fraction f5 = new Fraction(2,4);
if (f5 == f2)
{
Console.WriteLine("F5: {0} == F2: {1}", f5.ToString( ),
f2.ToString( ));
}
int k = (int)f4; //explicit conversion to int
Console.WriteLine("int: F5 = {0}", k.ToString());
}
}
47
Chui
Chng 7 Cu trc
Mt cu trc (struct) l mt kiu do ngi dng nh ngha, n tng t nh lp
nh nh hn lp.
48
Chui
}
}
Kt qu:
Loc1 location: 200, 300
In MyFunc loc: 50, 100
Loc1 location: 200, 300
7.2.2 Gi hm dng mc nh
Theo trn trnh by khi ta khng to bt k ny th khi to mt th hin ca cu
trc thng qua t kho new n s gi n constructor mc nh ca cu trc. Ni
dung ca constructor s t gi tr cc bin v 0.
49
Chui
50
Chui
51
Chui
hoc ta c th to mt th din ca giao din bng vic phn phi ti liu v kiu
ca giao din v sau s dng giao din truy cp nhng phng thc:
IStorable isDoc = (IStorable) doc;
isDoc.status = 0;
isDoc.Read( );
In this case, in Main( ) you know that Document is in fact an IStorable, so you can
take advantage of that knowledge. As stated earlier, you cannot instantiate an
interface directly. That is, you cannot say:
IStorable isDoc = new IStorable( );
52
Chui
8.2.2 Ton t is
Khi chng ta mun mt i tng c kh nng h tr giao din, theo nguyn tc l
chng ta phi gi phng thc tng ng ln. Trong C# c 2 phng thc h tr
cng vic ny.
C php nh sau:
expression is type
hay
if (doc is IStorable)
isinst ICompressible
brfalse.s IL_0039
ldloc.0
castclass ICompressible
stloc.2
ldloc.2
callvirt instance void ICompressible::Compress( )
br.s IL_0043
ldstr "Compressible not supported"
8.2.3 Ton t as
Ton t as kt hp tc t is v s phn b cc thao tc bng vic kim tra s phn
b c hp l hay khng (gi tr s tr v l true) v sau y s hon tt cng vic.
Nu s phn b khng hp l (tc t is s tr v gi tr false), tc t as s tr v gi
tr null. C php ca vic khai bo:
expression as type
53
Chui
{
Document doc = new Document("Test Document");
IStorable isDoc = doc as IStorable;
if (isDoc != null)
isDoc.Read( );
else
Console.WriteLine("IStorable not supported");
ICompressible icDoc = doc as ICompressible;
if (icDoc != null)
icDoc.Compress( );
else
Console.WriteLine("Compressible not supported");
}
isinst ICompressible
stloc.2
ldloc.2
brfalse.s IL_0034
ldloc.2
callvirt instance void ICompressible::Compress( )
54
Chui
}
public class Tester
{
static void Main( )
55
Chui
{
// create a document object
Document theDoc = new Document("Test Document");
// p kiu c th gi IStorable.Read()
IStorable isDoc = theDoc as IStorable;
if (isDoc != null)
{
isDoc.Read( );
}
// p kiu c th gi ITalk.Read()
ITalk itDoc = theDoc as ITalk;
if (itDoc != null)
{
itDoc.Read( );
}
theDoc.Read( );
theDoc.Talk( );
}
}
Kt qu:
Creating document with: Test Document
Implementing IStorable.Read
Implementing ITalk.Read
Implementing IStorable.Read
Implementing ITalk.Talk
56
Chui
57
Chui
V d nh:
int[] myIntArray;
9.1.2 Gi tr mc nh
Gi s c on m sau:
/*1*/ int[] myArray;
/*2*/ maArray = new int[5];
/*3*/ Button[] myButtonArray;
/*4*/ myButtonArray = new Button[5];
dng /*1*/ khai bo bin myArray l mt mng kiu int. Khi ny bin myArray c
gi tr l null do cha c khi to. Dng /*2*/ khi to bin myArray, cc phn t
trong mng c khi to bng gi tr mc nh l 0. Dng /*3*/ tng t /*1*/
nhng Button thuc kiu tham chiu (reference type). Dng /*4*/ khi to bin
myButtonArray, cc phn t trong mng khng c khi to (gi tr "khi to" l
null). S dng bt k phn t no ca mng cng gy li cha khi to bin.
58
Chui
59
Chui
60
Chui
}
}
Kt qu:
DisplayVals
DisplayVals
DisplayVals
DisplayVals
DisplayVals
DisplayVals
DisplayVals
DisplayVals
DisplayVals
5
6
7
8
1
2
3
4
5
v d nh:
int [,] myRectangularArray;
9.2.4 Lp System.Array
Lp Array c rt nhiu hm hu ch, n lm cho mng trong C# "thng minh" hn
nhiu ngn ng khc. Chng c h tr nh l cc phng thc c dng sn
nh trng hp string. Hai phng thc quan trong nht ca lp System.Array l
Sort() v Reverse().
61
Chui
9.3 Indexers
Indexer tng t nh Property, tuy c khc nhau mt cht v ngha. Xt mt v d
m phng mt quyn sch c nhiu chng
// Property
public Chuong[] DsChuong
{
get{ return m_dsChuong; }
}
62
Chui
}
public string Ten
{
get { return m_sTen; }
set { m_sTen = value; }
}
public string NoiDung
{
get { return m_sNoiDung; }
set { m_sNoiDung = value; }
}
} // ht class Chuong
// Ci t lp Sach
public class Sach
{
private string m_sTen;
private ArrayList m_dsChuong;
public Sach()
{
m_sTen = "";
m_dsChuong = new ArrayList();
}
public Sach(string sTen)
{
m_sTen = sTen;
m_dsChuong = new ArrayList();
}
public string Ten
{
get { return m_sTen; }
set
{
if ( value == null )
throw new ArgumentNullException();
}
m_sTen = value;
}
// indexer th nht c mt tham s kiu int
public Chuong this[int index]
{
get
{
if ( index < 0 || index > m_dsChuong.Count - 1 )
return null;
return (Chuong)m_dsChuong[index];
}
set
{
if ( index < 0 || index > m_dsChuong.Count - 1 )
throw new ArgumentOutOfRangeException();
}
m_dsChuong[index] = value;
63
Chui
64
Chui
ngha
IEnumerable
ICollection
IComparer
IList
IDictionary
IDictionaryEnumerator
9.6 Hng i
Hng i (queue) l mt ti cha hot ng theo c ch FIFO (First in first out vo trc ra trc). Cng ging nh ta i xp hng mua v xem phim, nu ta vo
trc mua v th ta s c mua v trc.
Hng i l mt tp hp tt cho vic ta s dng qun l ngun ti nguyn c gii
hn. V d nh ta gi i nhng thng ip n ti nguyn, m ti nguyn th ch c
th gii quyt cho mt thng ip. Do chng ta phi to mt hng i nhng
65
Chui
9.7 Stacks
Stack l ti cha hot ng theo c ch LIFO (Last in first out - vo sau ra trc).
Hai phng thc c bn trong vic thm hoc xa Stack l:Push( ) v Pop( ). Ngoi
ra Stack cn c phng thc Peek( ), tng t nh Pop() nhng khng xa b phn
t ny.
Cc lp ArrayList, Queue v Stack u c nhng phng thc ging nhau nh
CopyTo( ) v ToArray( ) dng sao chp nhng phn t vo trong mt mng.
Trong trng hp Stack th phng thc CopyTo( ) s sao chp nhng phn t vo
mt mng mt chiu tn ti, v ni dung chng s ghi ln v tr bt u m
chng ta ch nh. Phng thc ToArray( ) tr v mt mng mi vi ni dung l
nhngphn t trong stack.
9.8 Dictionary
Dictionary l tn gi chung cho cc ti cha lu tr cc phn t theo quan h
kha/gi tr. iu ny c ngha l tng ng vi mt "kha", ta tm c mt v ch
duy nht mt "gi tr" tng ng.Ni cch khc l mt "gi tr" c mt "kha" duy
nht khng trng vi bt k "kha" ca gi tr khc.
Mt lp mun l mt Dictionary th ci t giao din IDictionary. Lp Dictionary
mun c s dng trong cu lnh foreach th ci t giao din
IDictionaryEnumerator.
Dictionary thng c dng nht l bng bm (Hashtable).
Bng bm
Hashtable l cu trc d liu c mc tiu ti u ha vic tm kim. .et Framework
cung cp lp Hashtable ci t cu trc d liu ny.
Mt i tng c dng nh "kha" phi ci t hay tha k phng thc
Object.GetHashCode() v Object.Equals() (cc lp th vin .NET Framework hin
nhin tha iu kin ny). Mt iu kin na l i tng ny phi immutable (d
liu cc trng thnh vin khng thay i) trong lc ang l kha.
66
Chui
Chng 10 Chui
Chui (string) trong C# l mt kiu dng sn nh cc kiu int, long, c y
tnh cht mm do, mnh m v d dng. Mt i tng chui trong C# l mt hay
nhiu k t Unicode khng th thay i th t. Ni cch khc l cc phng thc
p dng ln chui khng lm thay i bn thn chui, chng ch to mt bn sao c
sa i, chui gc vn gi nguyn.
khai bo mt i tng chui, s dng t kha string; i tng ny tht s
trng vi i tng System.String trong th vin lp .NET Framework. Vic s
dng hai i tng ny l nh nhau trong mi trng hp.
Khai bo lp System.String nh sau:
public sealed class String:IComparable,ICloneable,Iconvertible
10.1 To chui mi
Cch n gin nht to mt bin kiu chui l khai bo v gn mt chui cho n
string sChuoi = "Khai bo v gn mt chui";
67
Chui
Gii thch
Empty
Compare()
CompareOrdinal()
Concat()
Copy()
Equals()
Format()
Intern()
IsInterned()
Join()
Chars
Indexer ca chui
Length
Chiu di chui (s k t)
Clone()
Tr v mt chui
CompareTo()
CopyTo()
EndsWith()
Equals()
Insert()
LastIndexOf()
PadLeft()
PadRight()
Remove()
Xa mt s k t
Split()
StartsWith()
SubString()
Ly mt chui con
ToCharArray()
ToLower()
ToUpper()
Trim()
TrimEnd()
68
Chui
Thnh vin
Gii thch
TrimStart()
Ch : v tr rn chui bt u t v tr s 0
Chiu di chui
bit s k t ca chui, dng thuc tnh Length
string s = "Xin cho";
int l = s.Length; // l = 8
69
Chui
M t
V d
Kt qu
C hoc c
Tin t (Currency)
string.Format("{0:C}", 2.5);
$2.50
string.Format("{0:C}", -2.5);
($2.50)
D hoc d
Decimal
string.Format("{0:D5}", 25);
00025
E hoc e
string.Format("{0:E}", 250000);
2.500000E+005
F hoc f
string.Format("{0:F2}", 25);
25.00
(Fixed-point)
string.Format("{0:F0}", 25);
25
G hoc g
General
string.Format("{0:G}", 2.5);
2.5
N hoc n
S (Number)
string.Format("{0:N}", 2500000);
2,500,000.00
X hoc x
H s 16 (Hexadecimal)
string.Format("{0:X}", 250);
FA
string.Format("{0:X}", 0xffff);
FFFF
70
Chui
Phng thc
Gii thch
Capacity
Chars
Length
MaxCapacity
Append()
AppendFormat()
EnsureCapacity()
Insert()
Remove()
Replace()
Ly/thit t s k t ti a chui c th lu gi
Indexer
Kch thc chui
Ly s k t ti a lp c th lu gi
Thm mt i tng vo cui chui
nh dng chui tham s, sau thm chui ny vo cui
Xc nh chui c th lu gi ti thiu mt lng k t khng
Chn mt i tng vo chui ti v tr
Xa mt s k t trong chui
Thay mt k t/chui con bng k t/chui con mi
71
Chui
Chng 11 Qun l li
C# qun l li v cc trng thi bt thng bng bit l (exception). Mt bit l l
mt i tng cha cc thng tin v s c bt thng ca chng trnh.
iu quan trng trc ht l phi phn bit r s khc nhau gia bug, error v bit
l. Bug l li v mt lp trnh do chnh lp trnh vin khng kim sot c m
ngun. Bit l khng th sa cc bug. Mc d bug s pht sinh (nm) mt bit l,
chng ta khng nn da vo cc bit l sa cc bug, m nn vit li m ngun
cho ng.
Error l li gy ra bi ngi dng. Chng hn nh ngi dng nhp mt con s thay
v phi nhp cc k t ch ci. Mt error cng nm ra mt bit l, nhng ta c th
ngn chn bng cch bt ly li ny, yu cu ngi dng chnh sa cho n khi hp
l. Bt c khi no c th, error nn c tin on trc v ngn chn.
Ngay c khi cc bug c sa, cc error c tin on ht th vn cn nhiu
tnh hung khng th lng trc nh: h thng ht b nh hay chng trnh
ang truy cp mt tp tin khng tn ti. Chng ta khng th ngn chn c bit
l nhng c li c th qun l c chng chng khng lm gy ng dng.
Khi chng trnh gp phi tnh hung trn, chng hn ht b nh, n s nm (pht
sinh) mt bit l. Khi mt bit l c nm ra, hm ang thc thi s b tm dng v
vng nh stack s c duyt ngc cho n khi gp trnh gii quyt bit l.
iu ny c ngha l nu hm hin hnh khng c trnh gii quyt bit l th hm s
b ngt v hm gi s c c hi gii quyt li. Nu khng c hm gi no gii
quyt bit l th bit l s c nm cho CLR gii quyt. iu ny ng ngha vi
vic chng trnh s b dng mt cch bt thng.
Trnh qun l li (exception handler) l mt on m c thit k gii quyt cc
bit l c nm ra. Trnh gii quyt li c ci t trong khi lnh bt u bi t
kha catch{}. Mt cch l tng th khi bit l c bt v gii quyt th chng
trnh tip tc thc thi v vn c gii quyt. Ngay c trong trng hp chng
trnh khng th tip tc c th bng cch bt bit l ta vn cn mt c hi in (hoc
ghi li thnh tp tin) cc thng bo li v kt thc chng trnh mt m p.
Nu trong hm c nhng on m phi c thc thi bt chp c hay khng c xy
ra bit l (nh on m gii phng cc ngun lc c cp pht), on m ny nn
c b trong khi lnh finnally{}.
72
Chui
11.1 Nm v bt bit l
Trong C# chng ta c th nm bt k mt i tng no thuc lp hay lp con ca
lp System.Exception (vit tt l Exception). Vng tn System khai bo sn
nhiu lp bit l hu ch chng hn nh ArgumentNullException,
InValidCastException, OverflowException
73
Chui
in
at
in
at
in
...exceptions01.cs:line 26
Programming_CSharp.Test.Func1( )
...exceptions01.cs:line 20
Programming_CSharp.Test.Main( )
...exceptions01.cs:line 12
74
Chui
Console.WriteLine(
"Exception caught and handled.");
}
Console.WriteLine("Exit Func2...");
}
Kt qu:
Enter Main...
Enter Func1...
Enter Func2...
Entering try block...
Exception caught and handled.
Exit Func2...
Exit Func1...
Exit Main...
11.1.2.1 Sa cha li lm
Trong v d 11-2, lnh bt catch ch n gin thng bo rng mt bit l c
bt v qun l. Trong ng dng thc t, chng ta s vit cc on m gii quyt li
y. V d nu ngi dng c m mt tp ch c, ta hn cho gi mt phng
thc cho php ngi dng thay i thuc tnh tp tin. Nu trng hp ht b nh, ta
hn cho ngi dng c hi ng cc ng dng khc. Nu tt c u tht bi, khi
lnh catch s cho in cc thng bo m t chi tit li ngi dng bit r vn .
Khi mt bit l xy ra, khi try ngng thc thi ngay lp tc v quyn c trao cho
khi lnh catch. N s khng bao gi quay tr li khi try v v th khng th in
dng lnh thot khi try. Sau khi hon tt khi lnh catch, cc dng lnh sau
khi catch c thc thi tip tc.
Khng c khi catch, vng nh stack c duyt ngc, nhng nu c khi
catch vic ny s khng xy ra. Bit l c gii quyt, khng cn li na,
75
Chui
76
Chui
77
Chui
Kt qu:
DivideByZeroException caught!
Trong v d ny, DoDivide() s khng cho php chia mt s cho 0 hay chia 0 cho
s khc. N s nm ra bit l DivideByZeroException nu ta c chia cho
khng. Nu ta em chia 0 cho s khc, s khng c bit l thch hp: v chia khng
cho mt s l mt php ton hp l v khng nn nm bt k bit l no. Tuy nhin
gi s trong v d ny ta khng mun em 0 chia cho s khc v s nm ra bit l
ArithmeticException.
Khi mt bit l c nm ra, CLR tm kim trnh gii quyt bit l theo theo trnh
t, v chn trnh gii quyt ph hp vi bit l. Khi chy chng trnh vi a = 5
v b = 7, kt qu l:
5 / 7 = 0.7142857142857143
78
Chui
79
Chui
Trong v d ny dng thng bo Close file here lun lun xut hin, cho d bit
l c xy ra hay khng.
Ghi ch: khi lnh finally c th c to m khng cn khi catch,
nhng bt buc phi c khi try. Khng th dng cc lnh break,
continue, return v goto trong khi finally.
80
Chui
{
Console.WriteLine("Unknown exception caught");
}
finally
{
Console.WriteLine ("Close file here.");
}
}
public double DoDivide(double a, double b)
{
if (b == 0)
{
DivideByZeroException e = new DivideByZeroException();
e.HelpLink = "http://www.libertyassociates.com";
throw e;
}
if (a == 0)
throw new ArithmeticException( );
return a / b;
}
}
}
Kt qu:
Open file here
DivideByZeroException! Msg: Attempted to divide by zero.
HelpLink: http://www.libertyassociates.com
Here's a stack trace:
at Programming_CSharp.Test.DoDivide(Double a, Double b)
in c:\...exception06.cs:line 56
at Programming_CSharp.Test.TestFunc( )
in...exception06.cs:line 22
Close file here.
Trong trng hp ny kt qu s l:
DivideByZeroException! Msg:You tried to divide by zero which is not
meaningful
81
Chui
{
Console.WriteLine("\nDivideByZeroException! Msg: {0}",
e.Message);
Console.WriteLine("\nHelpLink: {0}", e.HelpLink);
Ta c kt qu cui cng.
11.3 Cc bit l t to
Vi cc bit l c th ty bin thng bo do CLR cung cp, thng cho hu ht
cc ng dng. Tuy nhin s c lc ta mun thm nhiu dng thng tin hn cho i
tng bit l, khi ta phi t to ly cc bit l mong mun. Bit l t to bt buc
tha k t lp System.Exception. V d 11-7 m t cch to mt bit l mi.
V d 11-7. T to bit l
using System;
namespace Programming_CSharp
{
public class MyCustomException : System.ApplicationException
{
public MyCustomException(string message) : base(message)
{
}
}
public class Test
{
public static void Main( )
{
Test t = new Test( );
t.TestFunc( );
}
public void TestFunc( )
{
try
{
Console.WriteLine("Open file here");
double a = 0;
double b = 5;
Console.WriteLine("{0}/{1}={2}", a, b, DoDivide(a,b));
Console.WriteLine("This line may or may not print");
}
catch (System.DivideByZeroException e)
{
Console.WriteLine("\nDivideByZeroException! Msg: {0}",
e.Message);
Console.WriteLine("\nHelpLink: {0}\n", e.HelpLink);
}
catch (MyCustomException e)
{
Console.WriteLine("\nMyCustomException! Msg: {0}",
e.Message);
82
Chui
}
// do the division if legal
public double DoDivide(double a, double b)
{
if (b == 0)
{
DivideByZeroException e = new DivideByZeroException();
e.HelpLink = "http://www.libertyassociates.com";
throw e;
}
if (a == 0)
{
MyCustomException e = new MyCustomException(
"Can't have zero divisor");
e.HelpLink =
"http://www.libertyassociates.com/NoZeroDivisor.htm";
throw e;
}
return a / b;
}
83
Chui
84
Chui
}
public void DangerousFunc2( )
{
try
{
DangerousFunc3( );
}
// nu bt c bit l DivideByZeroException thc hin
// vi cng vic sa li v nm ra bit l tng qut
catch (System.DivideByZeroException e)
{
Exception ex = new Exception(
"E2 - Func2 caught divide by zero",e);
throw ex;
}
}
public void DangerousFunc3( )
{
try
{
DangerousFunc4( );
}
catch (System.ArithmeticException)
{
throw;
}
catch (System.Exception)
{
Console.WriteLine("Exception handled here.");
}
}
public void DangerousFunc4( )
{
throw new DivideByZeroException(
"E1 - DivideByZero Exception");
}
}
}
Kt qu:
E3 - Custom Exception Situation!
Retrieving exception history...
E2 - Func2 caught divide by zero
E1 - DivideByZeroException
85
Chui
C php trn nm cng mt loi bit l cho khi try bn ngoi (ch cn t kha
throw)
DangerousFunc2() s bt c bit l ny, n s nm ra mt bit l mi thuc
kiu Exception. Khi khi to bit l ny, ta truyn cho n hai tham s: thng bo
E2 - Func2 caught divide by zero, v bit l c lm bit l ni.
DangerousFunc1() bt bit l ny, lm vi cng vic no , sau to mt bit
l c kiu MyCustomException. Tng t nh trn khi khi to bit l ta truyn
cho n hai tham s: thng bo E3 - Custom Exception Situation!, v bit
V ta c kt qu
Retrieving exception history...
E2 - Func2 caught divide by zero
E1 - DivideByZero Exception
86
Chui
87
Chui
88
Chui
{
}
89
Chui
90
Chui
}
// dogs are ordered by weight
public static comparison WhichDogComesFirst( Object o1,
Object o2 )
{
Dog d1 = (Dog) o1;
Dog d2 = (Dog) o2;
return d1.weight > d2.weight ? theSecondComesFirst :
theFirstComesFirst;
}
public override string ToString( )
{
return weight.ToString( );
}
private int weight;
}
91
Chui
}
}
// phng thc sp th t ngc (gim) cc i tng
// theo th t do chnh chng qui nh.
public void ReverseSort( WhichIsFirst theDelegatedFunc)
{
if (theDelegatedFunc(thePair[0],thePair[1]) ==
comparison.theFirstComesFirst )
{
object temp = thePair[0];
thePair[0] = thePair[1];
thePair[1] = temp;
}
}
// kt hp hai hm ToString() ca hai i tng
public override string ToString( )
{
return thePair[0].ToString( ) + ", " +
thePair[1].ToString( );
}
// mng gi hai i tng
private object[] thePair = new object[2];
}
public class Dog
{
public Dog(int weight)
{
this.weight=weight;
}
// ch c sp theo trng lng
public static comparison WhichDogComesFirst( object o1,
object o2)
{
Dog d1 = (Dog) o1;
Dog d2 = (Dog) o2;
return d1.weight > d2.weight ?
comparison.theSecondComesFirst :
comparison.theFirstComesFirst;
}
public override string ToString()
{
return weight.ToString();
}
private int weight;
}
public class Student
{
public Student(string name)
{
this.name = name;
}
// sinh vin sp theo th t tn
public static comparison WhichStudentComesFirst( object o1,
object o2 )
{
Student s1 = (Student) o1;
92
Chui
}
public override string ToString( )
{
return name;
}
private string name;
}
public class Test
{
public static void Main( )
{
// to hai i tng sinh vin v hai i tng ch
// y chng vo 2 i tng Pair
Student Jesse = new Student("Jesse");
Student Stacey = new Student ("Stacey");
Dog Milo = new Dog(65);
Dog Fred = new Dog(12);
Pair studentPair = new Pair(Jesse,Stacey);
Pair dogPair = new Pair(Milo, Fred);
Console.WriteLine("studentPair\t\t\t: {0}",
studentPair.ToString( ));
Console.WriteLine("dogPair\t\t\t\t: {0}",
dogPair.ToString( ));
// to th hin ca delegate
Pair.WhichIsFirst theStudentDelegate =
new Pair.WhichIsFirst(Student.WhichStudentComesFirst);
Pair.WhichIsFirst theDogDelegate =
new Pair.WhichIsFirst(Dog.WhichDogComesFirst);
// sp xp s dng delegate
studentPair.Sort(theStudentDelegate);
Console.WriteLine("After Sort studentPair\t\t: {0}",
studentPair.ToString( ));
studentPair.ReverseSort(theStudentDelegate);
Console.WriteLine("After ReverseSort studentPair\t:{0}",
studentPair.ToString( ));
dogPair.Sort(theDogDelegate);
Console.WriteLine("After Sort dogPair\t\t: {0}",
dogPair.ToString( ));
dogPair.ReverseSort(theDogDelegate);
Console.WriteLine("After ReverseSort dogPair\t: {0}",
dogPair.ToString( ));
}
}
Kt qu:
studentPair : Jesse, Stacey
dogPair : 65, 12
After Sort studentPair : Jesse, Stacey
After ReverseSort studentPair : Stacey, Jesse
After Sort dogPair : 12, 65
After ReverseSort dogPair : 65, 12
93
Chui
Chng trnh test to ra hai i tng Student v hai i tng Dog, sau a
chng vo ti cha Pair. Hm khi to ca Student nhn vo tn sinh vin c
hm khi to Dog nhn vo trng lng ca ch.
Student Jesse = new Student("Jesse");
Student Stacey = new Student ("Stacey");
Dog Milo = new Dog(65);
Dog Fred = new Dog(12);
Pair studentPair = new Pair(Jesse,Stacey);
Pair dogPair = new Pair(Milo, Fred);
Console.WriteLine("studentPair\t\t\t:{0}",studentPair.ToString());
Console.WriteLine("dogPair\t\t\t\t: {0}", dogPair.ToString( ));
94
Chui
v thay th bng
public static Pair.WhichIsFirst OrderStudents
{
get{ return new Pair.WhichIsFirst(WhichStudentComesFirst); }
}
95
Chui
96
Chui
DoEffect
DoEffect
DoEffect
DoEffect
97
Chui
{
}
{
Console.WriteLine("Blurring image");
public static void Filter( )
Console.WriteLine("Filtering image");
}
public static void Sharpen( )
{
Console.WriteLine("Sharpening image");
}
public static void Rotate( )
{
Console.WriteLine("Rotating image");
}
public void ProcessImages( )
{
for (int i = 0;i < numEffectsRegistered;i++)
{
arrayOfEffects[i]( );
}
}
// cc bin thnh vin
private DoEffect[] arrayOfEffects;
private Image image;
private int numEffectsRegistered = 0;
}
// lp kim th
public class Test
{
public static void Main( )
{
Image theImage = new Image( );
// khng giao din lm n gin vn
ImageProcessor theProc = new ImageProcessor(theImage);
theProc.AddToEffects(theProc.BlurEffect);
theProc.AddToEffects(theProc.FilterEffect);
theProc.AddToEffects(theProc.RotateEffect);
theProc.AddToEffects(theProc.SharpenEffect);
theProc.ProcessImages( );
}
}
}
Kt qu:
An image created
Blurring image
Filtering image
Rotating image
Sharpening image
98
Chui
12.1.5 Multicasting
Multicasting l cch gi hai phng thc thng qua mt delegate n.
tng t nh dng:
myMulticastDelegate = myMulticastDelegate + Transmitter;
99
Chui
V d 12-3. Kt hp cc delegate
using System;
namespace Programming_CSharp
{
public class MyClassWithDelegate
{
// khai bo delegate
public delegate void StringDelegate(string s);
}
public class MyImplementingClass
{
public static void WriteString(string s)
{
Console.WriteLine("Writing string {0}", s);
}
public static void LogString(string s)
{
Console.WriteLine("Logging string {0}", s);
}
public static void TransmitString(string s)
{
Console.WriteLine("Transmitting string {0}", s);
}
}
public class Test
{
public static void Main( )
{
// nh ngha ba i tng StringDelegate
MyClassWithDelegate.StringDelegate Writer,Logger,Transmitter;
// nh ngha mt SringDelegate khc
// hnh ng nh mt multicast delegate
MyClassWithDelegate.StringDelegate myMulticastDelegate;
// khi to 3 delegate u tin,
// truyn vo cc phng thc nh ng gi
Writer = new MyClassWithDelegate.StringDelegate(
MyImplementingClass.WriteString);
Logger = new MyClassWithDelegate.StringDelegate(
MyImplementingClass.LogString);
Transmitter = new MyClassWithDelegate.StringDelegate(
MyImplementingClass.TransmitString);
// gi phng thc ca delegate Writer
Writer("String passed to Writer\n");
// gi phng thc ca delegate Logger
Logger("String passed to Logger\n");
// gi phng thc ca delegate Transmitter
Transmitter("String passed to Transmitter\n");
// thng bo kt ni hai deleagte
100
Chui
}
Kt qu:
Writing string String passed to Writer
Logging string String passed to Logger
Transmitting string String passed to Transmitter
myMulticastDelegate = Writer + Logger
Writing string First string passed to Collector
Logging string First string passed to Collector
myMulticastDelegate += Transmitter
Writing string Second string passed to Collector
Logging string Second string passed to Collector
Transmitting string Second string passed to Collector
myMulticastDelegate -= Logger
Writing string Third string passed to Collector
Transmitting string Third string passed to Collector
101
Chui
V d nh:
102
Chui
103
Chui
Hm Run c vng lp for v tn lun lun kim tra gi h thng. Nu thi gian
thay i n s thng bo n tt c cc subscriber.
u tin l ng trong 10 mili giy
Thread.Sleep(10);
nguyn CPU ca h thng. Sau khi ng 10 mili giy, kim tra gi hin hnh
System.DateTime dt = System.DateTime.Now;
Khong sau 100 ln kim tra , gi tr giy s tng. Phng thc s thng bo thay
i ny cho cc subscriber. thc hin iu ny, u tin to mt i tng
TimeInfoEventArgs mi.
if (dt.Second != second)
{
TimeInfoEventArgs timeInformation =
new TimeInfoEventArgs(dt.Hour,dt.Minute,dt.Second);
104
Chui
105
Chui
}
}
106
Chui
// to i tng TimeInfoEventArgs
// truyn cho subscriber
TimeInfoEventArgs timeInformation=new TimeInfoEventArgs(
dt.Hour,dt.Minute,dt.Second);
// nu c subscriber, thng bo cho chng
if (OnSecondChange != null)
{
OnSecondChange( this,timeInformation );
}
}
// cp nht
this.second
this.minute
this.hour =
trng thi
= dt.Second;
= dt.Minute;
dt.Hour;
}
}
private int hour;
private int minute;
private int second;
}
public class DisplayClock
{
// subscribe s kin SecondChangeHandler ca theClock
public void Subscribe(Clock theClock)
{
theClock.OnSecondChange +=
new Clock.SecondChangeHandler(TimeHasChanged);
}
// phng thc ci t hm delegated
public void TimeHasChanged( object theClock,
` TimeInfoEventArgs ti)
{
Console.WriteLine("Current Time: {0}:{1}:{2}",
ti.hour.ToString( ),
ti.minute.ToString( ),
ti.second.ToString( ));
}
}
public class LogCurrentTime
{
public void Subscribe(Clock theClock)
{
theClock.OnSecondChange +=
new Clock.SecondChangeHandler(WriteLogEntry);
}
// phng thc ny nn vit ln tp tin
// nhng n gin ta xut ra mn hnh console
public void WriteLogEntry(object theClock,TimeInfoEventArgs ti)
{
Console.WriteLine("Logging to file: {0}:{1}:{2}",
ti.hour.ToString( ),
ti.minute.ToString( ),
ti.second.ToString( ));
}
}
public class Test
107
Chui
{
public static void Main( )
{
// to ng h mi
Clock theClock = new Clock( );
// to mt displayClock
// subscribe vi clock va to
DisplayClock dc = new DisplayClock( );
dc.Subscribe(theClock);
// to i tng Log
// subscribe vi clock va to
LogCurrentTime lct = new LogCurrentTime( );
lct.Subscribe(theClock);
// bt u chy
theClock.Run( );
}
}
}
Kt qu:
Current Time: 14:53:56
Logging to file: 14:53:56
Current Time: 14:53:57
Logging to file: 14:53:57
Current Time: 14:53:58
Logging to file: 14:53:58
Current Time: 14:53:59
Logging to file: 14:53:59
Current Time: 14:54:0
Logging to file: 14:54:0
108
Chui
Chng 13 Lp trnh vi C#
Phn ny s gii thiu chi tit v cch vit cc chng trnh .NET, bao gm
Windows Forms v Web Forms. Ngoi ra, chng ta s kho st thm v cch tng
tc vi c s d liu (Database) v cc dch v Web (Web Services).
Quan im v kin trc .NET l to s d dng, thun tin khi pht trin cc phn
mm theo tnh hng i tng. Vi mc ch ny, tng trn cng ca kin trc
.NET c thit k bao gm hai phn: ASP.NET v Windows Form. ASP.NET
c dng cho hai mc ch chnh: hoc to cc ng dng Web vi Web Forms
hoc to cc i tng Web (Web Objects) khng c giao din ngi dng (User
Interface: UI) vi Web Services.
Ta s kho st chi tit cc mc chnh sau :
1. Cch to ra cc ng dng Windows c tnh chuyn nghip cao trong mi
trng pht trin Windows Form mt cch nhanh chng theo m hnh RAD
( Rapid Application Development ).
2. c th truy cp d liu trong cc h qun tr d liu, ta s tho lun chi tit
v ADO.NET v cch tng tc vi Microsoft SQL Server v cc trnh cung
cp d liu (Providers Data ) khc.
3. L s kt hp cng ngh RAD trong phn (1) v ADO.NET trong phn (2)
minh ha vic to ra cc ng dng Web vi Web Forms.
4. Khng phi tt c mi ng dng u c giao din ngi dng thn thin. Web
Services gip to cc ng dng nh vy, chng l nhng ng dng c tnh
phn phi, cung cp cc chc nng da trn cc nghi thc Web chun, thng
dng nht l XML v HTTP.
109
Chui
110
Chui
111
Chui
ta s thm hai i
this.Controls.Add (this.btnCancel);
this.Controls.Add (this.lblOutput);
Sau khi ta nh ngha hm bt s kin click trn Button, ta s vit m thi hnh
cho hm ny. Ta s dng hm tnh ( static ) Exit() ca lp Application kt thc
ng dng :
protected void btnCancel_Click( object sender, System.EventArgs e)
{
Application.Exit();
}
112
Chui
public HandDrawnClass( )
{
// To cc i tng
this.lblOutput = new System.Windows.Forms.Label ( );
this.btnCancel = new System.Windows.Forms.Button ( );
// Gn tiu cho Form
this.Text = "Hello World";
// Hiu chnh Label
lblOutput.Location = new System.Drawing.Point(16,24);
lblOutput.Text = "Hello World!";
lblOutput.Size = new System.Drawing.Size (216, 24);
// Hiu chnh Button
btnCancel.Location = newSystem.Drawing.Point(150,20);
btnCancel.Size = new System.Drawing.Size (112, 32);
btnCancel.Text = "&Cancel";
// ng k trnh qun l s kin
btnCancel.Click +=
new System.EventHandler (this.btnCancel_Click);
113
Chui
114
Chui
115
Chui
116
Chui
117
Chui
16);
//
// lblOutput
//
this.lblOutput.Font = new System.Drawing.Font("Arial",
15.75F, System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,((System.Byte)(0)));
this.lblOutput.Location =
new System.Drawing.Point(24,
this.lblOutput.Name = "lblOutput";
this.lblOutput.Size = new System.Drawing.Size(136, 48);
this.lblOutput.TabIndex = 0;
this.lblOutput.Text = "Hello World";
// btnCancel
this.btnCancel.Location = new System.Drawing.Point(192, 208);
this.btnCancel.Name = "btnCancel";
this.btnCancel.TabIndex = 1;
this.btnCancel.Text = "Cancel";
this.btnCancel.Click +=
new System.EventHandler( this.btnCancel_Click );
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.AddRange(new System.Windows.Forms.Control[]{
this.btnCancel,
this.lblOutput});
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
private void btnCancel_Click(object sender, System.EventArgs e)
{
118
Chui
Application.Exit( );
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main( )
{
Application.Run(new Form1( ));
}
119
Chui
120
Chui
Sau khi to giao din xong, ta t thuc tnh CheckBoxes cho cy bn tri c tn
tvwSource thnh true, cn cy bn phi c tn tvwTargetDir thnh false, thc
hin ta n gin ch chn v sa i trn ca s thuc tnh ca tng i tng. Khi
ta nhn p ln bt k iu khin no th t ng Visual Studio .NET s pht sinh
ra m tng ng bt s kin ca iu khin v t con tr ( Cursor ) vo ngay
ti hm , ta nhn p vo Button Cancel v b sung m nh sau :
protected void btnCancel_Click( object sender, System.EventArgs e)
{
Application.Exit( );
}
C 2 tham s :
TreeView tvw: iu khin cy cn y d liu vo
Bool isSource: c xc nh l d liu y cho cy. Nu isSource
l true th cy s lit k c tp tin v th mc, false th ch c
tp tin.
121
Chui
FillDirectoryTree(tvwSource, true);
FillDirectoryTree(tvwTargetDir, false);
i tng TreeNode
iu khin TreeView c mt thuc tnh Nodes. thuc tnh ny nhn vo mt i
tng TreeNodeCollection , i tng ny thc cht l mt mng cha cc i
tng TreeNode, mi mt TreeNodel mt nt trn cy.
Trc tin ta cn khi to cy v rng :
tvw.Nodes.Clear( );
Tip theo ta tin hnh duyt trn mi th mc con ca i tng TreeNode gc trn,
lm iu ny ta gi hm GetSubDirectoriesNodes( ), hm ny cn nhn vo cc
i s : TreeNode gc, tn ca n v c xc nh l c y c tp tin vo cy hay
khng.
if (isSource)
{
GetSubDirectoryNodes(ndRoot, ndRoot.Text, true);
}
else
{
GetSubDirectoryNodes(ndRoot, ndRoot.Text, false);
}
122
Chui
123
Chui
Hm SetCheck() s tin hnh thc hin qui trn nt hin hnh, hm gm hai
tham s : nt cn nh du v c xc nh l nh du hay b nh du chn, nu
thuc tnh Count bng khng ( ngha l nt ny l nt l ) th ta s nh du chn
cho nt . Nu khng ta gi qui li hm SetCheck() :
private void SetCheck(TreeNode node, bool check)
{
node.Checked = check;
foreach (TreeNode n in node.Nodes)
{
if (node.Nodes.Count == 0)
{
node.Checked = check;
}
else
{
SetCheck(n,check);
}
}
}
124
Chui
if (theFullPath.EndsWith("\\"))
{
theFullPath =theFullPath.Substring(0,theFullPath.Length-1);
}
txtTargetDir.Text = theFullPath;
125
Chui
Nu khng l nt l, ta s lp qui tm nt l :
else
{
foreach (TreeNode n in node.Nodes)
GetCheckedFiles(n,fileNames);
}
126
Chui
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Drawing;
System.IO;
System.Windows.Forms;
127
Chui
/// <remarks>
/// chp tp tin ng dng minh ha cho Windows Form
/// </remarks>
namespace FileCopier
{
/// <summary>
/// Form minh ha cho ng dng Windows Form
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
/// <summary>
/// lp bn trong ca lp Form1, so snh 2 tp tin
/// </summary>
public class FileComparer : IComparer
{
public int Compare (object f1, object f2)
{
FileInfo file1 = (FileInfo) f1;
FileInfo file2 = (FileInfo) f2;
if (file1.Length > file2.Length)
{
return -1;
}
if (file1.Length < file2.Length)
{
return 1;
}
return 0;
}
}
public Form1( )
{
InitializeComponent( );
// y d liu vo cy bn tri v bn phi
FillDirectoryTree(tvwSource, true);
FillDirectoryTree(tvwTargetDir, false);
}
/// <summary>
/// phng thc ny dng y d liu vo cy
/// </summary>
private void FillDirectoryTree(TreeView tvw, bool isSource)
{
// trc khi y d liu vo cy, ta phi xa b cc nt
// hin ang tn ti trn cy.
tvw.Nodes.Clear( );
// ly v danh sch cc a logic trn my tnh
// sau y chng vo lm nt gc ca cy
string[] strDrives = Environment.GetLogicalDrives( );
// Duyt qua cc a, dng khi try/catch bt bt
// k li no xy ra trn a, nu a hp l th ta
// thm vo lm nt gc cho cy.
// a khng hp l s khng thm vo cy : a mm hay
// CD trng ...
128
Chui
129
Chui
/// </summary>
TreeNode subNode = new TreeNode(dirSub.Name);
parentNode.Nodes.Add(subNode);
// lp qui hm GetSubDirectoryNodes().
GetSubDirectoryNodes(
subNode,dirSub.FullName,getFileNames);
}
if (getFileNames)
{
// ly mi tp tin thuc nt
FileInfo[] files = dir.GetFiles( );
// thm cc tp tin v nt con
foreach (FileInfo file in files)
{
TreeNode fileNode = new TreeNode(file.Name);
parentNode.Nodes.Add(fileNode);
}
}
}
/// <summary>
/// im vo chnh ca ng dng.
/// </summary>
[STAThread]
static void Main( )
{
Application.Run(new Form1( ));
}
/// <summary>
/// to ra mt danh sch c th t cc tp tin c chn ,
/// chp chng sang cy bn phi
/// </summary>
private void btnCopy_Click(object sender,
System.EventArgs e)
{
// ly v danh sch tp tin
ArrayList fileList = GetFileList( );
// tin hnh chp tp tin
foreach (FileInfo file in fileList)
{
try
{
lblStatus.Text = "Copying " + txtTargetDir.Text +
"\\" + file.Name + "...";
Application.DoEvents( );
file.CopyTo(txtTargetDir.Text + "\\" +
file.Name,chkOverwrite.Checked);
}
catch // (ta khng lm g y c)
{
}
}
lblStatus.Text = "Done.";
Application.DoEvents( );
130
Chui
}
/// <summary>
/// bt s kin kt thc ng dng
/// </summary>
private void btnCancel_Click(object sender, System.EventArgs e)
{
Application.Exit( );
}
/// <summary>
/// bt s kin xa b cc nt c chn trn cy bn tri
/// </summary>
private void btnClear_Click( object sender, System.EventArgs e)
{
// ly v nt gc trn cy bn tri v
// tin hnh lp qui
foreach (TreeNode node in tvwSource.Nodes)
{
SetCheck(node, false);
}
}
/// <summary>
/// m bo ngi dng mun xa nt
/// </summary>
private void btnDelete_Click(object sender, System.EventArgs e)
{
// xc nhn xa
System.Windows.Forms.DialogResult result = MessageBox.Show(
"Are you quite sure?", // thng ip
"Delete Files", // tiu
MessageBox.Buttons.OKCancel, // nt nhn
MessageBox.Icon.Exclamation, // biu tng
MessageBoxDefaultButton.Button2); // nt mc nh
// nu ng xa
if (result == System.Windows.Forms.DialogResult.OK)
{
// duyt danh sch cc tp tin v xo cc tp tin
/ c chn
ArrayList fileNames = GetFileList( );
foreach (FileInfo file in fileNames)
{
try
{
// cp nht nhn
lblStatus.Text = "Deleting " +
txtTargetDir.Text + "\\" + file.Name + "...";
Application.DoEvents( );
file.Delete( );
}
catch (Exception ex)
{
// hp thoi thng bo
MessageBox.Show(ex.Message);
131
Chui
}
}
lblStatus.Text = "Done.";
Application.DoEvents( );
}
/// <summary>
/// ly ng dn y ca nt c chn v gn vo
/// iu khin TextBox txtTargetDir
/// </summary>
private void tvwTargetDir_AfterSelect( object sender,
System.Windows.Forms.TreeViewEventArgs e)
{
// ly ng dn y ca nt
string theFullPath = GetParentString(e.Node);
// nu n khng l nt l, ta s xa 2 k t cui cng
// i, v y l du //
if (theFullPath.EndsWith("\\"))
{
theFullPath =
theFullPath.Substring(0,theFullPath.Length-1);
}
// gn ng dn cho iu khin TextBox
txtTargetDir.Text = theFullPath;
}
/// <summary>
/// nh du chn nt hin hnh v cc nt con ca n
/// </summary>
private void tvwSource_AfterCheck(object sender,
System.Windows.Forms.TreeViewEventArgs e)
{
SetCheck(e.Node,e.Node.Checked);
}
/// <summary>
/// lp qui vic nh du chn hay loi b du chn trn
/// nt trun vo da vo c check
/// </summary>
private void SetCheck(TreeNode node, bool check)
{
// set this node's check mark
node.Checked = check;
// tm tt c cc nt con ca nt
foreach (TreeNode n in node.Nodes)
{
// nu l nt l th ta nh du chn hoc khng chn
if (node.Nodes.Count == 0)
node.Checked = check;
// nu khng l l th ta lp qui
else
SetCheck(n,check);
}
}
132
Chui
133
Chui
Ta cng c th to su liu XML trc tip ngay trong Visual Studio .NET, bng
cch nhn chut phi ln biu tng ca d n v chn Properties hin ln hp
thoi thuc tnh ca d n (Property Pages), sau chn mc Configuration
Properties \ Build ri g tn tp tin su liu XML cn to ra vo dng XML
Document File. Khi bin dch d n, tp tin su liu XML s t ng c to ra
trong th mc cha d n. Di y l mt on m c trch ra t tp tin su liu
XML c to ra t ng dng FileCopier trn :
<?xml version="1.0"?>
<doc>
<assembly>
<name>FileCopier</name>
</assembly>
<members>
<member name="T:FileCopier.Form1">
<summary>
Form demonstrating Windows Forms implementation
</summary>
</member>
<member name="F:FileCopier.Form1.components">
<summary>
134
Chui
135
Chui
136
Chui
137
Chui
FileCopier.exe
Osd8c0.osd
138
Chui
139
Chui
140
Chui
141
Chui
142
Chui
143
Chui
144
Chui
DDataSet l thnh phn chnh cho c trng kt ni khng lin tc ca kin trc
ADO.NET. DataSet c thit k c th thch ng vi bt k ngun d liu no.
DataSet cha mt hay nhiu i tng DataTable m n c to t tp cc dng
v ct d liu, cng vi kho chnh, kha ngoi, rng buc v cc thng tin lin
145
Chui
146
Chui
147
Chui
14.5 Trnh
Providers)
cung
cp
liu
(.NET
Data
.NET Framework h tr hai trnh cung cp d liu l SQL Server .NET Data
Provider ( dnh cho phin bn SQL Server 7.0 ca Microsoft tr ln ) v OLE DB
.NET Data Provider ( dnh cho cc h qun tr c s d liu khc ) truy cp vo
c s d liu.
Hnh 14-29 So snh SQL Server .NET Data Provider v the OLE DB .NET Data
Provider
148
Chui
Ta s duyt qua tng dng ca bng bng vng lp foreach ly v tng DataRow
mt, sau s truy cp n trng cn ly d liu thng qua tn ct, ri thm vo
ListBox.
foreach (DataRow dataRow in dataTable.Rows)
{
lbCustomers.Items.Add(
dataRow["CompanyName"] +
" (" + dataRow["ContactName"] + ")" );
}
Sau y l on m y ca ng dng :
using
using
using
using
using
using
using
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
System.Data.SqlClient;
namespace ProgrammingCSharpWinForm
{
public class ADOForm1 : System.Windows.Forms.Form
{
private System.ComponentModel.Container components;
private System.Windows.Forms.ListBox lbCustomers;
public ADOForm1( )
{
InitializeComponent( );
// kt ni n my ch, c s d liu northwind
string connectionString =
"server=localhost; uid=sa; pwd=; database=northwind";
149
Chui
150
Chui
To i tng DataSet mi
DataSet dataSet = new DataSet( );
151
Chui
152
Chui
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
System.Data.SqlClient;
namespace ProgrammingCSharpWindows.Form
{
public class ADOForm3 : System.Windows.Forms.Form
{
private System.ComponentModel.Container components;
private System.Windows.Forms.DataGrid CustomerDataGrid;
public ADOForm3( )
{
InitializeComponent( );
// khi to chui kt ni v chui truy vn d liu
string connectionString =
"server=localComputer; uid=sa; pwd=;database=northwind";
string commandString =
"Select CompanyName, ContactName, ContactTitle, "
+ "Phone, Fax from Customers";
// to ra mt SqlDataAdapter v DataSet mi,
// y d liu cho DataSet
SqlDataAdapter DataAdapter =
new SqlDataAdapter(commandString, connectionString);
DataSet DataSet = new DataSet( );
DataAdapter.Fill(DataSet,"Customers");
// kt buc d liu ca DataSet cho li
CustomerDataGrid.DataSource=
DataSet.Tables["Customers"].DefaultView;
153
Chui
}
public override void Dispose( )
{
base.Dispose( );
components.Dispose( );
}
private void InitializeComponent( )
{
this.components = new System.ComponentModel.Container();
this.CustomerDataGrid =
new DataGrid();
CustomerDataGrid.BeginInit();
CustomerDataGrid.Location =
new System.Drawing.Point (8, 24);
CustomerDataGrid.Size = new System.Drawing.Size (656, 224);
CustomerDataGrid.DataMember = "";
CustomerDataGrid.TabIndex = 0;
CustomerDataGrid.Navigate +=
new NavigateEventHandler(this.dataGrid1_Navigate);
this.Text = "ADOFrm3";
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size (672, 273);
this.Controls.Add (this.CustomerDataGrid);
CustomerDataGrid.EndInit ( );
}
public static void Main(string[] args)
{
Application.Run(new ADOForm3());
}
}
154
Chui
System.Data.SqlClient.SqlConnection myConnection;
System.Data.DataSet myDataSet;
System.Data.SqlClient.SqlCommand myCommand;
System.Data.SqlClient.SqlDataAdapter DataAdapter;
Sau ta s m kt ni :
myConnection.Open( );
155
Chui
using
using
using
using
using
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
System.Data.SqlClient;
namespace ProgrammingCSharpWindows.Form
{
public class ADOForm1 : System.Windows.Forms.Form
{
private System.ComponentModel.Container components;
private System.Windows.Forms.DataGrid dataGrid1;
private System.Data.SqlClient.SqlConnection myConnection;
private System.Data.DataSet myDataSet;
private System.Data.SqlClient.SqlCommand myCommand;
private System.Data.SqlClient.SqlDataAdapter DataAdapter;
public ADOForm1( )
{
InitializeComponent( );
// to i tng connection v m n
string connectionString =
"server=Neptune; uid=sa; pwd=oWenmEany;" +
"database=northwind";
myConnection = new SqlConnection(connectionString);
myConnection.Open();
// to i tng DataSet mi
myDataSet = new DataSet( );
// to i tng command mi v gn cho i tng
// connectio v chui truy vn cho n
myCommand = new System.Data.SqlClient.SqlCommand( );
myCommand.Connection=myConnection;
myCommand.CommandText = "Select * from Customers";
// to i tng DataAdapter vi i tng Command va
// to trn, ng thi thc hin nh x bng d liu
DataAdapter = new SqlDataAdapter( );
DataAdapter.SelectCommand= myCommand;
DataAdapter.TableMappings.Add("Table","Customers");
// y d liu vo DataSet
DataAdapter.Fill(myDataSet);
// gn d liu vo li
dataGrid1.DataSource =
myDataSet.Tables["Customers"].DefaultView;
}
public override void Dispose()
{
base.Dispose();
components.Dispose();
}
156
Chui
157
Chui
Ta tin hnh to quan h cho hai bng bng cch gi hm khi to ca i tng
DataRelation, truyn vo cho n tn quan h v hai ct cn to quan h :
dataRelation =new System.Data.DataRelation("CustomersToOrders",
dataColumn1, dataColumn2);
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
System.Data.SqlClient;
namespace ProgrammingCSharpWindows.Form
{
public class ADOForm1 : System.Windows.Forms.Form
{
private System.ComponentModel.Container components;
private System.Windows.Forms.DataGrid dataGrid1;
private System.Data.SqlClient.SqlConnection myConnection;
private System.Data.DataSet myDataSet;
private System.Data.SqlClient.SqlCommand myCommand;
private System.Data.SqlClient.SqlCommand myCommand2;
158
Chui
159
Chui
base.Dispose( );
components.Dispose( );
160
Chui
161
Chui
162
Chui
Hin th chui thng bo cp nht dng d liu cho ngi dng bit. lm iu
ny ta s gi phng thc tnh DoEvents() ca i tng Application, hm ny s
gip sn mi li mn hnh vi thng ip hay cc thay i khc.
lblMessage.Text = "Updating " + targetRow["CompanyName"];
Application.DoEvents();
163
Chui
{
DataRow[] errorRows = theTable.GetErrors( );
foreach (DataRow theRow in errorRows)
msg = msg + theRow["CustomerID"];
}
}
lblMessage.Text = msg;
}
Tip theo hin th cu lnh truy vn cho ngi dng bit, v cp nht nhng thay
i cho DataSet u tin, ri hin th d liu mi ln i tng ListBox.
lblMessage.Text = DataAdapter.UpdateCommand.CommandText;
Application.DoEvents( );
DataSet.AcceptChanges( );
PopulateLB( );
Gi li dng cn xa dng lm thng ip hin th cho ngi dng bit trc khi
xa dng ny khi c s d liu.
string msg = targetRow["CompanyName"] + " deleted. ";,
164
Chui
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
System.Data.SqlClient;
namespace ProgrammingCSharpWindows.Form
{
public class ADOForm1 : System.Windows.Forms.Form
{
private System.ComponentModel.Container components;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.TextBox txtPhone;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox txtContactTitle;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.TextBox txtZip;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox txtCity;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox txtAddress;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtContactName;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtCompanyName;
165
Chui
private
private
private
private
private
private
private
private
private
private
System.Windows.Forms.Label label2;
System.Windows.Forms.TextBox txtCompanyID;
System.Windows.Forms.Label label1;
System.Windows.Forms.Button btnNew;
System.Windows.Forms.TextBox txtCustomerName;
System.Windows.Forms.Button btnUpdate;
System.Windows.Forms.Label lblMessage;
System.Windows.Forms.Button btnDelete;
System.Windows.Forms.ListBox lbCustomers;
SqlDataAdapter DataAdapter;
166
Chui
167
Chui
168
Chui
this.Controls.Add
this.Controls.Add
this.Controls.Add
this.Controls.Add
this.Controls.Add
this.Controls.Add
this.Controls.Add
this.Controls.Add
this.Controls.Add
this.Controls.Add
this.Controls.Add
this.Controls.Add
this.Controls.Add
this.Controls.Add
this.Controls.Add
this.Controls.Add
this.Controls.Add
this.Controls.Add
this.Controls.Add
(this.label7);
(this.txtZip);
(this.label6);
(this.txtCity);
(this.label5);
(this.txtAddress);
(this.label4);
(this.txtContactName);
(this.label3);
(this.txtCompanyName);
(this.label2);
(this.txtCompanyID);
(this.label1);
(this.btnNew);
(this.txtCustomerName);
(this.btnUpdate);
(this.lblMessage);
(this.btnDelete);
(this.lbCustomers);
}
// Qun l s kin nhn nt to mi (New)
protected void btnNew_Click( object sender, System.EventArgs e)
{
// to mt dng mi
DataRow newRow = dataTable.NewRow( );
newRow["CustomerID"] = txtCompanyID.Text;
newRow["CompanyName"] = txtCompanyName.Text;
newRow["ContactName"] = txtContactName.Text;
newRow["ContactTitle"] = txtContactTitle.Text;
newRow["Address"] = txtAddress.Text;
newRow["City"] = txtCity.Text;
newRow["PostalCode"] = txtZip.Text;
newRow["Phone"] = txtPhone.Text;
// thm mt dng mi vo bng
dataTable.Rows.Add(newRow);
// cp nht vo c s d liu
DataAdapter.Update(DataSet,"Customers");
// thng bo cho ngi dng bit cu truy vn thay i
lblMessage.Text = DataAdapter.UpdateCommand.CommandText;
Application.DoEvents( );
DataSet.AcceptChanges( );
// hin th li d liu cho iu khin ListBox
PopulateLB( );
// Xo trng cc TextBox
ClearFields( );
}
// Xa trng cc TextBox
private void ClearFields( )
{
txtCompanyID.Text = "";
169
Chui
txtCompanyName.Text = "";
txtContactName.Text = "";
txtContactTitle.Text = "";
txtAddress.Text = "";
txtCity.Text = "";
txtZip.Text = "";
txtPhone.Text = "";
}
// qun l s kin nht nt chn cp nht (Update)
protected void btnUpdate_Click( object sender, EventArgs e)
{
// ly v dng c chn trn ListBox
DataRow targetRow =
dataTable.Rows[lbCustomers.SelectedIndex];
// thng bo cho ngi bit dng cp nht
lblMessage.Text = "Updating " +
targetRow["CompanyName"];
Application.DoEvents( );
// hiu chnh dng
targetRow.BeginEdit( );
targetRow["CompanyName"] = txtCustomerName.Text;
targetRow.EndEdit( );
// ly v cc dng thay i
DataSet DataSetChanged =
DataSet.GetChanges(DataRowState.Modified);
// m bo khng c dng no c li
bool okayFlag = true;
if (DataSetChanged.HasErrors)
{
okayFlag = false;
string msg = "Error in row with customer ID ";
// kim tra li trn tng bng
foreach (DataTable theTable in DataSetChanged.Tables)
{
// nu bng c li th tm li trn dng c th
if (theTable.HasErrors)
{
// ly cc dng c li
DataRow[] errorRows = theTable.GetErrors( );
// duyt qua tng dng c li thng bo.
foreach (DataRow theRow in errorRows)
{
msg = msg + theRow["CustomerID"];
}
}
}
lblMessage.Text = msg;
}
// nu khng c li
if (okayFlag)
170
Chui
{
// trn cc thay i trong 2 DataSet thnh mt
DataSet.Merge(DataSetChanged);
// cp nht c s d liu
DataAdapter.Update(DataSet,"Customers");
// thng bo cu truy vn cho ngi dng
lblMessage.Text =
DataAdapter.UpdateCommand.CommandText;
Application.DoEvents( );
// cp nht DataSet v
// hin th d liu mi cho ListBox
DataSet.AcceptChanges( );
PopulateLB( );
}
else // nu c li
DataSet.RejectChanges( );
// qun l s kin xa
protected void btnDelete_Click( object sender, EventArgs e)
{
// ly v dng c chn trn ListBox
DataRow targetRow =
dataTable.Rows[lbCustomers.SelectedIndex];
// chun b thng bo cho ngi dng
string msg = targetRow["CompanyName"] + " deleted. ";
// xa dng c chn
dataTable.Rows[lbCustomers.SelectedIndex].Delete( );
// cp nht thay i cho DataSet
DataSet.AcceptChanges( );
// cp nht c s d liu
DataAdapter.Update(DataSet,"Customers");
// hin th li ListBox vi d liu thay i
PopulateLB( );
// thng bo cho ngi dng bit
lblMessage.Text = msg;
Application.DoEvents( );
}
public static void Main(string[] args)
{
Application.Run(new ADOForm1( ));
}
}
171
Chui
172
Chui
173
Chui
174
Chui
175
Chui
176
Chui
177
Chui
Hnh 15-40
178
Chui
Mc ch
CompareValidator
CustomValidator
RangeValidator
RegularExpressionvalidator
ValidationSummary
15.4 Mt s v d mu minh ha
Mt cch thun tin nht hc mt cng ngh mi chnh l da vo cc v d, v
vy trong phn ny chng ta s kho st mt vi v d minh ha cho phn l
thuyt ca chng ta. Nh ta bit, ta c th vit m qun l theo hai cch : hoc l
vit trong tp tin .cs hoc l vit trc tip trong trang cha m HTML. y d
tp trung vo cc v d ca chng ta, ta s vit m qun l trc tip trn trang
HTML.
179
Chui
<head>
// m qun l C# s c vit trong th <script> ny
<script language="C#" runat="server">
// trang s gi hm ny u tin, ta s thc hin kt buc
// trc tip trong hm ny
void Page_Load(Object sender, EventArgs e) {
Page.DataBind();
}
// ly gi tr ca thuc tnh thng qua thuc tnh // get
string custID{
get {
return "ALFKI";
}
}
int orderCount{
get {
return 11;
}
}
</script>
</head>
<body>
<h3><font face="Verdana"> Ket buoc khong dung DataSource
</font></h3>
<form runat=server>
Khach hang: <b><%# custID %></b><br>
So hoa don: <b><%# orderCount %></b>
</form>
</body>
</html>
180
Chui
}
}
</script>
</head>
<body>
181
Chui
182
Chui
183
Chui
c kiu l chui
DataColumn("Qty", typeof(string)));
DataColumn("Item", typeof(string)));
DataColumn("Price", typeof(string)));
}
else {
//nu bng c sn trong Session, ta s ly ra dng
Cart = (DataTable)Session["DG6_ShoppingCart"];
184
Chui
//sau khi hiu chnh d liu, ngi dng tin hnh cp nht public
void MyDataGrid_Update(Object sender, DataGridCommandEventArgs e) {
// ly d liu trn TextBox
string item = e.Item.Cells[1].Text;
string qty = ((TextBox)e.Item.Cells[2].Controls[0]).Text;
string price = ((TextBox)e.Item.Cells[3].Controls[0]).Text;
// y, do chng ta dng d liu gi lu trn b nh chnh, // nu
dng c s d liu th chng ta s tin hnh hiu chnh // trc tip
trong c s d liu bng cc cu truy vn :
// UPDATE, SELECT, DELETE
//xa dng c
CartView.RowFilter = "Item='"+item+"'";
if (CartView.Count > 0) {
CartView.Delete(0);
}
CartView.RowFilter = "";
185
Chui
OnUpdateCommand="MyDataGrid_Update"
AutoGenerateColumns="false"
>
// cc thng s hiu chnh trn ct, y ta ch cho ngi
// dng hiu chnh trn ct s lng v gi ha n
<Columns>
<asp:EditCommandColumn
EditText="Edit"
CancelText="Cancel"
UpdateText="Update"
ItemStyle-Wrap="false"
HeaderText="Edit Command Column"
HeaderStyle-Wrap="false"
/>
<asp:BoundColumn HeaderText="Item" ReadOnly="true"
DataField="Item"/>
<asp:BoundColumn HeaderText="Quantity" DataField="Qty"/>
<asp:BoundColumn HeaderText="Price" DataField="Price"/>
</Columns>
</asp:DataGrid>
</form>
</body>
</html>
Sau khi ngi dng chn nt Edit trn li, mn hnh ng dng s nh sau :
186
Chui
187
Chui
<html>
<head>
<script language="C#" runat=server>
// thay i ch hin th li bng cch chn 1 trong 3 mc
// trong hp thoi ListBox
void ListFormat_SelectedIndexChanged(Object Sender, EventArgs E )
{
valSum.DisplayMode = (ValidationSummaryDisplayMode)
ListFormat.SelectedIndex;
}
</script>
</head>
<body>
<h3><font face="Verdana">V d v xc nhn iu khin hp l
ValidationSummary</font></h3>
<p>
<form runat="server">
<table cellpadding=10><tr> <td>
<table bgcolor="#eeeeee" cellpadding=10><tr><td colspan=3>
<font face=Verdana size=2><b>Credit Card
Information</b></font></td></tr>
<tr>
<td align=right>
<font face=Verdana size=2>Card Type:</font></td>
<td>
// danh sch cc nt chn c bt li bi iu //khin xc nhn hp
l RequireFieldValidator1
<ASP:RadioButtonList id=RadioButtonList1 RepeatLayout="Flow"
runat=server>
<asp:ListItem>MasterCard</asp:ListItem>
<asp:ListItem>Visa</asp:ListItem>
</ASP:RadioButtonList>
</td>
//iu khin xc nhn hp l cho cc nt chn //RadioButtonList1
<td align=middle rowspan=1>
<asp:RequiredFieldValidator id="RequiredFieldValidator1"
ControlToValidate="RadioButtonList1"
ErrorMessage="Card Type. "
Display="Static"
InitialValue="" Width="100%" runat=server>
*
</asp:RequiredFieldValidator>
</td></tr>
<tr>
<td align=right>
<font face=Verdana size=2>Card Number:</font>
</td>
<td>
<ASP:TextBox id=TextBox1 runat=server />
</td>
<td>
188
Chui
189
Chui
<tr>
<td>
//nt nhn xc nh hp l
<ASP:Button id=Button1 text="Validate" runat=server /></td></tr>
</table>
</td>
<td valign=top>
<table cellpadding=20><tr><td>
//iu khin dng hin th cc li ln trang, //n s bt bt k
li no c pht sinh bi cc //iu khin DropDownList hin th
<asp:ValidationSummary ID="valSum" runat="server"
HeaderText="You must enter a value in the following fields:"
Font-Name="verdana"
Font-Size="12"
/>
</td></tr></table>
</td>
</tr>
</table>
<font face="verdana" size="-1">Select the type of validation summary
display you wish: </font>
//Danh sch lit k 3 cch hin th li
<asp:DropDownList id="ListFormat" AutoPostBack=true
OnSelectedIndexChanged="ListFormat_SelectedIndexChanged"
runat=server >
<asp:ListItem>List</asp:ListItem>
<asp:ListItem selected>Bulleted List</asp:ListItem>
<asp:ListItem>Single Paragraph</asp:ListItem>
</asp:DropDownList>
</form>
</body>
</html>
190
Chui
Hnh 15-46 Hin th li do b trng trn TextBox theo dng du chm trn Bullet
191
Chui
192
Chui
System;
System.Collections;
System.ComponentModel;
System.Data;
System.Diagnostics;
System.Web;
System.Web.Services;
namespace MathService
{
public class MathService :System.Web.Services.WebService
{
public MathService()
{
InitializeComponent();
}
#region Component Designer generated code
private IContainer components = null;
private void InitializeComponent()
{
}
193
Chui
[WebMethod]
public float Divide(float a, float b)
{
if (b==0) return -1;
return a / b;
}
By gi chng ta s vit m thc thi cho trang Web. Trang Web ca chng ta s gi
cc hm ca dch v tng ng vi cc php cng, tr, nhn, chia . Sau y l m
ca trang Web:
<%@ Import Namespace="MathService" %>
<html>
<script language="C#" runat="server">
float operand1 = 0;
float operand2 = 0;
public void Submit_Click(Object sender, EventArgs E)
{
try
{
operand1 = float.Parse(Operand1.Text);
operand2 = float.Parse(Operand2.Text);
194
Chui
}
catch (Exception) { /* b qua li nu c */ }
//to ra mt i tng dch v MathService c th truy cp n
//cc hm thnh vin ca chng.
MathService service = new MathService();
switch (((Control)sender).ID)
{
case "Add"
: Result.Text = "<b>Result</b> = " +
service.Add(operand1, operand2).ToString(); break;
case "Subtract" : Result.Text = "<b>Result</b> =
service.Subtract(operand1, operand2).ToString(); break;
"
"
case "Divide"
: Result.Text = "<b>Result</b> =
service.Divide(operand1, operand2).ToString(); break;
"
</script>
<body style="font: 10pt verdana">
<h4>Using a Simple Math Service
</h4>
<form runat="server">
<div
style="padding:15,15,15,15;backgroundcolor:beige;width:300;border-color:black;borderwidth:1;border-style:solid">
Operand 1:<br>
<asp:TextBox id="Operand1" Text="15" runat="server"
/><br>
Operand 2:<br>
<asp:TextBox
id="Operand2"
/><p>
Text="5"
runat="server"
<input
type="submit"
id="Add"
value="Add"
OnServerClick="Submit_Click" runat="server">
<input type="submit" id="Subtract" value="Subtract"
OnServerClick="Submit_Click" runat="server">
<input type="submit" id="Multiply" value="Multiply"
OnServerClick="Submit_Click" runat="server">
<input
type="submit"
id="Divide"
value="Divide"
OnServerClick="Submit_Click" runat="server">
<p>
<asp:Label id="Result" runat="server" />
</div>
</form>
</body>
</html>
195
Chui
17.1 Tp tin PE
Assembly c lu tr trn da t theo dng thc tp tin Portable Executable (PE).
Dng thc tp tin PE ca .NET cng ging nh tp tin PE bnh thng ca
Windows NT. Dng thc PE c ci t thnh dng thc tp tin DLL v EXE.
V mt logic, assembly cha ng mt hay nhiu module. Mi module c t
chc thnh mt DLL v ng thi mi module l mt cu thnh ca assembly. Cc
module t bn thn chng khng th chy c, cc module phi kt hp vi nhau
thnh assembly th mi c th lm c vic g hu ch.
17.2 Metadata
Metadata l thng tin c lu tr bn trong assembly vi mc ch l m t cc
kiu d liu, cc phng thc v cc thng tin khc v assembly. Do c cha
metadata nn assembly c kh nng t m t.
17.5 Manifest
Manifest chnh l mt thnh phn ca metadata. Manifest m t mt assembly cha
nhng g, v d nh: thng tin nhn dng (tn, phin bn), danh sch cc kiu d
196
Chui
liu, danh sch cc resource, danh sch cc assembly khc c assembly ny tham
chiu n,
197
Chui
17.8.2 Phin bn
Assembly chia s trong .NET c nh v bng tn duy nht (unique) v phin bn.
Phin bn c biu din bi 4 s phn cch bng du : v d nh 1:2:6:1246
S
S
S
S
198
Chui
17.8.3 Tn mnh
Mt tn mnh l mt chui cc k t hexa mang thuc tnh l duy nht trong ton
cu (globally unique). Ngoi ra chui cn c m ha bng thut ton kha
cng khai 1 bo m rng assembly khng b thay i v tnh hay c .
to ra tn mnh, mt cp kha cng khai-b mt c to ra cho assembly. Mt
m bm (hash code) c to ra t tn, ni dung ca cc tp tin bn trong assembly
v chui biu din kha cng khai. Sau m bm ny c m ha bng kha b
mt, kt qu m ha c ghi vo manifest. Qu trnh trn c gi l k xc nhn
vo assembly (signing the assembly).
Khi assembly c CLR np vo b nh, CLR s dng kha cng khai trong
manifest gii m m bm xc nh xem assembly c b thay i khng.
199
Chui
18.1 Attributes
Mt attribute l mt i tng, trong i tng cha mt mu d liu, m lp
trnh vin mun nh km vi mt phn t (element) no trong ng dng. Phn
t (element) m lp trnh vin mun nh km attribute gi l mc tiu (target) ca
attribute. V d attribute:
[NoIDispatch]
c nh km vi mt lp hay mt giao din ni rng lp ch (target class) nn
c tha k t giao din IUnknown ch khng phi tha k t IDispatch.
18.2.1 ch ca Attribute
Mi attribute ch ng hng n mt ch (target) m n khai bo. ch c th l
lp, giao din, phng thc Bng sau lit k tt c cc ch
Bng 17-12 Cc ch ca attribute
Loi
ngha
All
Assembly
Class
ClassMembers
200
Chui
Constructor
p dng vi hm dng
Delegate
Enum
Event
Field
Interface
Method
Module
Parameter
Property
ReturnValue
p dng cho tr tr v
Struct
201
Chui
18.3.2 t tn mt attribute
Lp trnh vin hon ton t do trong vic t tn cho attribute. Tuy nhin, compiler
ca .NET cn c thm kh nng t ni thm chui Attribute vo tn. iu c
ngha l nu lp trnh vin nh ngha mt attribute c tn l MyBugFix th khi
tm kim hoc truy xut attribute trn, lp trnh vin c th vit tn attribute:
MyBugFix hoc MyBugFixAttribute. Nu mt attribute c tn l
MyBugFixAttribute th lp trnh vin cng c th ghi tn attribute l
MyBugFix hoc MyBugFixAttribute.
V d:
[MyBugFix(123, "Jesse Liberty", "01/01/05", Comment="Off by one")]
i s kiu tn th c ci t nh l properties:
public string Comment
{
get { return comment; }
set { comment = value; }
}
202
Chui
18.4 Reflection
cho vic lu attribute trong metadata c ch, cn phi c c ch truy xut chng
vo lc chy. Cc lp trong vng tn (namespace) Reflection, cng vi cc lp
trong System.Type v System.TypeReference, cung cp s h tr truy xut
metadata.
Reflection l mt khi nim chung cho bt k thao tc no trong cc thao tc sau
y:
Xem xt metadata
Tm hiu kiu d liu (type discovery): lp, interface, phng thc, i s ca
phng thc, properties, event, field,
Ni kt tr cc phng thc v properties (late binding to methods and
properties)
To ra mt kiu d liu mi ngay trong lc thc thi. Lp trnh vin c th nh
ngha mt assembly mi ngay lc chy, c th lu xung da t dng li.
203
Chui
204
Chui
205
Chui
19.2 Context
Min ng dng (app domain) n lt n li c chia ra thnh cc context.
Context c th xem nh mt ranh gii m cc i tng bn trong context c cng
quy tc s dng (usage rules). Cc quy tc s dng nh: ng b ha giao dch
(synchronization transaction),
206
Chui
207
Chui
19.3 Remoting
Cng vi vic marshaling i tng vt qua ranh gii context v min ng dng,
i tng c th c marshaling vt qua ranh gii process v thm ch qua ranh
gii my - mng - my. Khi mt i tng c marshaling vt qua ranh gii
process hay my - mng my, n c gi l Remoted.
208
Chui
ng k kiu Singleton
RemotingConfiguration.RegisterWellKnownServiceType
( calcType, "theEndPoint",WellKnownObjectMode.Singleton );
System;
System.Runtime.Remoting;
System.Runtime.Remoting.Channels;
System.Runtime.Remoting.Channels.Http;
namespace Programming_CSharp
{
// implement the calculator class
public class Calculator : MarshalByRefObject, ICalc
{
public Calculator( )
{
Console.WriteLine("Calculator constructor");
}
// implement the four functions
public double Add(double x, double y)
{
Console.WriteLine("Add {0} + {1}", x, y);
return x+y;
}
public double Sub(double x, double y)
{
Console.WriteLine("Sub {0} - {1}", x, y);
return x-y;
}
public double Mult(double x, double y)
209
Chui
{
Console.WriteLine("Mult {0} * {1}", x, y);
return x*y;
}
210
Chui
namespace Programming_CSharp
{
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
public class CalcClient
{
public static void Main( )
{
int[] myIntArray = new int[3];
Console.WriteLine("Watson, come here I need you...");
// create an Http channel and register it
// uses port 0 to indicate won't be listening
HttpChannel chan = new HttpChannel(0);
ChannelServices.RegisterChannel(chan);
// get my object from across the http channel
MarshalByRefObject obj =
(MarshalByRefObject) RemotingServices.Connect
(typeof(Programming_CSharp.ICalc),
"http://localhost:65100/theEndPoint");
try
{
// cast the object to our interface
Programming_CSharp.ICalc calc =
obj as Programming_CSharp.ICalc;
// use the interface to call methods
double sum = calc.Add(3.0,4.0);
double difference = calc.Sub(3,4);
double product = calc.Mult(3,4);
double quotient = calc.Div(3,4);
// print the results
Console.WriteLine("3+4 = {0}", sum);
Console.WriteLine("3-4 = {0}", difference);
Console.WriteLine("3*4 = {0}", product);
Console.WriteLine("3/4 = {0}", quotient);
}
catch( System.Exception ex )
{
Console.WriteLine("Exception caught: ");
Console.WriteLine(ex.Message);
}
}
}
}
Kt xut pha client
Watson, come here I need you...
3+4 = 7
3-4 = -1
3*4 = 12
3/4 = 0.75
Kt xut pha server:
Calculator constructor
Press [enter] to exit...
Add 3 + 4
Sub 3 - 4
211
Chui
Mult 3 * 4
Div 3 / 4
thnh
RemotingServices. RegisterWellKnownServiceType(
"CalcServerApp","Programming_CSharp.Calculator",
"theEndPoint",WellKnownObjectMode.SingleCall );
212
Chui
213
Chui
214
Chui
Chng 20 Thread v S ng B
Thread l mt process nh cn cung cp kh nng multitasking trong mt ng
dng. Vng tn System.Threading cung cp nhiu lp v giao din h tr lp
trnh nhiu thread.
20.1 Thread
Thread thng c to ra khi bn mun lm ng thi 2 vic trong cng mt
thi im. Gi s ng dng ca bn ang tin hnh c vo b nh mt tp tin c
kch thc khong 500MB, trong lc ang c th d nhin ng dng khng th p
ng yu cu x l giao din. Gi s ngi dng mun ngng gia chng, khng
cho ng dng c tip tp tin ln na, do cn mt thread khc x l giao
din, lc ny khi ngi dng n nt Stop th ng dng p ng c yu cu trong
khi thread ban u vn ang c tp tin.
20.1.1 To Thread
Cch n gin nht l to mt th hin ca lp Thread. Contructor ca lp Thread
nhn mt tham s kiu delegate. CLR cung cp lp delegate ThreadStart nhm mc
ch ch n phng thc m bn mun thread mi thc thi. Khai bo delegate
ThreadStart nh sau:
public delegate void ThreadStart( );
215
Chui
t2.Join( );
Cu lnh trn bo cho b iu phi thread (ca h iu hnh) bit bn khng mun
b iu phi thread phn phi thi gian CPU cho thread thc thi cu lnh trn trong
thi gian 1 giy.
20.2 ng b ha (Synchronization)
Khi bn cn bo v mt ti nguyn, trong mt lc ch cho php mt thread thay i
hoc s dng ti nguyn , bn cn ng b ha.
ng b ha c cung cp bi mt kha trn i tng , kha s ngn cn
thread th 2 truy cp vo i tng nu thread th nht cha tr quyn truy cp i
tng.
Sau y l v d cn s ng b ha. Gi s 2 thread s tin hnh tng tun t 1
n v mt bin tn l counter.
int counter = 0;
Hm lm thay i gi tr ca Counter:
public void Incrementer( )
{
try
{
while (counter < 1000)
{
int temp = counter;
temp++; // increment
// simulate some work in this method
Thread.Sleep(1);
// assign the Incremented value
216
Chui
217
Chui
218
Chui
if (counter < 5)
{
Monitor.Wait(this);
}
Pulse() bo hiu cho CLR rng c s thay i trong trng thi monitor c th dn
n vic gii phng (tip tc chy) mt thread ang trong tnh trng ch i.
Khi thread hon tt vic s dng monitor, n gi hm Exit() tr monitor.
Monitor.Exit(this);
Source code v d:
namespace Programming_CSharp
{
using System;
using System.Threading;
class Tester
{
static void Main( )
{
// make an instance of this class
Tester t = new Tester( );
// run outside static Main
t.DoTest( );
}
public void DoTest( )
{
// create an array of unnamed threads
Thread[] myThreads = {
new Thread( new ThreadStart(Decrementer) ),
new Thread( new ThreadStart(Incrementer) ) };
// start each thread
int ctr = 1;
foreach (Thread myThread in myThreads)
{
myThread.IsBackground=true;
myThread.Start( );
myThread.Name = "Thread" + ctr.ToString( );
ctr++;
Console.WriteLine("Started thread {0}",myThread.Name);
Thread.Sleep(50);
}
// wait for all threads to end before continuing
foreach (Thread myThread in myThreads)
{
myThread.Join( );
}
// after all threads end, print a message
Console.WriteLine("All my threads are done.");
}
219
Chui
void Decrementer( )
{
try
{
// synchronize this area of code
Monitor.Enter(this);
// if counter is not yet 10
// then free the monitor to other waiting
// threads, but wait in line for your turn
if (counter < 10)
{
Console.WriteLine(
"[{0}] In Decrementer. Counter: {1}. Gotta Wait!",
Thread.CurrentThread.Name, counter);
Monitor.Wait(this);
}
while (counter >0)
{
long temp = counter;
temp--;
Thread.Sleep(1);
counter = temp;
Console.WriteLine("[{0}] In Decrementer. Counter: {1}.",
Thread.CurrentThread.Name, counter);
}
}
finally
{
Monitor.Exit(this);
}
}
void Incrementer( )
{
try
{
Monitor.Enter(this);
while (counter < 10)
{
long temp = counter;
temp++;
Thread.Sleep(1);
counter = temp;
Console.WriteLine("[{0}] In Incrementer. Counter: {1}",
Thread.CurrentThread.Name, counter);
}
// I'm done incrementing for now, let another
// thread have the Monitor
Monitor.Pulse(this);
}
finally
{
Console.WriteLine("[{0}] Exiting...",
Thread.CurrentThread.Name);
Monitor.Exit(this);
}
}
private long counter = 0;
220
Chui
}
}
Kt qu:
Started thread Thread1
[Thread1] In Decrementer.
Started thread Thread2
[Thread2] In Incrementer.
[Thread2] In Incrementer.
[Thread2] In Incrementer.
[Thread2] In Incrementer.
[Thread2] In Incrementer.
[Thread2] In Incrementer.
[Thread2] In Incrementer.
[Thread2] In Incrementer.
[Thread2] In Incrementer.
[Thread2] In Incrementer.
[Thread2] Exiting...
[Thread1] In Decrementer.
[Thread1] In Decrementer.
[Thread1] In Decrementer.
[Thread1] In Decrementer.
[Thread1] In Decrementer.
[Thread1] In Decrementer.
[Thread1] In Decrementer.
[Thread1] In Decrementer.
[Thread1] In Decrementer.
[Thread1] In Decrementer.
All my threads are done.
1
2
3
4
5
6
7
8
9
10
Counter:
Counter:
Counter:
Counter:
Counter:
Counter:
Counter:
Counter:
Counter:
Counter:
9.
8.
7.
6.
5.
4.
3.
2.
1.
0.
20.3.2 Deadlock
Gi s thread A nm monitor ca ti nguyn X v ang ch monitor ca ti
nguyn Y. Trong khi th thread B li nm monitor ca ti nguyn Y v ch
221
Chui
222
Chui
21.1 Tp tin v th mc
Cc lp cp trong chng ny thuc v vng tn System.IO. Cc lp ny bao
gm lp File m phng cho mt tp tin trn a, v lp Directory m phng
cho mt th mc trn a.
21.1.1 Lm vic vi th mc
Lp Directory c nhiu phng thc dnh cho vic to, di chuyn, duyt th
mc. Cc phng thc trong lp Directory u l phng thc tnh;v vy khng
cn phi to mt th hin lp Directory m c th truy xut trc tip t tn lp.
Lp DirectoryInfo l lp tng t nh lp Directory. N cung cc tt c cc
phng thc m lp Directory c ng thi b sung nhiu phng thc hu ch
hn cho vic duyt cu trc cy th mc. Lp DirectoryInfo tha k t lp
FileSystemInfo, v v vy cng tha k lp MarshalByRefObj. Lp
DirectoryInfo khng c phng thc tnh, v vy cn to mt th hin lp trc
khi s dng cc phng thc.
C mt khc bit quan trong gia Directory v DirectoryInfo l cc phng
thc ca lp Directory s c kim tra v bo mt mi khi c gi trong khi
i tng DirectoryInfo ch kim tra mt ln vo lc khi to, cc phng thc
v vy s thc hin nhanh hn.
Di y l bng lit k cc phng thc quan trng ca hai lp
Bng 20-13 Cc phng thc lp Directory
Phong thc
Gii thch
CreateDirectory()
Delete()
Xo th mc v cc ni dung ca n.
223
Chui
Exists( )
GetCreationTime( )
SetCreationTime( )
GetCurrentDirectory( )
SetCurrentDirectory( )
Tr v kt qu kiu logic, ng nu ng dn n th mc tn ti (c
ngha l th mc tn ti).
Ly/thit t ngy gi to th mc
Ly/thit t th mc hin hnh
GetDirectories( )
Ly v mt mng cc th mc con mt th mc
GetDirectoryRoot( )
Tr v th mc gc ca ng dn
GetFiles( )
GetLastAccessTime( )
SetLastAccessTime( )
GetLastWriteTime( )
SetLastWriteTime( )
GetLogicalDrives( )
GetParent()
Tr v th mc cha ca mt ng dn.
Move()
ngha
Attributes
CreationTime
Exists
Tr v ng nu th mc tn ti
Extension
FullName
LastAccessTime
LastWriteTime
Name
Tn th mc
Parent
Ly th mc cha
Root
Ly th mc gc ca ng dn.
Create( )
To mt th mc
CreateSubdirectory()
Delete( )
Xa mt th mc v ni dung ca n
GetDirectories( )
GetFiles( )
Ly danh mc cc tp tin ca th mc
GetFileSystemInfos()
MoveTo( )
224
Chui
Phong thc/property
ngha
Refresh( )
225
Chui
}
indentLevel--; // gim cp th mc
Kt qu (mt phn):
[2] logiscan [5/1/2001 3:06:41 PM]
[2] miitwain [5/1/2001 3:06:41 PM]
[1] Web [5/1/2001 3:06:41 PM]
[2] printers [5/1/2001 3:06:41 PM]
[3] images [5/1/2001 3:06:41 PM]
[2] Wallpaper [5/1/2001 3:06:41 PM]
363 directories found.
Gii thch
AppendText()
Copy()
Create()
To mt tp tin mi
CreateText()
Delete()
Xo mt tp tin
Exists()
Tr v ng nu tp tin tn ti
GetAttributes()
226
Chui
Phng thc
Gii thch
SetAttributes()
GetCreationTime()
SetCreationTime()
GetLastAccessTime()
SetLastAccessTime()
GetLastWriteTime()
SetLastWriteTime()
Move()
OpenRead()
OpenWrite()
Gii thch
Attributes()
CreationTime
Directory
Ly th mc cha
Exists
Xc nh tp tin c tn ti cha?
Extension
FullName
LastAccessTime
LastWriteTime
Length
Name
Tn tp tin
AppendText()
CopyTo()
Create()
To mt tp tin mi
Delete()
Xa tp tin
MoveTo()
Open()
M mt tp tin vi cc quyn hn
OpenRead()
OpenText()
OpenWrite()
227
Chui
228
Chui
Kt qu (mt phn):
[0] WinNT [5/1/2001 3:34:01 PM]
ActiveSetupLog.txt [4/20/2001 10:42:22 AM] Size: 10620 bytes
actsetup.log [4/20/2001 12:05:02 PM] Size: 8717 bytes
Blue Lace 16.bmp [12/6/1999 4:00:00 PM] Size: 1272 bytes
[2] Wallpaper [5/1/2001 3:14:32 PM]
Boiling Point.jpg [4/20/2001 8:30:24 AM] Size: 28871 bytes
Chateau.jpg [4/20/2001 8:30:24 AM] Size: 70605 bytes
Windows 2000.jpg [4/20/2001 8:30:24 AM] Size: 129831 bytes
8590 files in 363 directories found.
229
Chui
int counter = 0;
foreach (FileInfo file in filesInDir)
{
string fullName = file.FullName;
if (counter++ %2 == 0)
{
file.MoveTo(fullName + ".bak");
Console.WriteLine("{0} renamed to {1}",
fullName,file.FullName);
}
else
{
file.Delete( );
Console.WriteLine("{0} deleted.", fullName);
}
}
newSubDir.Delete(true); // hy th mc con ny
}
}
Kt qu (mt phn):
c:\test\media\Bach's Brandenburg Concerto No. 3.RMI
copied to newTest
c:\test\media\Beethoven's 5th Symphony.RMI copied to newTest
c:\test\media\Beethoven's Fur Elise.RMI copied to newTest
c:\test\media\canyon.mid copied to newTest
c:\test\media\newTest\Bach's Brandenburg Concerto
No. 3.RMI renamed to
c:\test\media\newTest\Bach's Brandenburg Concerto
No. 3.RMI.bak
c:\test\media\newTest\Beethoven's 5th Symphony.RMI deleted.
c:\test\media\newTest\Beethoven's Fur Elise.RMI renamed to
c:\test\media\newTest\Beethoven's Fur Elise.RMI.bak
c:\test\media\newTest\canyon.mid deleted.
Gii thch
Stream
BinaryReader /
BinaryWriter
File, FileInfo,
Directory,
230
Chui
DirectoryInfo
FileStream
TextReader,
TextWriter,
StringReader,
StringWriter
BufferedStream
MemoryStream
NetworkStream
231
Chui
{
class Tester
{
const int SizeBuff = 1024;
public static void Main( )
{
Tester t = new Tester( );
t.Run( );
}
private void Run( )
{
// c t tp tin ny
Stream inputStream = File.OpenRead(
@"C:\test\source\test1.cs");
// ghi vo tp tin ny
Stream outputStream = File.OpenWrite(
@"C:\test\source\test1.bak");
// to vng m cha d liu
byte[] buffer = new Byte[SizeBuff];
int bytesRead;
// sau khi c d liu xut chng ra outputStream
while ( (bytesRead =
inputStream.Read(buffer,0,SizeBuff)) > 0 )
{
outputStream.Write(buffer,0,bytesRead);
}
// ng tp tin trc khi thot
inputStream.Close( );
outputStream.Close( );
}
}
}
232
Chui
233
Chui
Vi tp tin c dung lng ln, chng trnh ny s chy nhanh hn chng trnh v
d trc.
tham s th hai thuc kiu bool, nu tp tin tn ti, gi tr true s ghi d liu
mi vo cui tp tin, gi tr false s xa d liu c, d liu mi s ghi d liu
c.
V d 21-6. c v ghi tp tin vn bn
using System;
using System.IO;
namespace Programming_CSharp
{
class Tester
{
public static void Main( )
{
Tester t = new Tester( );
t.Run( );
}
private void Run( )
{
// m mt tp tin
FileInfo theSourceFile = new FileInfo(
@"C:\test\source\test.cs");
// to lung c vn bn cho tp tin
StreamReader reader = theSourceFile.OpenText( );
// to lung ghi vn bn cho tp tin xut
StreamWriter writer = new StreamWriter(
@"C:\test\source\test.bak",false);
// to mt bin chui l gi mt dng vn bn
234
Chui
string text;
// c ton b tp tin theo tng dng
// ghi ra mn hnh console v tp tin xut
do
{
text = reader.ReadLine( );
writer.WriteLine(text);
Console.WriteLine(text);
} while (text != null);
// ng tp tin
reader.Close( );
writer.Close( );
}
Khi thc thi chng trnh ni dung tp tin ngun c ghi ln tp tin mi ng thi
xut ra mn hnh console.
235
Chui
Sau thc hin cng vic khc, trng hp ny l vng lp for thc hin 500.000
ln.
for (long i = 0; i < 500000; i++)
{
if (i%1000 == 0)
{
Console.WriteLine("i: {0}", i);
}
}
236
Chui
{
string s = Encoding.ASCII.GetString (buffer, 0, bytesRead);
Console.WriteLine(s);
inputStream.BeginRead(buffer, 0, buffer.Length,
myCallBack, null);
}
System;
System.IO;
System.Threading;
System.Text;
namespace Programming_CSharp
{
public class AsynchIOTester
{
private Stream inputStream;
// delegated
private AsyncCallback myCallBack;
// vng nh buffer lu gi liu c c
private byte[] buffer;
// kch thc buffer
const int BufferSize = 256;
AsynchIOTester( )
{
// m mt lung nhp
inputStream = File.OpenRead(
@"C:\test\source\AskTim.txt");
// cp pht vng buffer
buffer = new byte[BufferSize];
// gn mt hm callback
myCallBack = new AsyncCallback(this.OnCompletedRead);
}
public static void Main( )
{
AsynchIOTester theApp =
new AsynchIOTester();
theApp.Run( );
}
void Run()
{
inputStream.BeginRead(
buffer, // cha kt qu
0, // v tr bt u trn buffer
buffer.Length, // kch thc buffer
myCallBack, // callback delegate
null); // i tng trng thi cc b
// lm chuyn g trong lc c d liu
for (long i = 0; i < 500000; i++)
{
if (i%1000 == 0)
{
237
Chui
}
// hm callback
void OnCompletedRead(IAsyncResult asyncResult)
{
int bytesRead =
inputStream.EndRead(asyncResult);
// nu c c d liu
if (bytesRead > 0)
{
// chuyn n thnh chui
String s =
Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine(s);
inputStream.BeginRead(
buffer, 0, buffer.Length, myCallBack, null);
}
}
}
Kt qu (mt phn)
i: 47000
i: 48000
i: 49000
Date: January 2001
From: Dave Heisler
To: Ask Tim
Subject: Questions About O'Reilly
Dear Tim,
I've been a programmer for about ten years. I had heard of
O'Reilly books,then...
Dave,
You might be amazed at how many requests for help with
school projects I get;
i: 50000
i: 51000
i: 52000
Trong cc ng dng thc t, ta s tng tc vi ngi dng hoc thc hin cc tnh
ton trong khi cng vic nhp xut tp tin hay c s d liu c thc hin mt
cch bt ng b mt tiu trnh khc.
21.4 Serialization
Serialize c ngha l sp theo th t. Khi ta mun lu mt i tng xung tp tin
trn a t lu tr, ta phi nh ra trnh t lu tr ca d liu trong i tng.
Khi cn ti to li i tng t thng tin trn tp tin lu tr, ta s "np" ng
theo trnh t nh trc . y gi l qu trnh Serialize.
Ni chnh xc hn, serialize l tin trnh bin i trng thi ca i tng theo
mt nh dng c th c lu tr hay dch chuyn (transfer).
238
Chui
239
Chui
System;
System.IO;
System.Runtime.Serialization;
System.Runtime.Serialization.Formatters.Binary;
namespace Programming_CSharp
{
[Serializable]
class SumOf
{
public static void Main( )
{
Console.WriteLine("Creating first one with new...");
SumOf app = new SumOf(1,10);
Console.WriteLine("Creating second one with
deserialize...");
SumOf newInstance = SumOf.DeSerialize( );
newInstance.DisplaySums( );
}
public SumOf(int start, int end)
{
startNumber = start;
endNumber = end;
ComputeSums( );
DisplaySums( );
Serialize( );
}
private void ComputeSums( )
{
int count = endNumber - startNumber + 1;
theSums = new int[count];
theSums[0] = startNumber;
for (int i=1,j=startNumber + 1;i<count;i++,j++)
{
theSums[i] = j + theSums[i-1];
}
}
private void DisplaySums( )
{
foreach(int i in theSums)
{
Console.WriteLine("{0}, ",i);
}
}
private void Serialize( )
{
Console.Write("Serializing...");
240
Chui
Kt qu:
Creating first one with new...
1,
3,
6,
10,
15,
21,
28,
36,
45,
55,
Serializing......completed
Creating second one with deserialize...
1,
3,
6,
10,
15,
21,
28,
36,
45,
55,
241
Chui
System;
System.IO;
System.Runtime.Serialization;
System.Runtime.Serialization.Formatters.Binary;
namespace Programming_CSharp
{
[Serializable]
class SumOf : IDeserializationCallback
{
public static void Main( )
{
Console.WriteLine("Creating first one with new...");
SumOf app = new SumOf(1,5);
Console.WriteLine("Creating second one with
deserialize...");
SumOf newInstance = SumOf.DeSerialize( );
newInstance.DisplaySums( );
}
public SumOf(int start, int end)
{
startNumber = start;
endNumber = end;
242
Chui
ComputeSums( );
DisplaySums( );
Serialize( );
}
private void ComputeSums( )
{
int count = endNumber - startNumber + 1;
theSums = new int[count];
theSums[0] = startNumber;
for (int i=1,j=startNumber + 1;i<count;i++,j++)
{
theSums[i] = j + theSums[i-1];
}
}
private void DisplaySums( )
{
foreach(int i in theSums)
{
Console.WriteLine("{0}, ",i);
}
}
private void Serialize( )
{
Console.Write("Serializing...");
FileStream fileStream =
new FileStream("DoSum.out",FileMode.Create);
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileStream,this);
Console.WriteLine("...completed");
fileStream.Close( );
}
public static SumOf DeSerialize( )
{
FileStream fileStream =
new FileStream("DoSum.out",FileMode.Open);
BinaryFormatter binaryFormatter =
new BinaryFormatter( );
return (SumOf) binaryFormatter.Deserialize(fileStream);
fileStream.Close( );
}
public virtual void OnDeserialization( Object sender )
{
ComputeSums( );
}
private int startNumber = 1;
private int endNumber;
[NonSerialized] private int[] theSums;
}
Kt qu:
243
Chui
244
Chui
Sau khi chy on m ny ta, thc hin vic tm kim tp tin test.cfg, ta s thy
n trong ng dn sau:
c:\Documents and Settings\Administrator\ApplicationData\
Microsoft\COMPlus\IsolatedStorage\0.4\
Url.wj4zpd5ni41dynqxx1uz0x0aoaraftc\
Url.wj4zpd5ni41dynqxx1uz0ix0aoaraftc\files
245
Chui
22.1 P/Invoke
Khi u Platform invoke facility (P/Invoke - d dng gi cc giao din lp trnh
ca h iu hnh/sn din) c d nh cung cp mt cch thc truy cp n
cc hm Windows API, nhng ta c th dng n gi cc hm th vin DLL.
V d sp trnh by s dng hm Win API MoveFile ca th vin kernal32.dll. Ta
khai bo phng thc static extern bng attribute DllImport nh sau:
[DllImport("kernel32.dll", EntryPoint="MoveFile",
ExactSpelling=false, CharSet=CharSet.Unicode,
SetLastError=true)]
static extern bool MoveFile(
string sourceFile, string destinationFile);
246
Chui
247
Chui
else
{
file.Delete( );
Console.WriteLine("{0} deleted.", fullName);
}
}
}
}
newSubDir.Delete(true);
Kt qu (mt phn):
c:\test\media\newTest\recycle.wav renamed to
c:\test\media\newTest\recycle.wav
c:\test\media\newTest\ringin.wav renamed to
c:\test\media\newTest\ringin.wav
22.2 Con tr
Nh cp trn, ch nn s dng con tr khi lm vic vi cc COM, WinAPI,
hm DLL.
Cc ton t s dng vi con tr tng t nh C/C++
&: ton t ly a ch
*: ton t ly ni dung con tr
->: ton t n cc thnh vin ca con tr
248
Chui
void* lpBuffer,
int nBytesToRead,
int* nBytesRead,
int overlapped);
// hm dng: m mt tp tin tn ti
public APIFileReader(string filename)
{
fileHandle = CreateFile(
filename, // tp tin
GenericRead, // cch truy xut - desiredAccess
UseDefault, // shareMode
UseDefault, // attributes
OpenExisting, // creationDisposition
UseDefault, // flagsAndAttributes
UseDefault); // templateFile
}
// unsafe: cho php to con tr v
//
ng cnh unsafe (unsafe context)
public unsafe int Read(byte[] buffer, int index, int count)
{
int bytesRead = 0;
// fixed: cm CLR dn dp rc
fixed (byte* bytePointer = buffer)
{
ReadFile(
fileHandle, // hfile
bytePointer + index, // lpBuffer
count, // nBytesToRead
&bytesRead, // nBytesRead
0); // overlapped
}
return bytesRead;
}
const uint GenericRead = 0x80000000;
const uint OpenExisting = 3;
const uint UseDefault = 0;
int fileHandle;
}
class Test
{
public static void Main( )
{
APIFileReader fileReader =
new APIFileReader("myTestFile.txt");
// to buffer v ASCII coder
const int BuffSize = 128;
byte[] buffer = new byte[BuffSize];
ASCIIEncoding asciiEncoder = new ASCIIEncoding( );
// c tp tin vo buffer v hin th ra mn hnh console
while (fileReader.Read(buffer, 0, BuffSize) != 0)
{
Console.Write("{0}", asciiEncoder.GetString(buffer));
}
249
Chui
}
}
250
Chui
Phn 2
Xy dng mt ng dng minh ha
251
Chui
252
Chui
253
Chui
254
Chui
255
Chui
256
Chui
23.1.2 Xc nh yu cu
ng dng phi gip ngi dng c th nm bt c kin thc mt cch nhanh
nht, trnh trn lan, di dng v phi h tr chc nng hiu chnh ( Admin ).
257
Chui
258
Chui
23.2.2.2 CHNG
Chng thuc v mt ch no , mi chng c mt hay nhiu mc chnh,
v d, trc nghim.
23.2.2.3 MC CHNH
Mc chnh thuc v mt chng no , mi mc chnh c mt hay nhiu
chnh con v mt tp tin m t chi tit cho mc chnh ny nu c.
23.2.2.4 V D
V d thuc v mt chng no , mi v d s c phn m ngun v kt xut
tng ng vi m ngun ny, c th s c mt tp tin m t chi tit v v d nu
cn thit.
Tn thuc tnh
Loi
Kiu d liu
ngha
MACHUDE
PK
VARCHAR(50)
Mi ch c mt m ch
duy nht
259
Chui
TEN
VARCHAR(50)
Tn ch
NOIDUNG
VARCHAR(1000)
Ni dung ca ch
SOCHUONG
INT
S chng c trong ch
TENTP
VARCHAR(50)
Tn thnh phn : L
thuyt, V d, Trc
nghim, Qun tr
NOIDUNGTP
VARCHAR(500)
Tn thuc tnh
Loi
Kiu d liu
ngha
MACHUONG
PK
INT
Mi chng c mt m
duy nht
TEN
VARCHAR(50)
Tn ca chng
NOIDUNG
VARCHAR(1000)
Ni dung ca chng
SOMUCCHINH
INT
S mc chnh trong mt
chng
Tn thuc tnh
Loi
Kiu d liu
ngha
MAMUCCHINH
PK
INT
M mc chnh
TENMC
VARCHAR(100)
Tn mc chnh
GIOITHIEUMC
VARCHAR(2000)
TAPTIN
VARCHAR(50)
NOIDUNGCTMC
VARCHAR(1000)
Ni dung ca mt chnh
con thuc mc chnh
Tn thuc tnh
Loi
Kiu d liu
ngha
MAVD
PK
INT
M v d
TENVIDU
VARCHAR(100)
Tn ca v d
MANGUON
VARCHAR(1000)
M ngun ca mt v d
KETQUA
VARCHAR(1000)
Kt xut ca m v d
TAPTIN
VARCHAR(50)
260
Chui
Tn thuc tnh
Loi
Kiu d liu
ngha
MACAUTRACNGHIEM
PK
INT
M cu trc
nghim
TEN
VARCHAR(500)
Tn ca cu trc
nghim
NOIDUNG
VARCHAR(1000)
Ni dung ca cu
trc nghim
TRALOI1, TRALOI2,
TRALOI3, TRALOI4
VARCHAR(500)
Mt cu hi c 4
cu tr li, ng vi
4 thuc tnh
DAPAN
INT
p n ca cu
hi, c 4 gi tr : 1,
2, 3, 4
Tn x l
Loi
ngha
Qui nh
Thm ch mi
Qui nh
Xa ch c sn
Qui nh
Sa i thng tin v ch
Qui nh
Qui nh
Lp bo co, thng k
Qui nh
Tn x l
Loi
ngha
Qui nh
Thm chng mi
Qui nh
Xa chng c sn
Qui nh
Qui nh
Qui nh
261
Chui
Tn x l
Loi
ngha
Qui nh
Thm mc chnh mi
Qui nh
Xa mc chnh c sn
Qui nh
Qui nh
Qui nh
X l trn i tng : V D
Stt
Tn x l
Loi
ngha
Qui nh
Thm v d mi
Qui nh
Xa v d c sn
Qui nh
Sa i thng tin v v d
Qui nh
Qui nh
Tn x l
Loi
ngha
Qui nh
Qui nh
262
Chui
nghim, cc cu chn la v p n
ca cu.
3
Xa cu trc nghim c sn
Qui nh
Qui nh
Qui nh
Tn thuc tnh
Loi
Kiu d liu
ngha
MATHAMSO
PK
INT
M tham s
TEN
VARCHAR(100)
Tn tham s
GIATRI
INT
Gi tr tham s
DIENGIAI
VARCHAR(100)
ngha ca tham
s
Kiu d liu
ngha
Tn thuc tnh
Loi
263
Chui
TENNGUOIDUNG
PK
VARCHAR(100)
Tn ngi dng
MATMA
VARCHAR(100)
Mt m
VARCHAR(100)
a ch mail
DIENTHOAI
VARCHAR(100)
in thoi
FAX
VARCHAR(100)
S fax
Tng quan V d
V d theo chng
Bo co
Thng k
MN
HNH
CHNH
ng nhp
Qun tr
Thng
bo li
L thuyt
V d
264
Trc nghim
Chui
265
Chui
266
Chui
267
Chui
268
Chui
269
Chui
Kt qu bi lm trc nghim
Hnh 22-59 Kt qu chm im bi lm trc nghim
270
Chui
271
Chui
Giao din tng quan hiu chnh ni dung chi tit ca tng ch
Hnh 22-61 Tng quan v hiu chnh l thuyt, v d v trc nghim
272
Chui
273
Chui
274