You are on page 1of 649

OK

200
08
V ualSttud
Visu
dio20
008
8

Miccrosoft

C#AndV
VB.net









)(
.NET Framew
work




vb4arab


.




(Source Co
odes

)
d Cases

Real World
.


" :


.. ..


"



!"


!"


..

(.N
NET
)








(...LIN
NQ WPF DirectX COM .NET Java
)a
-





.NET

).... VBC#(

!


Visuall Studio 200
08
(
)

(

)
C#
Basic #
B


."NET.
"



NET.

.
Window
ws Forms

Database Program
mming

NET .



)
Data Entitties WPF

(Framework LINQ

Portable User Interfaces WCF


.Distributed Applications
.

)

(
NET. .

- al-asiri.COM

al-asiri.CCO
...............................................................................................

2
27

2 ....................................................................................................
29

3 ...............................................................................................
30

02
3 ............................................... 2008
35
03 4 ....................................................................... .NET2008
42
04 .nett
.
.....................................

5 ...................................
55
05 008
7 ...................................................... VisuallStudio20
74
.net ....................................................

06

07
.net 110 .....................................................
08 142 .......................................................... OOP
8
86

Interfacess 09 180 ...........................................................................


10 196 ..................................................................................
11 ns
210 .......................................................................... Collection
2
12
224 .................................................................. .net 2008
13 tem.IO .net
292 .................................................... Syst
14 323 .................................................... WindowsForms .net
372 ............................................................................................. +GDI 15
n 16
384 ........................................................ WindowsPresentationFFoundation
............................................................... ADO.net

17
4
439
Q 18
508 .............................................................................................. LINQ
531 ..............................................................................................WWFF 19
542 .............................................................................................. WCFF 20
21 555 .......................................................................................
22 577 ................................................................. ASP.neet
647 ..............................................................................................

648 ...........................................................................................................

25
5 ...................................................................................................................
27
7 .............................................................................................................

29
9 .........................................................................................................................
30
0 ...................................................................................................................

02

200
08

.1 8
37
7 ................................................................... VisualSttudio2008
.2 8 .................................................................... VisualSStudio2008
38
V
VS2005

.3
39
9 .............................................. VS2008

03

.NET200
08

.1 ht
4 ........................................................................................... Silverligh
44
.2 Q
46
6 ................................................................................................ LINQ
47
.3 7 ............................................................................................... WPF
49
.4 9 ....................................................................................... Expression
51
.5 1 ................................................................................................ WCF
C
ctoring.6
51
1 ....................................................................................... CodeRefac

04

.net

57
.1 7 ................................................................................................... .neet
.2 9 ................................................................................. .net
59
.3 0 .................................................................................... BaseeClass Librrary
60
mblies.4
61
1 ......................................................................................... .netAssem
.5 2 ....................................................................................................... CIL
62
.6 data
63
3 ............................................................................................. Metad
.7 4 .............................................................................................. Maniffest
64
monTypeSystem.8
64
4 .................................................................................. Comm
6 ........................................................................................ CTTSMembeers .1.8
66

10

66 ................................................................................... CTSDataTypes .2.8


67 .................................................................. CommonLanguageSpecification.9
68 ....................................................................... CommonLanguageRunTime.10
.11 69 ...............................................................................ObjectBrowser
.12 70 ........................................................................... NameSpace
.1.12 70 ..............................................................................
.13 71 ................................................................................... ildasm
.14 72 ....................................................................... opensource.net

05

2008

.1 76 .......................................................................................
.1.1 76 ............................................. VisualStudio2008CommandPrompt
.2.1 78 ................................................................................ TextPad
.3.1 80 ............................................................................... Notepad++
81 ..................................................................................... SharpDevelop .4.1
.2 82 ......................................................................... VisualStudio2008
.1.2 83 .........................................................................................

06

.1 88 .................................................................................... Console
.2 90 ...........................................................................................
.1.2 91 ........................................................................................
.2.2 91 ................................................................................... Constant
.3.2 92 ................................................................ ReadOnlyField
.3 93 ............................................................................. String
.1.3 93 ......................................................... String
.2.3 94 ......................................................................................
.3.3 94 .........................................................................................
.4.3 94 .......................................................................................
EscapeCharacters .5.3 95 ...........................................................

11

.6.3 95 ......................................................................... String


96 ............................................................................. StringBuilder .7.3
.4 98 ..................................................................................
.5 98 ............................................................................
99 .......................................................................... WideningConversions .1.5
99 ......................................................................... NarrowingConversions .2.5
.3.5 100 ...................................................................................... Cast
.4.5 101 ...................................................................... Convert
.6 101 .................................................................................. .net
.1.6 101 ....................................................................................
.2.6 103 ..........................................................................................
103 ........................................................................................ AndAlso .3.6
105 .......................................................................................... OrElse .4.6
.5.6 105 ............................................................................... switch
.7 106 ..........................................................................................
106 ......................................................................... For - Next Loop .1.7
107 ................................................................................... While Loop .2.7
108 ............................................................................. For Each Loop .3.7

07

.net

.1 112 ........................................................................................
.2 116 ......................................................................................... Function
.3 117 ......................................................................................... Methods
.4 117 ............................................................................................. out
.5 byref 118 ..................................................... byval
.6 120 ................................................................................................
.1.6 121 .......................................................................... Arrays
.2.6 121 ...................................................................................
.3.6 121 ...........................................................................

12

.4.6 122 ........................................................................


.5.6 123 ..........................................................
.6.6 124 ........................................................................
.7 124 ...................................................................................... Enumeration
.8 127 ...................................................................................... Structure
.1.8 129 ................................................................... Struct
.9 Value 131 ....................................................................... Reference
.10 133 ..................................................................................................
137 ....................................................................................... Nullable Types.11
.1.11 139 ............................................................................... Nullable
.2.11 140 ...........................................................................................

08

OOP

.1 144 ............................................................................... Classes


.1.1 146 .......................................................................... Constructors
.2.1 147 .............................................................................. Destructor
148 ................................................................................................... this.2
.3 149 ................................................................................... Static
153 ........................................................................................ StaticClass .1.3
.4 154 ............................................................................ OverLoading
.5 157 ..................................................................... Access Modifier
.6 158 ............................................................................... OOP
158 ..................................................................................... Encapsulation .1.6
158 ........................................................................................ Inheritance .2.6
159 .................................................................................... Polymorphism .3.6
160 .......................................................................................... Encapsulation.7
.1.7 public 161 ....................................... private
.2.7 164 .............................................................. Constructor
.3.7 165 ........................................................................ Type Property

13

166 ..................................................................................... Inheritance .8


167 .................................................................................... isa .1.8
170 ........................................... sealed - NotInheritable .2.8
170 ....................................................................................... .3.8
171 .......................................................................... .4.8
171 ................................................................................ hasa .5.8
172 .................................................................................. Casting .6.8
174 ................................................................................. is .7.8
174 .................................................................... VisualStudioClassDiagram .8.8
175 ..................................................................................... Polymorphism .9
177 ............................................................................................. Abstract .10
178 ................................................................................ Abstract method .1.10
Interfaces

09

182 ..................................................................................... Interface .1


184 ........................................................................................ Names Clashes.2
187 .......................................................................... IEnumerable interface.3
191 ............................................................................ ICloneable interface.4
193 .......................................................................... IComparable interface.5

10

198 .......................................................................... SyntaxErrors .1


198 ......................................................................... LogicalErros .2
200 ....................................................................... System.Exception .3
202 ............................................................. Throwing Exceptions - .4
203 ............................................................... Catching exceptions - .5
205 ............................................................................... Finally .1.5
206 ................................................................................... break .2.5
206 ......................................................................... TargetSite .3.5
206 ............................................................................. HelpLink .4.5

14

207 .......................................................................................... .6
Collections

11

212 .................................................. System.Collections Interfaces .1


215 ............................................................. System.Collections .2
215 ..................................................................................... ArrayList .1.2
218 ..................................................................................... HashTable .2.2
219 ............................................................................................ Queue .3.2
220 ............................................................................................ Stack .4.2
.net2008

12

226 ............................................................................................. Generics .1


228 .................................................................. StructureandClassGenerics .1.1
230 ............................................................................... GenericCollection .2.1
231 ............................................................................... where T .3.1
233 ........................................................................................... Delegates .2
235 ............................................................................... Delegates .1.2
236 ..................................................................................... Events .2.2
238 ............................................................. C# - AnonymousMethods .3
239 ..................................................................................... .4
240 .................................................................... ExtensionMethods .5
241 ................................................................................ AutomaticProperties.6
242 ................................................................... LambdaExpressions .7
246 ........................................................ ObjectInitializerSyntax .8
248 ................................................................... AnonymousTypes .9
250 ....................................................................................... PartialMethods.10
251 .................................................................................... GarbageCollector.11
252 ............................................................................................ GC .1.11
253 ............................................................................... OperatorOverloading.12
257 ...................................................................................... Pointers .13

15

261 .................................................................................... QueryExpressions.14


263 ............................................................................. PreprocessorDirectives.15
264 ................................................................. #region, #endregion .1.15
266 ........................................................ #if, #elif, #else, #endif .2.15
267 ........................................................................... #define, #undef .3.15
269 .................................................................................... XMLCommenting.16
274 ........................................................................................ .netassemblies.17
274 ..................................................................................... namespace .1.17
275 .................................................................... DefaultNamespace .2.17
276 ............................................... Formatofa.net Assembly .3.17
277 ............................................................................... PrivateAssemblies .4.17
277 ............................................................................... SharedAssemblies .5.17
278 .................................................................... Multithreading .18
278 ................................................................................................ .1.18
279 ................................................................ Synchronization .2.18
280 .......................................................... System.Threading.Thread .3.18
284 .............................................................................. Priority .4.18
286 ........................................................ ParameterizedThreadStart .5.18
286 .................................................................. ForegroundandBackground .6.18
287 ....................................................................... ThreadsSynchronization .7.18
288 ................................................................................... ThreadPool .8.18
288 ....................................................................... BackgroundWorker .9.18
System.IO .net

13

294 ................................................................... System.IO .1


295 .................................................. Directory DirectoryInfo .2
296 ............................................................................ DirectoryInfo .3
299 ........................................................................ Directory .4
300 ........................................................................ DriveInfo .5

16

301 ................................................................................ FileInfo .6


303 ............................................................... Open .1.6
304 ................................... OpenWrite OpenRead .2.6
304 ............................................................... OpenText .3.6
305 ............................................. AppendText CreateText .4.6
305 .................................................................................. File .7
307 ............................................................................................... Stream.8
308 ............................................................................. FileStream .1.8
309 ........................................................................... .2.8
309 ...................................................... StreamWriter, StreamReader .3.8
312 ...................................................... StringWriter, StringReader .4.8
313 ...................................................... BinaryReader, BinaryWriter .5.8
314 .......................................................................... FileSystemWatcher.9
317 ................................................................................... ObjectSerialization.10
318 ........................................................................ Serialization .1.10
320 ............................................................................. XmlSerializer .2.10
WindowsForms .net

14

325 ..................................................................................................... .1
325 ........................................................................... WindowsForms .2
328 .................................................................................. .1.2
329 ......................................................................................... .2.2
333 ............................................................... ViusalStudio.net .3
341 ................................................................... Windows.Forms .4
341 ..................................................... Windows.Forms .1.4
342 ............................................................................... Form .2.4
343 ................................................................................... Form .3.4
343 ................................................................................. Form .4.4
344 ...................................................................................... Controls .5

17

344 ........................................................................ Controls .1.5


345 ......................................................................... Controls .2.5
346 .............................................. System.Windows.Forms.Control .6
346 .......................................................................................... Button .1.6
347 ....................................................................................... CheckBox .2.6
347 ................................................................................. RadioButton .3.6
348 ...................................................................... ListBox ComboBox .4.6
348 ........................................................................................ Textbox .5.6
350 ............................................................................................ Label .6.6
350 .......................................................................... Panel GroupBox .7.6
351 ................................................................................. RichTextBox .8.6
353 ............................................................................................ Timer .9.6
354 ....................................................................................... TreeView .10.6
355 ................................................................................. ProgressBar .11.6
355 ....................................................................................... TrackBar .12.6
356 ........................................................................... DateTimePicker .13.6
356 .................................................................................................. Dialogs.7
358 ................................................................................... MessageBox .1.7
360 .................................................................................. Dialogs Controls .2.7
360 ................................................................................. ColorDialog .3.7
362 ................................................................................... FontDialog .4.7
364 ......................................................................... OpenAndSaveDialogs .5.7
367 ................................................................................. PrintDialog .6.7
367 ............................................................................................. .8
369 ............................................................................................ .9
+GDI

15

374 ......................................................................................... +GDI .1


374 ........................................................ System.Drawing .2

18

.3 375 ...................................................................................... Graphics


.4 378 .............................................................................................. Pen
.5 378 .......................................................................................... Brush
.6 379 ......................................................................................................
.7 381 .............................................................................................

16

WindowsPresentationFoundation

.1 386 ..........................................................................................
386 ................................................................................................. WPF .1.1
386 ............................................................................................... XAML .2.1
386 ............................................................................ MicrosoftExpression .3.1
.2 387 ...................................................................................... WPF
.3 388 ............................................................................................ WPF
.4 388 ............................................................................. WPF
.5 390 ............................................................................
.6 396 .............................................................................................. WPF
.7 399 .............................................................................. DataBinding
400 ................................................................................................. WPF2D.8
.1.8 400 ............................................................................. Shapes
.2.8 403 ................................................................................. Pen
.3.8 403 .......................................................................... Brush
.4.8 405 .............................................................................. Transformations

.9 Animation 406 ................................................................................ WPF


.10 409 .................................................................................. XAML
.11 409 ............................................................................................. Styles
.1.11 411 ................................................................................ Style
.2.11 Style 411 ................................................................................
.3.11 Style 411 ................................................................... Triggers
.12 414 ........................................................................................... Templates

19

416 ................................................................................................. 3DWPF.13


423 ................................................................................................. XNA .14
424 ........................................................................ MicrosoftExpressionStudio.15
424 ..................................................................... MicrosoftExpressionWeb .1.15
425 .................................................................. MicrosoftExpressionDesign .2.15
426 ................................................................... MicrosoftExpressionMedia .3.15
427 ................................................................. MicrosoftExpressionEncoder .4.15
428 ................................................................................. ExpressionBlend .5.15
ADO.net

17

441 ................................................................................. ADO.net .1


441 ..................................................................... ADO.netDataProvider .2
441 .............................................. Data Providers .1.2
442 .......................... ThirdPartyADO.net DataProviders .2.2
443 .............................................................. System.Data .3
448 ................................................................................... SQLServer .4
448 .................................................................................. .1.4
457 .................................................................................. SQLStatements .2.4
468 ................................................................................ StoredPrcoedure .3.4
471 ...................................................................................... SQLInjection .4.4
472 .............................................................................................. .5.4
473 ............................................................................................. .5
473 ............................................... ConnectionStringBuilder .1.5
474 ....................................................................... Command .2.5
478 ........................................................................... DataReaders .3.5
480 .................................................................................... DataAccessLayer.6
487 ......................................................................... AsynchronousDataAccess.7
489 ........................................................................................... Transactions.8
493 ........................................................................................... .9

20

493 ...................................................................................... DataSet .1.9


495 ......................................................................... DataTable .2.9
496 .............................................................................. DataTable .3.9
496 ....................................................................... DataColumn .4.9
498 .............................................................................. DataRow .5.9
502 ........................... DataTable DataTableReader .6.9
502 ............................................................................... XML Serializing .10
503 ................................................................................... DataGrid .11
506 ............................................................................. DataAdapter .12
LINQ

18

510 ..................................................................................................... .1
513 ............................................................................................... LINQ .2
518 ...................................................................................... LINQTo DataSet.3
519 ........................................................................................... LINQTo XML.4
521 ............................................................................................ LINQTo SQL.5
526 ................................................................................... SubmitChanges.6
527 ................................................... LINQToSQL .7
WWF

19

533 .................................................................................. WF .1
534 .......................................................................................... WF .1.1
535 ............................................................................ SequentialWorkflow .2.1
535 ....................................................................... StateMachineWorkflow .3.1
537 ............................................................................................. WWF .2
541 ..................................................................................... WFCodeLiabrary.3
WCF

20

544 ........................................................................................... WebService.1


545 ....................................................... .net WebService .1.1
546 ........................................... WebService .2.1

21

.3.1 547 .....................................................................


.2 550 .......................................................................................... WCF
.1.2 551 ...................................................................................... WCF
.2.2 552 ....................................................................... Address

21

.1 557 ......................................................................................... Debug


.2 562 ........................................................................................
564 ........................................................................................... C#vsVB.net.3
.4 569 ......................................................................................... Mono
.5 571 ...................................................................... .net

22

ASP.net

.1 579 ...................................................................................
.2 586 ...................................................................................... ASP.net
.3 593 ................................................................... System.Web.UI.Page
.1.3 593 ............................................................................. Request
.2.3 596 ........................................................................... Response
.4 598 .......................................................................................... ASP.net
.1.4 598 ...................................................................
602 ........................................................................................... MasterPages.5

.6 606 ..................................................................................... Sitemap


.7 608 ..................................................................... ValidationControl
615 ................................................................................... StateManagement.8
615 ...................................................................................... Controlstate .1.8
617 ...................................................................................... ViewState .2.8
617 ......................................................................................... Session .3.8
618 ........................................................................................ Cookies .4.8
621 .................................................................................. Application .5.8
622 ............................................................................................. Cache .6.8

22

623 ........................................................................................ Global.asax .7.8


625 ................................................................................. ASP.net.9
628 ........................................................................................... DataGrid .1.9
635 ..................................................................................................... WAP.10
635 ....................................................................................... WAP .1.10
636 ................................................................................................ WML .2.10
637 ................................................................................... WAP+ASP.net .3.10
638 ..................................................................................................... AJAX.11
638 ........................................................................................ AJAX .1.11
647 .........................................................................................
648 .........................................................................................................

23

24

...

net 200
08.




2008
.

Pro C#
# 2008 and
a
the .net 3.5
5


Andrew Tro
oelsen

Platform


C#
C




VB.net MSDN
V
net. C#
.

25




net.
.



...
.

26




.

2007
7
.
:

A-Gamal@win
ndowslive.co
om

00
0201080
011792 :

http://hammada2091.g
googlepagess.com/cv.pdff

www
w.vb4arab.co
om


www
w.AhmedGamal-Space.b
blogspot.com
m

www.AhmedGam
mal-Technical.blogspot.co
om

27

( )

)
(.net




.
.



...

-


.

...

28


Office Window
ws

C# VB.net
.
.




.





.

vb4arab.co
om

29


net 2008
.net 8.
:

:

.

net 2008.

:
.

ne
et .
:
ne
et .


.






.

: net.






:

Visual Studio
S


.

:

.



.

:

OOP

:
.

Interfa
: aces

.

30

: Collections
.
:
net.
: .
: Windows Forms
.
:
. +GDI
: WPF
.
:
ADO.net SQL Server .
: LINQ .
: WWF .
: WCF .
:
.
:
. ASP.net
...

31

. net 20
008.






.


.

32



Loop
Cond ps
ditions
)(
Interface
Claass )(

Vaariable

... (
)

33

34

2

2008

35

36

V
Visual
lStud
dio20
008

.1


Visual Studio
S
200
08



nalEdition

Profession
:
90

http://mssdn.microsofft.com/en-uss/vs2008/pro
oducts/cc268
8305.aspx

*.iso Poweer ISO



CD DVD


.
Pow :
werISO

http://ww
ww.freedown
nloadscenterr.com/Utilitie
es/Backup_a
and_Copy_Uttilities/Powe
erISO.html

ProducctKey

http://mssdn.microsofft.com/en-uss/vs2008/pro
oducts/cc263
3903.aspx


VisualStudio2008
8
Addor RemoveP
Programs

Product Key

... Change/Remove
.

37

.2 VisualStudio2008

:

http://www.microsoft.com/express/product/default.aspx

Express Professional Edition


:

net 2008. Basic


netFramework.
http://go.microsoft.com/?linkid=7653517

net 2008. C#
netFramework.
http://go.microsoft.com/?linkid=7653518

net 2008. C++


netFramework.
http://go.microsoft.com/?linkid=7653520

.net Framework

http://go.microsoft.com/?linkid=7653519

38


Net
http://www.microsoft.com/express/sql/default.aspx


gadgets mashups
http://www.microsoft.com/express/popfly/default.aspx

.1 .2 Express .netFramework

.3 VS2005
VS2008
net2005. net2008.
.

VS2008 .
. Next

.
. Finish
.
2008 2005
2008 :
SolutionExplorer .
Compile OptionInfer .ON
Advanced Compile Options Target framework .net
netFramework2.0.
Framework3.5

39

2008
References
.

40

41

3
.net
2008

42

43

.net2008


.net2008
net2008.
.

net 2008 .
net Framework.

.

.1 Silverlight

Silverlight Flash

.
Adobe Flash -
! -
Adobe Macromedia
Adobe ActionScript Flash
Flex Apollo Sun
JavaFX Script
Silverlight HD Video
- . -

44

.net2008

: Silverlight

http://www.microsoft.com/silverlight/default_ns.aspx

Silverlight GetSilverlight
. Silverlight
Setup
... Silverlight .
: Silverlight

http://silverlight.net/samples/1.0/Page-Turn/default.html

http://www.yeejie.com/silverlight_magazine/

.1 .3 .Silverlight

45

.net2008

.2 LINQ


.
:

SQL
Select companyname from customers

...
)"RS.Fields("FieldName

Loop
:

VB.NET
))(Do While (Rs.Read
))"Console.WriteLine(Rs.Fields("CompanyName
Loop

C#
do
{
;))"Console.WriteLine( Rs.Fields("CompanyName
}
;))(while(Rs.Read


Classes Members Methods Functions Operators
.net.

46

.net2008
VB.NET

_ Dim queryResults = From cust In customers


Select cust.CompanyName

C#
var queryResults = from cust in customers
;select cust.CompanyName

queryResults
.

.3 WPF
WinFx
Windows Presentation Foundation XAML
WPF .net 2008
XAML XAML .
XAML .

WPF
XAML
XAML
.net
Visual Studio

.
.net 2008
net Framework 3.5.

47

.net2008

http://blogs.msdn.com/tims/archive/2007/02/02/greatwpf-applications-6-fnac-com.aspx

http://blogs.msdn.com/tims/archive/2007/03/05/greatwpf-applications-12-roxio-central.aspx

http://blogs.msdn.com/tims/archive/2007/02/09/greatwpf-applications-8-notescraps.aspx

.WPF .2 .3

48

.net2008

.4 Expression



Flash
.
...

Expression

XAML
ExpressionBlend.

MSExpression Blend
- - Design
- - WEB
MicrosoftFrontPage
AJAX XAML
. ExpressionMedia

Blend
:

49

.net2008
8

Exp
.1 .3 pressionBleend

-
21

Partn
ners

-
.

50

.net2008

.5 WCF

...
.
Winsock 6 Sockets .net
WCF Windows Communication
.Foundation
ServerAnd
Client !!!
WCF
.

CodeRefactoring .6
IDE
.
.net2008

.
Refactor! for Visual
.Basic2008 :

http://msdn.microsoft.com/en-us/vbasic/bb693327.aspx

51

.net2008

Refactor!ForVisualBasic2008 .2 .3
CodeSnippet 2008


:

http://msdn2.microsoft.com/en-us/vbasic/bb973770.aspx

52

.net2008

CodeSnippetEditor .3 .3
2005 2008
.VisualStudio2008

53

54

4
.net

55

56

.net

.1 .net
.net ...
2000

...

Engine ..
.net
J#.net VB.net C#
C++/CLI JScript.net ... .net
LISP.net .
.net
Linux mono
.. .net C#
VB.net f#
1 .net

:

http://www.dotnetlanguages.net/DNL/Resources.aspx

57

.net

Pro C# 2008 .NET 3.5 Platform -Exploring the .NET universe using curly
brackets
.net

manegedcode :
-

; ...
Syntax Visual Basic
.net C# Basic C++ Fortran Delphi

.


.
-


...
. net.

58

.net

.2 net.
.net
net. .CLR, CTSandCLS :

CLR Runtime Layer Common Language Runtime


.net - -
Threads
" CLR .net
.

Common Type System CTS


.net
.net
CommonLanguageSpecification CLS
..Net


C#
CLS .net Linux mono
CLS CTS
.

59

.net

.3 BaseClassLibrary
.net BaseClassLibrary
Classes net .
net.
Threads XML GUI .
. .Net
BCL :

.1 .4 - BCL - MSDN
System .net
Data types ..
System .

60

.net

System.CodeDom
System.Collections .Lists, Stack
System.Diagnostics Events CountersProcess
System.Globalization
.
System.IO

Serial Port
System.Resources Resources

System.Text
System.Text.RegularE RegularExpressions
xpressions
.1 .4 System

.netAssemblies . 4
Compiler .net
intermediatelanguage IL
metadata exe
dll

61

.net

IL MSIL MS
MS.
C Common
IL MSIL metadata

IL metadata metadata manifest

manifest
.

.5 CIL
C# ProCSharp2008

C#
// Calc.cs
;using System
namespace CalculatorExample
{
// This class contains the app's entry point.
class Program
{
)(static void Main
{
;)(Calc c = new Calc
;)int ans = c.Add(10, 84
;)Console.WriteLine("10 + 84 is {0}.", ans
// Wait for user to press the Enter key before shutting down.
;)(Console.ReadLine
}
}
// The C# calculator.
class Calc
{
)public int Add(int x, int y
} ;{ return x + y
}
}

ILDASM

62

.net

CIL
.method public hidebysig instance int32 Add(int32 x,int32 y) cil managed
{
// Code size 9 (0x9)
.maxstack 2
.locals init (int32 V_0)
IL_0000: nop
IL_0001: ldarg.1
IL_0002: ldarg.2
IL_0003: add
IL_0004: stloc.0
IL_0005: br.s IL_0007
IL_0007: ldloc.0
IL_0008: ret
}// end of method Calc::Add

PlatformSpecific Instructions
Jitter
.
:

http://msdn.microsoft.com/en-us/library/f7dy01k1(VS.80).aspx

MetaData .6
MetaData
AssemblyMetadata
TypeDef #2 (02000003)
------------------------------------------------------TypDefName: CalculatorExample.Calc (02000003)
Flags : [NotPublic] [AutoLayout] [Class]
[AnsiClass] [BeforeFieldInit] (00100001)
Extends : 01000001 [TypeRef] System.Object
Method #1 (06000003)
------------------------------------------------------MethodName: Add (06000003)
Flags : [Public] [HideBySig] [ReuseSlot] (00000086)
RVA : 0x00002090
ImplFlags : [IL] [Managed] (00000000)
CallCnvntn: [DEFAULT]
hasThis
ReturnType: I42 Arguments
Argument #1: I4
Argument #2: I42 Parameters
(1) ParamToken : (08000001) Name : x flags: [none] (00000000)
(2) ParamToken : (08000002) Name : y flags: [none] (00000000)

63

.net

.net

.

.7 Manifest
Assembly
File
:

AssemblyManifest
.assembly extern mscorlib
{
) .publickeytoken = (B7 7A 5C 56 19 34 E0 89
.ver 2:0:0:0
}
.assembly Calc
{
.hash algorithm 0x00008004
.ver 0:0:0:0
}
.module Calc.exe
.imagebase 0x00400000
.subsystem 0x00000003
.file alignment 512
.corflags 0x00000001

CommonTypeSystem .8
CTS
.net :
ClassInterface -

64

.net

Structure Enumeration Delegate


CTS
CTS Compiler

.net
Class
AbstractClass AbstractClass -
interface -
AbstractClass

C#
class abst_class
{
;)int sum(int x, int y
;string name
}

VB.NET
Class abst_class
Private Function sum(ByVal x As Integer, ByVal y As Integer) As Integer
End Function
Private name As String
End Class

CTS CTS
. Istheclassabstractorconcrete

CTS Class .


Class .

65

.neet

CTSMemb
bers .1 .8
CTS Members


Fieldss :

Memb
bers
constructtor,finalize
er, static constructo
or, nested type, opeerator, meethod, pro
operty,
indexer,ffield,readonlyfield,,constant,,event
) (visibilitytrrait

.. Classs

Public

.CTS

CTSDataTy
D
ypes .2 .8
ProC#


.net
DataTypees
CTS
.n :
keeywords net
2008

66

.net

CTS
.net
CTS :

http://msdn2.microsoft.com/en-us/library/zcx1eb1e.aspx

CommonLanguageSpecification .9
CLS subset CTS
.net
CTS .net
CTS CLS .net.
CLSRules
.net.
C# VB.net CLS
CLS

: CLS

C#
])[assembly: System.CLSCompliant(true

VB.NET
>)<Assembly: System.CLSCompliant(True

CLS :

http://msdn.microsoft.com/en-us/library/12a7a7h3.aspx

67

.n
net

Co
omm
monLaanguageR
RunTime .10
.net

CLR




m
0.dll

msvbvm60



JV .... CLR
VM
.

.net



CLR mscoree.dll
.net
Microsofft
Engine


Common
n Object Runtime
R
E
Execution
CLR Load metadata

Load Types
CIL
...

platformspecificcinstructio
ons

CLR
CLR
.

BaseClass

B
.net

native
e




:

68

.net

.2 .4 native .
:

http://msdn2.microsoft.com/en-us/library/8bs2ecf4(VS.71).aspx

.11 ObjectBrowser
View ObjectBrowser :

.3 .4 ObjectBrowser

69

.net

Visual Studio
net .
.
MSDN
Help .MSDN

.12 NameSpaces
System namespace
namespaces.
name space Microsoft
Microsoft.ManagementConsole Micosoft
.
mono
namespace :
System.Windows.Forms .Forms

.1 .12

C#
;using System.Data.SqlClient

VB.NET
Imports System.Data.SqlClient

70

.net
C#

;)(SqlConnection sql1 = new SqlConnection

VB.NET
)(Dim sql1 As SqlConnection = New SqlConnection

C#
System.Data.SqlClient.SqlConnection sql1 = new
;)(System.Data.SqlClient.SqlConnection

VB.NET
Dim sql1 As System.Data.SqlClient.SqlConnection = New
)(System.Data.SqlClient.SqlConnectionn

.13 ildasm
Visual
Studio 2008
ildasm

.net
CIL ...
:
.4 .4 ildasm

:

71

.net

http://msdn.microsoft.com/en-us/library/aa730858.aspx

.14 OpenSource.net

http://www.mono-project.com

Mono project Projects CIL


.
Portable.NET CIL .
:

http://www.dotgnu.org

.MONO

72

73

74

75


.1

VisualStudio200
08

net fram
mewrok 3.5 .

net2008.


DevelopmentKit





VisualSStudio200
08

http://mssdn2.microso
oft.com/en-u
us/library/zcxx1eb1e.aspxx

VisuaalStudio200
08Com
mmand
dProm
.1 .1mpt
? csc -

C#
C

C#




....




76

VisualSttudio
) VisualSStudio200
.1 .5 08CommandPromptt

VisualStud (
V
dioTools <
< -2008
:

cs
Compille

CommandPromptt
csc Fil
le.cs

:dll

CommandPromptt
csc /ta
arget:lib
brary Fil
le.cs

:exe

CommandPromptt
csc /ou
ut:My.exe
e File.cs

:
Co
ompile

77


CommandPrompt

csc /define:DEBUG /optimize /out:File2.exe *.cs

http://msdn2.microsoft.com/en-us/library/78f4aasd(VS.80).aspx

.2 .1 TextPad

Notepad
HTML ...
... .

78

.2 .5 .TextPad
TextPad C# VB.net
Visual Studio
Compile RE ... C#

http://www.eggheadcafe.com/community/aspnet/2/10014016/textpad-and-c.aspx

Textpad

http://www.textpad.com/add-ons/cliplibs.html

79

RegulerExpressions
Textpad.

.3 .1 Notepad++

Textpad autocomplete
.

.2 .5 .Notepad++

80

http://notepad-plus.sourceforge.net/uk/about.php

OpenSource

http://sourceforge.net/projects/notepad-plus/

SharpDevelop .4 .1
C# :

.3 .5 .SharpDevelop

81

...
:

http://www.icsharpcode.net/OpenSource/SD/

.2 VisualStudio2008
IDE C# VB.net Studio Visual
Proffessional Express
. VisualC#2008Express

WebSite New Project

.4 .5 .VisualStudio2008

82

ConsoleApplication Class
Main namespace ... .
Console
.net2008
Solution Explorer
References
References .Add

Class
Classes :

Properties
.
.net ClassDesigner Classes
.

.1 .2
function Main :

83


C#

;)"Console.Write("Hello World
;)(Console.ReadKey

VB.NET
)"Console.Write("Hello World
)(Console.ReadKey

... . VisualStudio2008
F5 .

84

85

01

86

87


Console .

.1 Console



Console .
Console :

C#

. //
)Console.WriteLine(string
. //
;)(string x = Console.ReadLine
//
;)(int x = Console.ReadKey
//
;)(ConsoleKeyInfo r = Console.ReadKey
//

VB.NET

. '
)Console.WriteLine(String
. '
)(Dim x As String = Console.ReadLine
'
)(Dim x As Integer = Console.ReadKey
'
)(Dim r As ConsoleKeyInfo = Console.ReadKey
'

88

BackgroundColor

ForeGroundColor

ConsoleColor

C#
;Console.ForegroundColor = ConsoleColor.Yellow

VB.net ; .
WindowWidth Title .
:
: name
: Age
:

C#
;)Console.Write("First Name: " + name + " - Age: " + age

C#
;)Console.Write("First Name: {0} - Age: {1}", name, age

Format d e
:
exponential

C#
;)Console.WriteLine("E format: {0:E}", 99999

89

.2

C#
;int x
;string name

VB.NET
Dim x As Integer
Dim name As String

new

new
bool false

.


new

Objects

arraylists


.
C#
.1 .6
) C#
ProCSharp 2008 and .net
(2008platform

90

object Equals
GetHashCode.
int long
MaxValue MinValue ... char IsDigit
IsLetter .

.1 .2
Class int ,
string .


) Class (
. Member
int long
Array Struct

.

.2 .2 Constants
Constant Constant
:

C#
;public const int myNumber = 100

91


VB.NET

Public Const myNumber As Integer = 100

PI=3.14

... .
.
...

.3 .2 ReadOnlyField
:

C#
;public readonly double PI = 3.14

VB.NET
Public ReadOnly PI As Double = 3.14

Constant
:

C#
class MyMathClass
{
;public readonly double PI
)(public MyMathClass
{
;PI = 3.14
}
}

VB.NET
Class MyMathClass
Public ReadOnly PI As Double
)(Public Sub New
PI = 3.14
End Sub
End Class

92

.3 String
String

.1 .3 String

Length
Compare
Contains
EndWith
IndexOf
LastIndexOf
Remove
Insert String
Replace

Split
) (-
ToUpper capitalsmall
.1 .6 String

93

.2 .3
Split
:

C#
;)"string[] newarray = g.Split("-

VB.NET
)"Dim newarray As String() = g.Split("-

.3 .3
+ Concate :

C#
;)string s3 = String.Concat(s1, s2

VB.NET
)Dim s3 As String = [String].Concat(s1, s2

.4 .3
== C# = VB.net
Equals :

C#
;))Console.WriteLine(s1.Equals(s2

VB.NET
))Console.WriteLine(s1.Equals(s2

94

EscapeCharacters .5 .3

/ /n
:
/t Tab

C#
;)"Console.Write("My Name:/nAhmed Gamal

/ //
VerbatimStrings Escape
:
Characters

C#
;)"Console.WriteLine(@"C:\MyApp\bin\Debug

.6 .3 String

Parse
:

C#
;)"int x = int.Parse("1
;)"bool v = bool.Parse("True

VB.NET
)"Dim x As Integer = Integer.Parse("1
)"Dim v As Boolean = Boolean.Parse("True

ToString

C#

;)(string x = m.ToString

VB.NET
)(Dim x As String = m.ToString

95

StringBuilder .7 .3

+ C# &
VB.net - :

C#
// C#:
;"Label1.Text = Text1.Text + "@hotmail.com

VB.NET
'VB.net:
"Label1.Text = Text1.Text + "@hotmail.com

Visual Studio

StringBuilder System.Text.StringBuilder
:

C#
//C#:
;)System.Text.StringBuilder mail = New System.Text.StringBuilder(Text1.Text
;)"mail.Append("@hotmail.com

VB.NET
'VB.net:
)Dim mail As New System.Text.StringBuilder(Text1.Text
)"mail.Append("@hotmail.com

StringBuilder
+ & Object String
.
Loop
netGotachas . 10
1000000 StringBuilder
.

96

.2 .6 + StringBuilder
3562.933 59.4 ...
... & +
StringBuilder Replace Insert
Remove
:CodeProject

http://www.codeproject.com/KB/cs/StringBuilder_vs_String.aspx

97

.4
:
DateTime

C#
;)DateTime dt = new DateTime(2004, 10, 17

C#
;)Console.WriteLine(DateTime.Now

TimeSpan

C#
;)TimeSpan ts = new TimeSpan(4, 30, 0

Add Substract :

C#
;)))Console.WriteLine(ts.Subtract(new TimeSpan(0, 15, 0

C#
;)dt = dt.AddMonths(2

VB.net ; .

.5
:
WideningConversions
NarrowingConversions

98

WideningConversions .1 .5

upwardcast Short Integer :

C#
;short x = 5
;)power(x

VB.NET
Dim x As Short = 5
)power(x

power

C#
)int power(int number
{
;return number ^ 2
}

VB.NET
Private Function power(ByVal number As Integer) As Integer
Return number Xor 2
End Function

int short
Integer Short
Short Integer .

NarrowingConversions .2 .5
Integer

Short Integer

99

Short
Short .
:
Cannotimplicitlyconverttype'int'to'short'.

Cast

.3 .5 Cast
cast
Integer Short :

C#
;int var = 10
;short var2 = (short)var

VB.NET
Dim var As Integer = 10
)Dim var2 As Short = CShort(var

var2 10
:

C#
;int var = 100000
;short var2 = (short)var
;)Console.WriteLine(var2
;)(Console.ReadKey

VB.NET
Dim var As Integer = 100000
)Dim var2 As Short = CShort(var
)Console.WriteLine(var2
)(Console.ReadKey

100

-
31072 32768

.32767
Try Catsh
.

.4 .5 Convert
:
Convert

C#
;)myByte = Convert.ToByte(myInt

VB.NET
)myByte = Convert.ToByte(myInt

.6 .net
.1 .6
if else :

C#

)if (x == 5
;)"Console.WriteLine("five
else
;)"Console.WriteLine("notFive

101


VB.NET

If x = 5 Then
)"Console.WriteLine("five
Else
)"Console.WriteLine("notFive
End If

== != < >
else if :

C#
)if (x > 90
{
;)""(Console.WriteLine
}
)else if (x >= 50
{
;)""(Console.WriteLine
}
else
{
;)""(Console.WriteLine
}

VB.NET
If x > 90 Then
)""(Console.WriteLine
ElseIf x >= 50 Then
)""(Console.WriteLine
Else
)""(Console.WriteLine
End If

) (True .
1 :

C :

C#
)if (string.lenght

= True
...

102

.2 .6
&& And
True Or
|| Not
! )(
:

C#
; ))"if ((x < 90 || x > 50) && (!name = "ahmed

VB.NET
If (x < 90 Or x > 50) And (Not Name = "ahmed") Then
End If

AndAlso .3 .6
.net And
:
1
True
False
True
False

2
True
True
False
False

True
False
False
False

.2 .6 And
false

.And
AndAlso false
.

103

:
C#

if (id > 0 & SearchForID(id) > 0)


{
// do something
}

VB.NET

If id > 0 And SearchForID(id) > 0 Then


' do something
End If

Id
:

C#
if (id > 0)
{
if (SearchForID(id) > 0)
{
// do something
}
}

VB.NET

If id > 0 Then
If SearchForID(id) > 0 Then
' do something
End If
End If

: AndAlso
C#

if (id > 0 && SearchForID(id) > 0)


{
// do something
}

VB.NET
If id > 0 AndAlso SearchForID(id) > 0 Then
' do something
End If

104

OrElse .4 .6
And Or :
1
True
False
True
False

True
True
True
False

2
True
True
False
False

.2 .6 Or
True

.Or
OrElse
. AndAlso

.5 .6 switch
switch :

C#
)switch (x
{
case 90:
;)""(Console.WriteLine
;break
case 50:
;)""(Console.WriteLine
;break
}

105

VB.NET
Select Case x
Case 90
)""(Console.WriteLine
Case 50
)""(Console.WriteLine
End Select

break

break .

.7

:

For-Next Loop .1 .7

C#
)for (int i = 0; i < 10; i++
{
;)Console.WriteLine(i
}

VB.NET
For i As Integer = 0 To 9
)Console.WriteLine(i
Next

- :
-
= 2

C#
)for (int i = 0; i < 10; i += 2
{
;)Console.WriteLine(i
}

106

VB.NET

For i As Integer = 0 To 9 Step 2


Console.WriteLine(i)
Next

While Loop .2 .7


:10
C#

int x = 0;
while (x < 10)
{
Console.WriteLine(x);
x++;
}

VB.NET

Dim x As Integer = 0
While x < 10
Console.WriteLine(x)
X+=1
End While

Do "exit"
. While
C#
string inp;
do
{
inp = Console.ReadLine();
Console.WriteLine(inp);
}
while (inp != "exit");

107

VB.NET
Dim inp As String
Do
inp = Console.ReadLine()
Console.WriteLine(inp)
Loop While inp <> "exit"

For Each Loop .3 .7


:

)(
C#

int[] arr = { 10, 20, 30, 40 };


foreach (int i in arr)
Console.WriteLine(i);

VB.NET
Dim arr As Integer() = {10, 20, 30, 40}
For Each i As Integer In arr
Console.WriteLine(i)
Next

108

109

02

110

111

.1
HelloWorld :

C#

;using System
;using System.Collections.Generic
;using System.Text
namespace ConsoleApplication4
{
class Program
{
)static void Main(string[] args
{
;)"Console.Write("Hello World
;)(Console.ReadKey
}
}
}

VB.NET
Module Module1
)(Sub Main
)"Console.Write("Hello World
)(Console.ReadKey
End Sub
End Module

C# using
Module Module
Class Shared-static
.VB
C# namespace
Class ... Main
Classes
Class Main main
. Main args

112

] args[0 ] args[n
.CommandLineParameters
CommandLineArgs

:

Shell
Explorer http://www.vb4arab.com

Explorer
\ C:

.
For
Loop

C#
)for (int i = 0; i < args.Length; i++
;)]Console.WriteLine(args[i

VB.NET
For i As Integer = 0 To args.Length - 1
))Console.WriteLine(args(i
Next

Run
:Run

Shell

C:\Users\Ahmed\Documents\Visual Studio
2008\Projects\ConsoleApplication4\ConsoleApplication4\bin\Debug\con
soleapplication4.exe ahmed ali

113

.1 .7

0
:

C#
)"if (args[0] == "0
{
;Console.BackgroundColor = ConsoleColor.Blue
;)"Console.WriteLine("0 enterd
}
else
{
;Console.BackgroundColor = ConsoleColor.Red
;)"Console.WriteLine("Empty
}
;)(Console.ReadKey

VB.NET
If args(0) = "0" Then
Console.BackgroundColor = ConsoleColor.Blue
)"Console.WriteLine("0 enterd
Else
Console.BackgroundColor = ConsoleColor.Red
)"Console.WriteLine("Empty
End If
)(Console.ReadKey

..


:

114

C#
if (args.Length > 0)
{
if (args[0] == "0")
{
Console.BackgroundColor = ConsoleColor.Blue;
Console.WriteLine("0 enterd");
}
}
else
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine("Empty");
}
Console.ReadKey();

VB.NET
If args.Length > 0 Then
If args(0) = "0" Then
Console.BackgroundColor = ConsoleColor.Blue
Console.WriteLine("0 enterd")
End If
Else
Console.BackgroundColor = ConsoleColor.Red
Console.WriteLine("Empty")
End If
Console.ReadKey()


C#

if (args.Length >0 && args[0] == "0")

VB.NET

If args.Length > 0 AndAlso args(0) = "0" Then


...
AndAlso VB.net And
.

115

.2 Functions
Main

int int

:

C#
)static int sum(int number1, int number2
{
;int total = number1 + number2
;return total
}

VB.NET
Private Function sum(ByVal number1 As Integer, ByVal number2 As Integer) As
Integer
Dim total As Integer = number1 + number2
Return total
End Function

:
Main

C#
;)int result = sum(5, 8
;)Console.Write(result
;)(Console.ReadKey

VB.NET
)Dim result As Integer = sum(5, 8
)Console.Write(result
)(Console.ReadKey

sum static
static static Main
static main
static .

116

.3 Methods
:

C#
)void printmsg(string msg
{
;)Console.WriteLine(msg
}

6 Sub VB.net
:

VB.NET
)Private Sub printmsg(ByVal msg As String
)Console.WriteLine(msg
End Sub

.4 out
return
void out :

C#
)static void sum(int number1, int number2, out int total
{
;total = number1 + number2
}

VB.NET
Private Shared Sub sum(ByVal number1 As Integer, ByVal number2 As Integer,
)ByRef total As Integer
total = number1 + number2
End Sub

C#
Module Shared
.

117

C#
;int result
;)sum(5, 8,out result
;)Console.Write(result
;)(Console.ReadKey

VB.NET
Dim result As Integer
)sum(5, 8, result
)Console.Write(result
)(Console.ReadKey



return

.out

.5 byref
byval
:

C#
;int x = 5
;int y = 10
;)sub(x, y

VB.NET
Dim x As Integer = 5
Dim y As Integer = 10
)sub(x, y

118


C#

)static void sub(int number1, int number2


{
;number1 = number1 - number2
;return number1
}

VB.NET
)Private Sub [sub](ByVal number1 As Integer, ByVal number2 As Integer
number1 = number1 - number2
Return number1
End Sub

number1 x
x
.X
ByRef x
number1 .x
ByRef :

C#
)static void sub(ref int number1, ref int number2
{
;int result = number1 - number2
;return result
}

VB.NET
)Private Sub [sub](ByRef number1 As Integer, ByRef number2 As Integer
Dim result As Integer = number1 - number2
Return result
End Sub

Struct
ByRef...

119

.6 Arrays
.

.1 .6

Arrays

Array 5
:

C#
;]int[] intarray = new int[5

VB.NET
)Dim intarray As Integer() = New Integer(4

4
:

C#
;)]Console.WriteLine(intarray[3

VB.NET
))Console.WriteLine(intarray(3

C#
)for (int i = 0; i < 5; i++
;)]Console.WriteLine(intarray[i

VB.NET
For i As Integer = 0 To 4
))Console.WriteLine(intarray(i
Next

120

.2 .6
:

C#
;array[0] = 15
;array[1] = 20
;array[2] = 13

VB.NET
array(0) = 15
array(1) = 20
array(2) = 13

C#
;} int[] intarray = new int[] { 15, 20, 13

VB.NET
}Dim intarray As Integer() = New Integer() {15, 20, 13

.3 .6
one dimensional
Multi dimensional
- :Matrix -

C#
;]int matrix = new int[3, 3

VB.NET
)Dim matrix As Integer = New Integer(2, 2

121

)( :
000
000
000
:

C#
;matrix[1, 2] = 20

VB.NET
matrix(1, 2) = 20

C#
;]int matrix = new int[3, 3
)for (int i = 0; i < 3; i++
)for (int j = 0; j < 3; j++
;)(matrix[i, j] = Console.ReadLine

VB.NET
}{ )Dim matrix As Integer = New Integer(2, 2
For i As Integer = 0 To 2
For j As Integer = 0 To 2
)(matrix(i, j) = Console.ReadLine
Next
Next

.4 .6
:

C#

;][]int[][] complexarray = new int[5

VB.NET
)()Dim complexarray As Integer()() = New Integer(4

122

C#
;)]Console.WriteLine(complexarray[1][4

VB.NET
))Console.WriteLine(complexarray(1)(4

4 complexarray

.5 .6
:

C#

)static void print(int[] arr


{
)for (int i = 0; i < arr.Length; i++
;)]Console.WriteLine(arr[0
}

VB.NET
))(Private Sub print(ByVal arr As Integer
For i As Integer = 0 To arr.Length - 1
))Console.WriteLine(arr(0
Next
End Sub

byref
.
array return :

C#
)(static int[] read
{
;]int[] arr = new int[3
)for (int i = 0; i < 3; i++
;)(arr[i] = Console.Read
;return arr
}

123

VB.NET
)(Private Function read() As Integer
}{ )Dim arr As Integer() = New Integer(2
For i As Integer = 0 To 2
)(arr(i) = Console.Read
Next
Return arr
End Function

.6 .6

:

Length
Sort
Reverse
ToString
Rank



Reverse

Rank

.1 .7 Array

.7 Enumeration
enumerations -
.
Enum
Nissan Toyota FIAT
1 0 2
.

124


C#

enum cars
{
toyota = 0,
nissan = 1,
fiat = 2
}

VB.NET

Enum cars
toyota = 0
nissan = 1
fiat = 2
End Enum

Enum
: byte
C#

enum cars : byte


{
toyota = 0,
nissan = 1,
fiat = 2
}

VB.NET
Enum cars As Byte
toyota = 0
nissan = 1
fiat = 2
End Enum

125

C#
)static void printPrice(cars mycar
{
)if (mycar == cars.fiat
;)"Console.WriteLine("20,000
)else if (mycar == cars.nissan
;)"Console.WriteLine("30,000
else
;)"Console.WriteLine("40,000
}

VB.NET
)Private Sub printPrice(ByVal mycar As cars
If mycar = cars.fiat Then
)"Console.WriteLine("20,000
ElseIf mycar = cars.nissan Then
)"Console.WriteLine("30,000
Else
)"Console.WriteLine("40,000
End If
End Sub

.byte
Enum API
A127X 00
Local

.

126

.8 Structures
Structure Structs
Struct
Struct

:

C#
struct Car
{
;public int carNumber
;public int year
;public string factory
;}

VB.NET
Structure Car
Public carNumber As Integer
Public year As Integer
Public factory As String
End Structure

)( :

C#
;)(Car ahmedcar = new Car
;ahmedcar.carNumber = 1000
;"ahmedcar.factory = "Nissan
;ahmedcar.year = 2007

VB.NET
)(Dim ahmedcar As New Car
ahmedcar.carNumber = 1000
"ahmedcar.factory = "Nissan
ahmedcar.year = 2007

struct struct struct




:

127

C#
struct Licence
{
public string UserName;
public int yearsToFinish;
}

VB.NET
Structure Licence
Public UserName As String
Public yearsToFinish As Integer
End Structure

C#
struct Car
{
public
public
public
public
};

int carNumber;
int year;
string factory;
Licence carLicence;

VB.NET
Structure Car
Public carNumber As Integer
Public year As Integer
Public factory As String
Public carLicence As Licence
End Structure

:
C#
Car ahmedcar = new Car();
ahmedcar.carNumber = 1000;
ahmedcar.factory = "Nissan";
ahmedcar.year = 2007;
ahmedcar.carLicence.UserName = "Ahmed Gamal";
ahmedcar.carLicence.yearsToFinish = 3;

128

VB.NET
Dim ahmedcar As New Car()
ahmedcar.carNumber = 1000
ahmedcar.factory = "Nissan"
ahmedcar.year = 2007
ahmedcar.carLicence.UserName = "Ahmed Gamal"
ahmedcar.carLicence.yearsToFinish = 3

Struct .1 .8
struct struct
renew
: struct

C#
struct Licence
{
public string UserName;
public int yearsToFinish;
public void renew(int periode)
{
yearsToFinish += periode;
}
}

VB.NET
Structure Licence
Public UserName As String
Public yearsToFinish As Integer
Public Sub renew(ByVal periode As Integer)
yearsToFinish += periode
End Sub
End Structure

129

struct Create .

struct
.
Constructor
: struct
C#

struct Car
{
private int carNumber;
private int year;
private string factory;
private Licence carLicence;
public Car(int p_carNumber, int p_year, string p_factory, Licence
p_carLicence)
{
carNumber = p_carNumber;
factory = p_factory;
year = p_year;
carLicence = p_carLicence;
}
};

VB.NET

Structure Car
Private carNumber As Integer
Private year As Integer
Private factory As String
Private carLicence As Licence
Public Sub New(ByVal p_carNumber As Integer, ByVal p_year As Integer, ByVal
p_factory As String, ByVal p_carLicence As Licence)
carNumber = p_carNumber
factory = p_factory
year = p_year
carLicence = p_carLicence
End Sub
End Structure

private
OOP struct

130

public
private .struct

.9 Value Reference

ValueType ValueType
:

C#
;int x=5
;int y=x
;y=18
;)Console.WriteLine(x
;)Console.WriteLine(y

VB.NET
Dim x As Integer = 5
Dim y As Integer = x
y = 18
)Console.WriteLine(x
)Console.WriteLine(y

x y

y=x y . x
struct...
ReferenceTypes Class
:

131

C#
class car
{
int carNumber;
string carName;
}

VB.NET
Class car
Private carNumber As Integer
Private carName As String
End Class

: int
C#

Car x = new Car();


x.carNumber = 1;
Car y = x;
Console.WriteLine (x == y);

VB.NET

Dim x As New Car()


x.carNumber = 1
Dim y As Car = x
Console.WriteLine(x = y)

Car y
y x
:
C#
Car x = newCar();
Car y = x;
x.carNumber=1;
y.carNumber =2;
Console.WriteLine (x.carNumber);
Console.ReadKey();

132

VB.NET
)(Dim x As Car = newCar
Dim y As Car = x
x.carNumber = 1
y.carNumber = 2
)Console.WriteLine(x.carNumber
)(Console.ReadKey

Class Car Clone Car


Class ICloneable Interface .Clone

.10
= ==
C# :

C#
)if (x == y
{
}

VB.NET
if x = y Then
End if

True False
5=5 : 7=7 " "Ahmed"="Ahmed

.

Int , Long , String...

133

C#
string a = new string(new char[] { 'h', 'e', 'l', 'l', 'o' });
string b = new string(new char[] { 'h', 'e', 'l', 'l', 'o' });
Console.WriteLine(a == b);

VB.NET
Dim a As New String(New Char() {"h"C, "e"C, "l"C, "l"C, "o"C})
Dim b As New String(New Char() {"h"C, "e"C, "l"C, "l"C, "o"C})
Console.WriteLine(a = b)

C#

: True

object c = a;
object d = b;
Console.WriteLine(c == d);

VB.NET
Dim c As Object = a
Dim d As Object = b
Console.WriteLine(c = d)

False
Equals

C#
Console.WriteLine(c.Equals(d));

VB.NET
Console.WriteLine(c.Equals(d))

C#

:
Structs Equals

struct car
{
public int carNumber;
};

134

VB.NET
public structure Car
public carNumber As Integer
End structure

C#
Car x = new Car();
x.carNumber=1;
Car y=x;
Console.WriteLine (x==y);

VB.NET
Dim x As New Car()
x.carNumber = 1
Dim y As Car = x
Console.WriteLine(x = y)

True
. False
: Equals

C#
Console.WriteLine (x.Equals(y));

VB.NET
Console.WriteLine(x.Equals(y))

: == Classes
C#

Console.WriteLine (Class1==Class2);

VB.NET
Console.WriteLine(Class1 = Class2)

135

Equals
True


True
:

C#
;)(Car x = new Car
;)(Car y = new Car
;x.carNumber=1
;y.carNumber = 1
;)Console.WriteLine (x==y
;)(Console.ReadKey

VB.NET
)(Dim x As New Car
)(Dim y As New Car
x.carNumber = 1
y.carNumber = 1
)Console.WriteLine(x = y
)(Console.ReadKey

False ...
:

C#
)bool isthesame(Car c1, Car c2
{
)if (c1.carNumber == c2.carNumber
;return true
;return false
}

136


VB.NET

Private Function isthesame(ByVal c1 As Car, ByVal c2 As Car) As Boolean


If c1.carNumber = c2.carNumber Then
Return True
End If
Return False
End Function


Clone :

C#
)Car doCopy(Car c1
{
;)(Car newCar = new Car
;newCar.carNumber = c1.carNumber
//
//
;return newCar
}

VB.NET
Private Function doCopy(ByVal c1 As Car) As Car
)(Dim newCar As New Car
newCar.carNumber = c1.carNumber
'
'
Return newCar
End Function

Clone
ICloneable
Class Clone

Clone .

NullableTypes .11
null
True False Short
Boolean

137

String
...
32767
null .reference
Boolean ) (null -
True False

)(
null Check
.
null bool
.net Framework
null :

C#
;bool? ismarried = null

VB.NET
Dim ismarried As System.Nullable(Of Boolean) = Nothing


.null
null :

C#
;Nullable<bool> nullableBool = null

VB.NET
Dim ismarried As System.Nullable(Of Boolean) = Nothing

? Generic > System.Nullable<T


.
return Nullable :

138

C#
public bool? functionName()
{
}

VB.NET
Public Function functionName() As System.Nullable(Of Boolean)
End Function

Nullable .1 .11
HasValue nullable
: null

C#
if (ismarried.HasValue)
{
}

VB.NET

If ismarried.HasValue Then
End If

: != ><
C#

if (ismarried != null)

VB.NET
If ismarried <> Nothing Then

139

null
nothing

.2 .11
nullable
null
False
:

C#
;int? ismarried = returnvaluefromdatabase() ?? false

VB.NET

Dim ismarried As System.Nullable(Of Integer) = IIf(returnvaluefromdatabase() Is


)(Nothing, [False], returnvaluefromdatabase

140

141

142

143

.1 Classes
ConsoleApplication
ClassProgram ...
OOP .Class

Class NewClass .Project
class }{
EndClass VB.net
Person :

C#
namespace ConsoleApplication4
{
class Person
{
}
}

VB.NET
Namespace ConsoleApplication4
Class Person
End Class
End Namespace

namespace Classes
namespace
main .Program

Class
Class :

144

C#
class Person
{
public string FirstName;
public string LastName;
public int Age;
}

VB.NET
Class Person
Public FirstName As String
Public LastName As String
Public Age As Integer
End Class

:
Objects
C#

Person Ahmed = new Person();


Ahmed.Age = 15;
Ahmed.FirstName = "Ahmed";
Ahmed.LastName = "Gamal";
Person Ali = new Person();
Ali.Age = 15;
Ali.FirstName = "Ahmed";
Ali.LastName = "Gamal";

VB.NET

Dim Ahmed As New Person()


Ahmed.Age = 15
Ahmed.FirstName = "Ahmed"
Ahmed.LastName = "Gamal"
Dim Ali As New Person()
Ali.Age = 15
Ali.FirstName = "Ahmed"
Ali.LastName = "Gamal"

:
C#
Person [] MyEmpolyee = new Person[3];
MyEmpolyee[0] = new Person();
MyEmpolyee[0].FirstName = "Ahmed";
MyEmpolyee[0].LastName = "Gamal";
MyEmpolyee[0].Age = 15;

145

VB.NET
}{ )Dim MyEmpolyee As Person() = New Person(2
)(MyEmpolyee(0) = New Person
"MyEmpolyee(0).FirstName = "Ahmed
"MyEmpolyee(0).LastName = "Gamal
MyEmpolyee(0).Age = 15

struct Class
:

C#
)(public string getFullName
{
;return FirstName + LastName
}

VB.NET
Public Function getFullName() As String
Return FirstName + LastName
End Function

.1 .1 Constructors
)( new Person
Constructor


: Class


New

146

C#
public Person()
{
Console.WriteLine("new object");
}

VB.NET
Public Sub New()
Console.WriteLine("new object")
End Sub

Constructor
Constructor
:

C#
public Person(string userfirstname)
{
FirstName = userfirstname;
}

VB.NET
Public Sub New(ByVal userfirstname As String)
FirstName = userfirstname
End Sub

C#

Person MyEmpolyee = new Person("ahmed");

VB.NET

Dim MyEmpolyee As New Person("ahmed")

Destructor .2 .1
Beep Object Constructor
:

147

C#
)(~Person
{
;)(Console.Beep
}

VB.NET
)(Protected Overrides Sub Finalize
End Sub

Destructor Object

.

this .2
this
Constructor :

C#
)public Person(string userfirstname
{
;FirstName = userfirstname
}

VB.NET
)Public Sub New(ByVal userfirstname As String
FirstName = userfirstname
End Sub

:
FirstName

C#
)public Person(string FirstName
{
;FirstName = FirstName
}

148

VB.NET
)Public Sub New(ByVal FirstName As String
FirstName = FirstName
End Sub

FirstName
FirstName .
= this C# Me VB.net

C#
)public Person(string FirstName
{
;this.FirstName = FirstName
}

VB.NET
)Public Sub New(ByVal FirstName As String
Me.FirstName = FirstName
End Sub

this

.this

.3 static
main static
C# Shared VB.net
static
Class
object Person

149

C#

class Person
{
public string FirstName;
public string LastName;
public int Age;
static public int counter;
}

VB.NET

Class Person
Public FirstName As String
Public LastName As String
Public Age As Integer
Public Shared counter As Integer
End Class

:

C#

Person MyEmpolyee = new Person();


MyEmpolyee.Age = 15;
MyEmpolyee.counter = 3;

VB.NET

Dim MyEmpolyee As New Person()


MyEmpolyee.Age = 15
MyEmpolyee.counter = 3

static counter
: Class
C#

Person MyEmpolyee = new Person();


MyEmpolyee.Age = 15;
Person.counter = 3;

VB.NET
Dim MyEmpolyee As New Person()
MyEmpolyee.Age = 15;
Person.counter = 3;

150

Object counter
Class 3 static
Class objects .

Class Constructor
:Destructor

C#
class Person
{
;public string FirstName
;public string LastName
;public int Age
;static public int counter
)(public string getFullName
{
;return FirstName + LastName
}
)(public Person
{
;counter++
}
)(~Person
{
;counter--
}
}

151

VB.NET
Class Person
Public FirstName As String
Public LastName As String
Public Age As Integer
Public Shared counter As Integer
Public Function getFullName() As String
Return FirstName + LastName
End Function
Public Sub New()
counter += 1
End Sub
Protected Overrides Sub Finalize()
Try
counter -= 1
Finally
MyBase.Finalize()
End Try
End Sub
End Class

:
C#

Person MyEmpolyee = new Person();


Person MyEmpolyee2 = new Person();
Person MyEmpolyee3 = new Person();
Person MyEmpolyee4 = new Person();
Person MyEmpolyee5 = new Person();
Console.WriteLine(Person.counter);

VB.NET

Dim MyEmpolyee As New Person()


Dim MyEmpolyee2 As New Person()
Dim MyEmpolyee3 As New Person()
Dim MyEmpolyee4 As New Person()
Dim MyEmpolyee5 As New Person()
Console.WriteLine(Person.counter)

152

C#
Person[] MyEmpolyee = new Person[5];
Console.WriteLine(Person.counter);

VB.NET
Dim MyEmpolyee As Person() = New Person(4) {}
Console.WriteLine(Person.counter)

5
:5 MyEmpolyee

C#
Person[] MyEmpolyee = new Person[5];
for (int i = 0; i < 5; i++)
MyEmpolyee[0] = new Person();
Console.WriteLine(Person.counter);

VB.NET
Dim MyEmpolyee As Person() = New Person(4) {}
For i As Integer = 0 To 4
MyEmpolyee(0) = New Person()
Next
Console.WriteLine(Person.counter)

StaticClass .1 .3
Static Class StaticClass .netFramewrok2.0
static
.new Class object
Class Class
. MessageBox
C#
MessageBox.Show(Welcome);

153

VB.NET
)MessageBox.Show(Welcome

.4 OverLoading
OOP Overloading
.
Overloading )( MessageBox.Show Windows
Forms
:

C#
;)MessageBox.Show(string text
;)MessageBox.Show(string text,string caption
;)MessageBox.Show(string text, string caption, MessageBoxButtons buttons

7
Overloading :

C#
;)MessageBox.ShowWithString(string text
;)MessageBox.ShowStringAndCaption(string text,string caption
MessageBox.ShowStringAndCaptionAndButtons(string text, string caption,
;)MessageBoxButtons buttons

OverLoading -
class int double

154

C#
static int Add(int x, int y)
{
return x + y;
}
static double Add(double x, double y)
{
return x + y;
}
static long Add(long x, long y)
{
return x + y;
}

VB.NET
Private Shared
Return x +
End Function
Private Shared
Return x +
End Function
Private Shared
Return x +
End Function

Function Add(ByVal x As Integer, ByVal y As Integer) As Integer


y
Function Add(ByVal x As Double, ByVal y As Double) As Double
y
Function Add(ByVal x As Long, ByVal y As Long) As Long
y

Constructor
: Constructors Person

C#
class Person
{
public string FirstName;
public string LastName;
public int Age;
public Person(){
Console.WriteLine("c1");
}
public Person(string fname, string lname)
{
FirstName = fname;
LastName = lname;
Console.WriteLine("c2");
}
public Person(string fname, string lname, int myage)
{
FirstName = fname;
LastName = lname;
Age = myage;
Console.WriteLine("c3");
}
}

155

VB.NET
Class Person
Public FirstName As String
Public LastName As String
Public Age As Integer
Public Sub New()
Console.WriteLine("c1")
End Sub
Public Sub New(ByVal fname As String, ByVal lname As String)
FirstName = fname
LastName = lname
Console.WriteLine("c2")
End Sub

Public Sub New(ByVal fname As String, ByVal lname As String, ByVal myage As
Integer)
FirstName = fname
LastName = lname
Age = myage
Console.WriteLine("c3")
End Sub
End Class

:
C#

Person MyEmpolyee = new Person();


Person MyEmpolyee = new Person("ahmed", "gamal");
Person MyEmpolyee = new Person("ahmed", "gamal", 22);

VB.NET
Dim MyEmpolyee As New Person()
Dim MyEmpolyee As New Person("ahmed", "gamal")
Dim MyEmpolyee As New Person("ahmed", "gamal", 22)

156

.5 AccessModifiers
public
Object
private
class
.

:Public
Object
Class public objects
Class .

:Private
Class Struct .

:Protected
Object Class.

:internal
.

:protected internal
Class
.

157

.6 OOP
OOP :
Encapsulation .1
Inheritance .2
Polymorphism .3

Encapsulation .1 .6
Encapsulation
BlackBox PrintReport
.

Structured Encapsulation OOP
Objects
.

Inheritance .2 .6
class
) class(

.


class BMW
class class class
Car isSport class BMW

158

Car BMW GMC


.
countofdoors
Car
.

.
Inheritance isa BMW isa Car
. CircleisaShape

Classes hasa Aggregation


Wheel . Car hasa Wheel

Polymorphism .3 .6
OOP Implementation
implementation
Class Shape :

C#
class Shape
{
)(public void Draw
{
}
)(public void GetSize
{
}
}

159


VB.NET
Class Shape
)(Public Sub Draw
End Sub
)(Public Sub GetSize
End Sub
End Class

Class Abstract Class C# VB.net


Interface AbstractClass .
) (
.
OverRidding
.DefaultImplementation

Encapsulation .7

Encapsulation

.
Encapsulation


) ( ) ( ) ( ...
.



.

160






.
OOP
.


...
.

.1 .7

public

private

Person
:

C#
class Person
{
;public int Age
}

VB.NET
Class Person
Public Age As Integer
End Class

- -
:

C#
;)(Person Ahmed = new Person
;Ahmed.Age = 999999999999

161

VB.NET
Dim Ahme
)(ed As New Person
Ahmed.Ag
ge = 999999999999




- -

-


:

C#
class pe
erson
{
;vate int Age
priv
publ
lic string SetAge(in
)nt x
{
)if (x > 100 || x < 1
n't edit ag
ge like th
;"hat
return "you can
;Age = x
;"return "done
}
)(lic int GetAge
publ
{
;return Age
}
}

162

VB.NET
Class person
Private Age As Integer
Public Function SetAge(ByVal x As Integer) As String
If x > 100 OrElse x < 1 Then
Return "you can't edit age like that"
End If
Age = x
Return "done"
End Function
Public Function GetAge() As Integer
Return Age
End Function
End Class

Set x
:

C#
public string SetAge(int Age)
{
if (Age > 100 || Age < 1)
return "you can't edit age like that";
this.Age = Age;
return "done";
}

VB.NET
Public Function SetAge(ByVal Age As Integer) As String
If Age > 100 OrElse Age < 1 Then
Return "you can't edit age like that"
End If
Me.Age = Age
Return "done"
End Function

... Me this



.

Mutator SetAge Accessor GetAge

163

.2 .7 Constructor

Constructor

Object Class
:

C#
class Person
{
;private int Age
)public Person(int Age
{
)if (Age > 100 || Age < 1
;"return "you can't edit age like that
;this.Age = Age
;"return "done
}
}

VB.NET
Class Person
Private Age As Integer
)Public Sub New(ByVal Age As Integer
If Age > 100 OrElse Age < 1 Then
"Return "you can't edit age like that
End If
Me.Age = Age
"Return "done
End Sub
End Class

164

.3 .7 TypeProperty


Set Get :

C#
class Person
{
public int Age
{
} ;get { return Age
set
{
))if (!(value > 100 || value < 1
;Age = value
}
}
}

VB.NET
Class Person
Public Property Age() As Integer
Get
Return Age
End Get
)Set(ByVal value As Integer
If Not (value > 100 OrElse value < 1) Then
Age = value
End If
End Set
End Property
End Class

Age Set
Get
.
Set Get public ) (
Age public .net 2.0
:
Set Get

165

C#
public int Age
{
get { return Age; }
protected set { Age = value; }
}

VB.NET
Public Property Age() As Integer
Get
Return Age
End Get
Protected Set(ByVal value As Integer)
Age = value
End Set
End Property

Set ReadOnlyProperty
:ReadOnlyProperty Get WriteOnlyProperty

C#
public int Age
{
get { return Age; }
}

VB.NET
Public ReadOnly Property Age() As Integer
Get
Return Age
End Get
End Property

Inheritance .8
OOP
. Inheritance Encapsulation
:

166

C#
class Car
{
private string carName;
private int carModel;
public Car(string carName, int carNumber)
{
this.carNme = carName;
this.carNumber = carNumber;
}
public Car()
{
carName = "Unknown";
carNumber = 0;
}
}

VB.NET
Class Car
Private carName As String
Private carModel As Integer
Public Sub New(ByVal carName As String, ByVal carNumber As Integer)
Me.carNme = carName
Me.carNumber = carNumber
End Sub
Public Sub New()
carName = "Unknown"
carNumber = 0
End Sub
End Class

isa .1 .8
hasa isa

BMW
C#
class BMW : Car
{
}

167

VB.NET
Class BMW
Inherits Car
End Class

BMW Car
public
carName :

C#
;)(BMW ahmedcar = new BMW
;"ahmedcar.carName = "anyname

VB.NET
)(Dim ahmedcar As New BMW
"ahmedcar.carName = "anyname


BMW :

C#
class BMW: Car
{
)public void changeCarName (string value
{
;carName = value
}
}

VB.NET
Class BMW
Inherits Car
)Public Sub changeCarName (ByVal value As String
carName = value
End Sub
End Class


private

168

private protected
object
: Car
C#

class Car
{
protected string carName;
protected int carModel;
}

VB.NET

Class Car
Protected carName As String
Protected carModel As Integer
End Class

BMW
:
C#

class BMW: Car


{
public void changeCarName(string value)
{
carName = value;
}
}

VB.NET
Class BMW
Inherits Car
Public Sub changeCarName(ByVal value As String)
carName = value
End Sub
End Class

169

.2 .8

NotInheritable - sealed

C#
sealed class Car
{
}

VB.NET
NotInheritable Class Car
End Class

NotInheritable sealed C#

.3 .8
VB.net
managed c++


. VB.net
Implementation interface
.
C# VB.net :

170

http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85562.aspx

.4 .8


BMW
BMW...

. maxSpeed
Car .



3 4

.

.5 .8 hasa

:

C#
class Tires
{
;int TiresType
;int TiresSize
}

171

VB.NET
Class Tires
Private TiresType As Integer
Private TiresSize As Integer
End Class

Tire isnotaCar Car


hasa Tire :

C#
class Car
{
;)(Tires carTires = new Tires
}

VB.NET
Class Car
)(Private carTires As New Tires
End Class

private protected

.6 .8 Casting
Casting
.
Classes
:BMW
" "cast

C#
;)(BMW ahmedCar = new BMW

172

VB.NET
)(Dim ahmedCar As New BMW

BMW
Car BMW Car
.
BMW :

C#
;)(Car ahmedCar = new BMW

VB.NET
)(Dim ahmedCar As Car = New BMW

implicitcast

.Car
BMW :

C#
;)(Object ahmedCar = new BMW

VB.NET
)(Dim ahmedCar As Object = New BMW

Object
Car cast :

C#
;)functionname((Car)ahmedCar
;)functionname((BMW)ahmedCar

173

VB.NET
))functionname(DirectCast(ahmedCar, Car
))functionname(DirectCast(ahmedCar, BMW

.7 .8 is

C#
)if (ahmedCar is BMW
{
}

VB.NET
If TypeOf ahmedCar Is BMW Then
End If


.
BMW

VisualStudioClassDiagram .8 .8
2005 ClassDiagram
:

174

VisualStudioClassDesigner .1 .8
new>classdiagram
.

.9 Polymorphism
polymorphism
...

class implementation
implementation
.Overriding

175


( 10.
)

C#
)public int calc(int fuel
{
;return fuel * 10
}

VB.NET
Public Function calc(ByVal fuel As Integer) As Integer
Return fuel * 10
End Function

BMW
5 calc
Overriding
.polymorphism base class
virtual :

C#
)public virtual int calc(int fuel
{
;return fuel * 10
}

VB.NET
Public Overridable Function calc(ByVal fuel As Integer) As Integer
Return fuel * 10
End Function

virtual overriddeable
:

C#
)public override int calc(int fuel
{
;return fuel * 5
}

176

VB.NET
Public Overloads Overrides Function calc(ByVal fuel As Integer) As Integer
Return fuel * 5
End Function

implementation
implementation Abstractclass interface
.

.10 Abstract
Abstract class
implementation
abstract :

C#
abstract partial class Car
{
}

VB.NET
Partial MustInherit Class Car
End Class

MustInherit vb.net abstract C#


:

C#
;)(Car ahmedCar = new Car

177


VB.NET
)(Dim ahmedCar As Car=new Car

AbstractMethod .1 .10
virtual overriding

overriding Abstractmethod
:

C#
;)public abstract int calc(int fuel

VB.NET
Public MustOverride Function calc(ByVal fuel As Integer) As Integer

178

179

9
Interfaces

180

181

Interfaces

Interface .1
abstract methods and members abstract class interface
inheritance
implementation
multiple interface implement
. inheritance
:
interface

C#
public interface ICar
{
int carMaxSpeed { get; set; }
void AddItem(string Item);
}

VB.NET
Public Interface ICar
Property carMaxSpeed() As Integer
Sub AddItem(ByVal Item As String)
End Interface

:
interface
C#

public interface ICar : IDisposable


{
int carMaxSpeed { get; set; }
void AddItem(string Item);
}

VB.NET
Public Interface ICar
Inherits IDisposable
Property carMaxSpeed() As Integer
Sub AddItem(ByVal Item As String)
End Interface

182

Interfaces

implements interface :

C#
public class BMW : ICar
{
}
public class BMW2 : ICar, ITruck
{
}

VB.NET
Public Class BMW
Implements ICar
End Class
Public Class BMW2
Implements ICar, ITruck
End Class

.
.


Interface Object :

C#
;)(ICar x = new ICar

VB.NET
)(Dim x As New ICar

Interface Interface:

C#
;int number

183

Interfaces

VB.NET
Dim number as integer

: get set

C#
int x { set; get; }

VB.NET
Private Property x() As Integer
Get
End Get
Set(ByVal value As Integer)
End Set
End Property

.interface .interface constructor -

NamesClashes .2
interface implements struct class
:
C#
public interface ICar
{
void move();
}
public interface ITruck
{
void move();
}
public class BMW : ITruck, ICar
{
}

184

Interfaces

VB.NET

Public Interface ICar


Sub move()
End Interface
Public Interface ITruck
Sub move()
End Interface
Public Class BMW
Implements ITruck
Implements ICar
End Class

move() implementation
:BMW

C#
public class BMW : ITruck, ICar
{
void move()
{
// do something.
}
}

VB.NET

Public Class BMW


Implements ITruck
Implements ICar
Private Sub move()
' do something.
End Sub
End Class

move() Car move() implementation


: Truck

185

Interfaces

C#

public class BMW : ITruck, ICar


{
void ICar.move()
{
// do something.
}
void ITruck.move()
{
// do something.
}
}

VB.NET

Public Class BMW


Implements ITruck
Implements ICar
Private Sub move() Implements ICar.move
' do something.
End Sub
Private Sub move() Implements ITruck.move
' do something.
End Sub
End Class

BMW object
:
C#

BMW ahmedCar=new BMW();


ICar temp= (ICar)ahmedCar;
temp.move();

VB.NET
Dim ahmedCar As New BMW()
Dim temp As ICar = DirectCast(ahmedCar, ICar)
temp.move()

186

Interfaces

IEnumerableInterface .3
interfaces
Class implement interface
interface IEnumerable .


LINQ

C#

;} "string[] users = { "Ahmed", "Mohammed

VB.NET
}"Dim users As String() = {"Ahmed", "Mohammed

for each
:

C#
)foreach (string us in users
{
;)Console.WriteLine(us
}

VB.NET
For Each us As String In users
)Console.WriteLine(us
Next

array
:

187

Interfaces

C#
public class employee
{
int emp_number;
string emp_name;
}

VB.NET
Public Class employee
Private emp_number As Integer
Private emp_name As String
End Class

C#
public class users
{
employee[] emp =
users()
{
emp[0] = new
emp[1] = new
emp[2] = new
}
}

new employee[3];

employee(10, "Ahmed");
employee(20, "Khaled");
employee(30, "Ali");

VB.NET
Public Class users
Private emp As employee() = New employee(2) {}
Private Sub New()
emp(0) = New employee(10, "Ahmed")
emp(1) = New employee(20, "Khaled")
emp(2) = New employee(30, "Ali")
End Sub
End Class

C#

: for each

foreach (employee e in emp)


{
}

188

Interfaces

VB.NET

For Each e As employee In emp


Next

.IEnumerable loop
:IEnumerable interface

C#
public interface IEnumerable
{
IEnumerator GetEnumerator();
}

VB.NET

Public Interface IEnumerable


Function GetEnumerator() As IEnumerator
End Interface

IEnumerator interface

C#
public interface IEnumerator
{
bool MoveNext();
object Current { get; }
void Reset();
}

VB.NET

Public Interface IEnumerator


Function MoveNext() As Boolean
ReadOnly Property Current() As Object
Sub Reset()
End Interface

interface implements users


: GetEnumerator() implement

189

Interfaces

C#
public class users : IEnumerable
{
employee[] emp = new employee[4];
users()
{
emp[0] = new employee(10, "Ahmed");
emp[1] = new employee(20, "Khaled");
emp[2] = new employee(30, "Ali");
emp[3] = new employee(40, "Sami");
}
public IEnumerator GetEnumerator()
{
return emp.GetEnumerator();
}
}

VB.NET
Public Class users
Implements IEnumerable
Private emp As employee() = New employee(3) {}
Private Sub New()
emp(0) = New employee(10, "Ahmed")
emp(1) = New employee(20, "Khaled")
emp(2) = New employee(30, "Ali")
emp(3) = New employee(40, "Sami")
End Sub
Public Function GetEnumerator() As IEnumerator
Return emp.GetEnumerator()
End Function
End Class

:
C#

IEnumerator i = emp.GetEnumerator();
i.MoveNext();
employee myCar = (employee)i.Current;

VB.NET
Dim i As IEnumerator = emp.GetEnumerator()
i.MoveNext()
Dim myCar As employee = DirectCast(i.Current, employee)

190

Interfaces




. moveNext

yield :

C#
)(public IEnumerator GetEnumerator
{
;]yield return emp[0
;]yield return emp[1
;]yield return emp[2
;yield break
}


yield break .
LINQ
.

ICloneableInterface .4
clone :

C#
;int x = 5
;int y = x

VB.NET
Dim x As Integer = 5
Dim y As Integer = x

191

Interfaces

x y :

C#
;)"Car x = new Car("BMW
;Car y = x

VB.NET
)"Dim x As New Car("BMW
Dim y As Car = x

x y y x
x y .
clone .
ICloneable clone
:

C#
)(public object Clone
{
;)return new Car(this.carName
}

VB.NET
Public Function Clone() As Object
)Return New Car(Me.carName
End Function

Clone :

C#
;)"Car x = new Car("BMW
;)(Car y = (Car)x.Clone

VB.NET
)"Dim x As New Car("BMW
)Dim y As car = DirectCast(x.Clone(), Car

192

Interfaces

IComparableInterface .5
interface
interface :

C#
public interface IComparable
{
;)int CompareTo(object o
}

VB.NET
Public Interface IComparable
Function CompareTo(ByVal o As Object) As Integer
End Interface

0
1 1- .


. .Equals

.
IComparable
:
CompareTo

C#
)int IComparable.CompareTo(object obj
{
;Car temp = (Car)obj
)if (this.year > temp.year
;return 1
)if (this.year < temp.year
;return -1
else
;return 0
}

193

Interfaces

VB.NET
Private Function CompareTo(ByVal obj As Object) As Integer Implements
IComparable.CompareTo
)Dim temp As Car = DirectCast(obj, Car
If Me.year > temp.year Then
Return 1
End If
If Me.year < temp.year Then
Return -1
Else
Return 0
End If
End Function

1- 0 1
100- 0 94

.

Sort
array myNumbers
:

C#
;)Array.Sort(myNumbers

VB.NET
)Array.Sort(myNumbers


.
car IComparableinterface
CompareTo
interface
.
check

.

194

195

10

196

197

.1 SyntaxErrors
AdvancedProgrammingEnvironments
VisualStudio,NetBeans...etc
:

VB.NET
if x.Nome = somevalue

Nome
Visual Studio.net
2008 .

.2 LogicalErrors

:

VB.NET
Dim x as Byte= 100000

Byte
.
object new ...

Logic Errors
.warnings

198

LogicalErrors :

UserError Byte
10

.

Exceptions

null
nullabletype ReadOnly
.

Bugs



... %99

.


.

199

System.Exception .3
.net
CLR
: System.Exception

C#
public class Exception : ISerializable, _Exception
{
// Public constructors
public Exception(string message, Exception innerException);
public Exception(string message);
public Exception();
// Methods
public virtual Exception GetBaseException();
public virtual void GetObjectData(SerializationInfo info,
StreamingContext context);
// Properties
public virtual IDictionary Data { get; }
public virtual string HelpLink { get; set; }
public System.Exception InnerException { get; }
public virtual string Message { get; }
public virtual string Source { get; set; }
public virtual string StackTrace { get; }
public MethodBase TargetSite { get; }
}

200


VB.NET

Public Class Exception


Implements ISerializable
Inherits _Exception
' Public constructors
Public Sub New(ByVal message As String, ByVal innerException As Exception)
End Sub
Public Sub New(ByVal message As String)
End Sub
Public Sub New()
End Sub
' Methods
Public Overridable Function GetBaseException() As Exception
End Function
Public Overridable Sub GetObjectData(ByVal info As SerializationInfo, ByVal
context As StreamingContext)
End Sub
' Properties
Public Overridable ReadOnly Property Data() As IDictionary
Get
End Get
End Property
Public Overridable Property HelpLink() As String
Get
End Get
Set(ByVal value As String)
End Set
End Property
Public ReadOnly Property InnerException() As System.Exception
Get
End Get
End Property
Public Overridable ReadOnly Property Message() As String
Get
End Get
End Property
Public Overridable Property Source() As String
Get
End Get
Set(ByVal value As String)
End Set
End Property
Public Overridable ReadOnly Property StackTrace() As String
Get
End Get
End Property
Public ReadOnly Property TargetSite() As MethodBase
Get
End Get
End Property
End Class

201

Message

Source

throw

HelpLink


IT

.1 .10 Exception

.4 ThrowingExceptions
throw
.
throw check

:

C#
))"if (!System.IO.File.Exists("c:\\ahmed.txt
{
;)"Console.WriteLine("there is no file
}

VB.NET
If Not System.IO.File.Exists("c:\ahmed.txt") Then
)"Console.WriteLine("there is no file
End If



throw
. throw :

202

C#
))"if (!System.IO.File.Exists("c:\\ahmed.txt
{
;)"throw new Exception("there is no file
}

VB.NET
If Not System.IO.File.Exists("c:\ahmed.txt") Then
)"Throw New Exception("there is no file
End If

.5 CatchingExceptions

Try

C#
try
{
;x += 100
;)"console.writeLine("no errror
}
catch
{
;)"!console.writeLine("some error
}

VB.NET
Try
x += 100
)"Console.WriteLine("no errror
Catch
)"!Console.WriteLine("some error
End Try

catch
.

203

C#
try
{
x += 100;
console.writeLine("no errror");
}
catch (Exception e)
{
Console.WriteLine("Method: {0}", e.TargetSite);
Console.WriteLine("Message: {0}", e.Message);
Console.WriteLine("Source: {0}", e.Source);
}

VB.NET

Try
x += 100
Console.WriteLine("no errror")
Catch e As Exception
Console.WriteLine("Method: {0}", e.TargetSite)
Console.WriteLine("Message: {0}", e.Message)
Console.WriteLine("Source: {0}", e.Source)
End Try



: overflow

C#
try
{
x += 100;
console.writeLine("no errror");
}
catch (OverflowException e0)
{
Console.WriteLine("value of x more than up bound");
}
catch (Exception e)
{
Console.WriteLine("Method: {0}", e.TargetSite);
Console.WriteLine("Message: {0}", e.Message);
Console.WriteLine("Source: {0}", e.Source);
}

204

VB.NET
Try
x += 100
Console.WriteLine("no errror")
Catch e0 As OverflowException
Console.WriteLine("value of x more than up bound")
Catch e As Exception
Console.WriteLine("Method: {0}", e.TargetSite)
Console.WriteLine("Message: {0}", e.Message)
Console.WriteLine("Source: {0}", e.Source)
End Try

Finally .1 .5
try - catch
x

:

C#
try
{
x += 100;
console.writeLine("no errror");
}
catch (Exception e)
{
Console.WriteLine("Method: {0}", e.TargetSite);
Console.WriteLine("Message: {0}", e.Message);
Console.WriteLine("Source: {0}", e.Source);
}
finally
{
Console.WriteLine("somehing");
}

VB.NET
Try
x += 100
Console.WriteLine("no errror")
Catch e As Exception
Console.WriteLine("Method: {0}", e.TargetSite)
Console.WriteLine("Message: {0}", e.Message)
Console.WriteLine("Source: {0}", e.Source)
Finally
Console.WriteLine("somehing")
End Try

205

.2 .5 break
break Exit Try
.

.3 .5 TargetSite
throw
Debug .

.4 .5 HelpLink

:

C#
try
{
;m += 100
;)"Console.WriteLine("no errror
}
)catch (Exception e
{
;"e.HelpLink = "www.ahmedgamal-space.blogspot.com
}

VB.NET
Try
m += 100
)"Console.WriteLine("no errror
Catch e As Exception
"e.HelpLink = "www.ahmedgamal-space.blogspot.com
End Try

206

.6

ApplicationException
Remoting Serializable
:

C#

public class NewException : ApplicationException, ISerializable


{
public NewException()
{
// something here
}
public NewException(string message)
{
// something here
}
public NewException(string message, Exception inner)
{
// something here.
}
// Serilization
protected NewException(SerializationInfo info, StreamingContext context)
{
// Add something here.
}
}

207

VB.NET
Public Class NewException
Inherits ApplicationException
Implements ISerializable
Public Sub New()
' Add something here.
End Sub
Public Sub New(ByVal message As String)
' Add something here.
End Sub
Public Sub New(ByVal message As String, ByVal inner As Exception)
' Add something here.
End Sub
' Sterilization
Protected Sub New(ByVal info As SerializationInfo, ByVal context As
StreamingContext)
' Add something here.
End Sub
End Class

:MSDN

http://msdn.microsoft.com/en-us/library/ms229014(VS.80).aspx

208

209

11
Collections

210

211

Collections

container
array array
. array
collections .

.1 InterfacesSystem.Collections
collection :

:ICollection
Size
IsSynchronized :

C#
public interface ICollection : IEnumerable
{
} ;int Count { get
} ;bool IsSynchronized { get
} ;object SyncRoot { get
;)void CopyTo(Array array, int index
}

VB.NET
Public Interface ICollection
Inherits IEnumerable
ReadOnly Property Count() As Integer
ReadOnly Property IsSynchronized() As Boolean
ReadOnly Property SyncRoot() As Object
)Sub CopyTo(ByVal array As Array, ByVal index As Integer
End Interface

:IComparer

:IDictionary



. :

212

Collections

C#
public interface IDictionary :ICollection, IEnumerable
{
bool IsFixedSize { get; }
bool IsReadOnly { get; }
object this[object key] { get; set; }
ICollection Keys { get; }
ICollection Values { get; }
void Add(object key, object value);
void Clear();
bool Contains(object key);
IDictionaryEnumerator GetEnumerator();
void Remove(object key);
}

VB.NET
Public Interface IDictionary
Inherits ICollection
Inherits IEnumerable
ReadOnly Property IsFixedSize() As Boolean
ReadOnly Property IsReadOnly() As Boolean
Default Property Item(ByVal key As Object) As Object
ReadOnly Property Keys() As ICollection
ReadOnly Property Values() As ICollection
Sub Add(ByVal key As Object, ByVal value As Object)
Sub Clear()
Function Contains(ByVal key As Object) As Boolean
Function GetEnumerator() As IDictionaryEnumerator
Sub Remove(ByVal key As Object)
End Interface

:IEnumerable
.

:IEnumerator
.

:IDictionaryEnumerator
interface GetEnumerator IDictionary
:

213

Collections

C#
public interface IDictionaryEnumerator : IEnumerator
{
DictionaryEntry Entry { get; }
object Key { get; }
object Value { get; }
}

VB.NET
Public Interface IDictionaryEnumerator
Inherits IEnumerator
ReadOnly Property Entry() As DictionaryEntry
ReadOnly Property Key() As Object
ReadOnly Property Value() As Object
End Interface

:IHashCodeProvider
.GetHashCode collection hashcode

:IList

:
C#
public interface IList :ICollection, IEnumerable
{
bool IsFixedSize { get; }
bool IsReadOnly { get; }
object this[int index] { get; set; }
int Add(object value);
void Clear();
bool Contains(object value);
int IndexOf(object value);
void Insert(int index, object value);
void Remove(object value);
void RemoveAt(int index);
}

214

Collections

VB.NET
Public Interface IList
Inherits ICollection
Inherits IEnumerable
ReadOnly Property IsFixedSize() As Boolean
ReadOnly Property IsReadOnly() As Boolean
Default Property Item(ByVal index As Integer) As Object
Function Add(ByVal value As Object) As Integer
Sub Clear()
Function Contains(ByVal value As Object) As Boolean
Function IndexOf(ByVal value As Object) As Integer
Sub Insert(ByVal index As Integer, ByVal value As Object)
Sub Remove(ByVal value As Object)
Sub RemoveAt(ByVal index As Integer)
End Interface

System.Collections .2
:
ArrayList
Hashtable
Queue
SortedList
Stack

ArrayList .1 .2
array array

.
)(
:
C#

Car[] carArray = new Car[4];

VB.NET
Dim carArray As Car() = New Car(3)

215

Collections


... array
.
using System.Collection
.

C#
;using System.Collections

VB.NET
Imports System.Collections

ArrayList
ArrayList :

C#
;)(ArrayList carList = new ArrayList

VB.NET
)(Dim carList As New ArrayList

C#
;)Car temp = new Car("BMW", 1990
;)carList.Add(temp

VB.NET
)Dim temp As New Car("BMW", 1990
)carList.Add(temp


Insert
:

C#
;)carList.Insert(temp

216

Collections

VB.NET
)carList.Insert(temp

C#
;)(carList.Clear

VB.NET
)(carList.Clear

C#
;)carList.RemoveAt(4

VB.NET
)carList.RemoveAt(4

C#
;)carList.Remove(temp

VB.NET
)carList.Remove(temp

Count
:

C#
)for (int i = 0; i < carList.Count; i++
{
;]temp = (Car)carList[i
}

217

Collections

VB.NET
For i As Integer = 0 To carList.Count - 1
)temp = DirectCast(carList(i), Car
Next

Sort array
ToArray Reverse IndexOf
temp
:

C#
;)int find = carList.IndexOf(temp, 0

VB.NET
)Dim find As Integer = carList.IndexOf(temp, 0

Find
.
0

HashTable .2 .2
DataStructure
HashTable
:

http://en.wikipedia.org/wiki/Hash_table

HashTable keys
Indexes .

218

Collection
ns

HashTab
.1 .11 ble


HashT Linked List
Table




Linked
d List


Has
shTable
Re .
Add,AddR emove
A
Range

Que
eue .3 .2




Enqueue
Que
eue

De
equeue


Que
eue


)

Task
Slides

....
:


219

Collections
C#

;)(Queue empQueue = new Queue


;)(employee temp = new employee
)for (int i = 0; i < 10; i++
{
;)(temp.userName = Console.ReadLine
;)empQueue.Enqueue(temp
}

VB.NET
)(Dim empQueue As New Queue
)(Dim temp As New employee
For i As Integer = 0 To 9
)(temp.userName = Console.ReadLine
)empQueue.Enqueue(temp
Next

.
Loop Dequeue
Count
.
Dequeue
Peek
.
DataStructure
Queue linkedlist circularqueue
.

Stack .4 .2
Queue LIFO Last Input First Output
Push
Pop Peek
.Stack

220

Collections

Stack :

C#
;)(Stack jobStack = new Stack

VB.NET
)(Dim jobStack As New Stack

Queue
Stack


Stack
.
Stack :
A+B
:
AB+
postfix Stack
Compilers.
postfix infix
FUTEX Group
Stack View
.
.

221

Collections

http://vb4arab.com/vb/uploaded/3/21207604046.rar

http://scriptasylum.com/tutorials/infix_postfix/infix_postfix.html

MSDN:

http://msdn2.microsoft.com/en-us/library/aa289149(VS.71).aspx

DataStructure

.Algorithms
System.Collections.Specialized
.

222

223

12

.net

224

225

.net

.net

.net2008
.

.1 Generics
.netFramework2.0
:
generics overloading

C#
)public static void print(int x
{
;)Console.WriteLine("Print As Integer {0}", x
}
)public static void print(long x
{
;)Console.WriteLine("Print As Long {0}", x
}
)public static void print(string x
{
;)Console.WriteLine("Print As String {0}", x
}

VB.NET
)As Integer
)Integer {0}", x
)As Long
)Long {0}", x
)As String
)String {0}", x

Public Shared Sub print(ByVal x


Console.WriteLine("Print As
End Sub
Public Shared Sub print(ByVal x
Console.WriteLine("Print As
End Sub
Public Shared Sub print(ByVal x
Console.WriteLine("Print As
End Sub


longs
:

226

.net
C#
;)"print("Ahmed
;)print(12
;)print(1000000000000

VB.NET
)"Print("Ahmed
)Print(12
)Print(1000000000000

.1 .12
Generic
> <T

C#
)public static void print<T>(T x
{
;)Console.WriteLine("Print As {0}: {1}", typeof(T), x
}

227

.net

VB.NET
)Public Shared Sub print(Of T)(ByVal x As T
)Console.WriteLine("Print As {0}: {1}", GetType(T), x
End Sub

.2 .12

StructureandClassGenerics .1 .1
methods Generics Classes
Structs class
class .struct

) (

228

.net

Identify
.

name number
Generics :

C#
>public class product<T
{
;private T Identify
)public product(T val
{
;Identify = val
;)Console.WriteLine(Identify
}
}

VB.NET
)Public Class product(Of T
Private Identify As T
)Public Sub New(ByVal val As T
Identify = val
)Console.WriteLine(Identify
End Sub
End Class

C#
;)product<int> prd = new product<int>(1001

VB.NET
)Dim prd As New product(Of Integer)(1001

C#
;)"product<string> prd2 = new product<string>("Some Product

229

.net

VB.NET
Dim prd2 As New product(Of String)("Some Product")

GenericCollection .2 .1
GenericClass
Generic Collection
: Collection Add,Delete ... etc
C#

public class MyCollection<T>


{
private List<T> myList = new List<T>();
public T GetItem(int pos)
{
return myList[pos];
}
public void AddItem(T it)
{
myList.Add(it);
}
public void ClearCars()
{
myList.Clear();
}
}

VB.NET
Public Class MyCollection(Of T)
Private myList As New List(Of T)()
Public Function GetItem(ByVal pos As Integer) As T
Return myList(pos)
End Function
Public Sub AddItem(ByVal it As T)
myList.Add(it)
End Sub
Public Sub ClearCars()
myList.Clear()
End Sub
End Class

230

.net



GenericCollection
Employee .... Car Colelctions
:

C#
Identify = val;
Console.WriteLine(Identify);
MyCollection<Car> myCars = new MyCollection<Car>();
myCars.AddItem(temp);
MyCollection<Employee> myCars = new MyCollection<Employee>();
myCars.AddItem(tempEmployee);

VB.NET
Dim myCars As New MyCollection(Of Car)()
myCars.AddItem(temp)
Dim myCars As New MyCollection(Of Employee)()
myCars.AddItem(tempEmployee)

C#
MyCollection<int> myCars = new MyCollection<int>();
myCars.AddItem(12);

VB.NET
Dim myCars As New MyCollection(Of Integer)()
myCars.AddItem(12)

GenericCollection


.name
. where

where T .3 .1
GenericCollection
:

231

.net

where T : struct
ValueType
RefernceType where T : class
Constructor where T :new()
class where T : ClassName
. interface

where T : IInterfaceName

Generics .1 .12
:
C#

public class Example <T> where T : class, IComparable, new()

VB.NET

Public Class Example(Of T As {Class, IComparable, New})

IComparable reference T
.Constructor
:

C#
public class Example<K, T> where K : class, new()
where T : IComparable<T>

VB.NET

Public Class Example(Of K As {Class, New}, T As IComparable(Of T))

T constructor Reference K
. IComparable
.
T

232

.net

Delegates .2
advanced .net programming
.Delegates
.
int int
:

C#
public int
{
return
}
public int
{
return
}
public int
{
return
}
public int
{
return
}
public int
{
return
}
public int
{
return
}

233

ConvertEGToD(int EG)
EG * 5.45;
ConvertRSToD(int RS)
RS * 3.75;
ConvertEGToRS(int EG)
EG * 1.45;
ConvertDToRS(int D)
D * 3.75;
ConvertDToEG(int D)
D / 5.45;
ConvertRSToEG(int RS)
RS / 1.45;

.net

VB.NET
Public Function ConvertEGToD(ByVal EG As Integer) As Integer
Return EG * 5.45
End Function
Public Function ConvertRSToD(ByVal RS As Integer) As Integer
Return RS * 3.75
End Function
Public Function ConvertEGToRS(ByVal EG As Integer) As Integer
Return EG * 1.45
End Function
Public Function ConvertDToRS(ByVal D As Integer) As Integer
Return D * 3.75
End Function
Public Function ConvertDToEG(ByVal D As Integer) As Integer
Return D / 5.45
End Function
Public Function ConvertRSToEG(ByVal RS As Integer) As Integer
Return RS / 1.45
End Function


.

.

switch if
:
C#

if (Operation == 0)
result = ConvertDToEG(userInput);
else if(Operation == 1)
result = ConvertRSToD(userInput);

VB.NET

If Operation = 0 Then
result = ConvertDToEG(userInput)
ElseIf Operation = 1 Then
result = ConvertRSToD(userInput)
End If

234

.net


. Operation
.Delegates

Delegates .1 .2
Delegates
Delegate output input .
:

C#
public delegate int myDelegate(int value);

VB.NET
Public Delegate Function myDelegate(ByVal value As Integer) As Integer

- -

C#

if (Operation == 0)
{
myDelegate aDelegate = new myDelegate(ConvertDToEG);
result = aDelegate(userInput);
}
else if (Operation == 1)
{
myDelegate aDelegate = new myDelegate(ConvertRSToD);
result = aDelegate(userInput);
}

VB.NET
If Operation = 0 Then
Dim aDelegate As New myDelegate(ConvertDToEG)
result = aDelegate(userInput)
ElseIf Operation = 1 Then
Dim aDelegate As New myDelegate(ConvertRSToD)
result = aDelegate(userInput)
End If

235

.net

Delegate
aDelegate
:

C#
)if (Operation == 0
{
;)myDelegate aDelegate = new myDelegate(ConvertDToEG
}
)else if (Operation == 1
{
;)myDelegate aDelegate = new myDelegate(ConvertRSToD
}
//
;)result = aDelegate(userInput

VB.NET
If Operation = 0 Then
)Dim aDelegate As New myDelegate(ConvertDToEG
ElseIf Operation = 1 Then
)Dim aDelegate As New myDelegate(ConvertRSToD
End If
'
)result = aDelegate(userInput


.
Delegate
.

.2 .2 Events
) ...

) ...( Delegates Event

236

.net

Delegates
List .Delegate
... Event

Delegate

Delegate :

C#
;)public delegate void CarEventHandler(string msg

VB.NET
)Public Delegate Sub CarEventHandler(ByVal msg As String

C#
;public event CarEventHandler Exploded
;public event CarEventHandler Damaged

VB.NET
Public Event Exploded As CarEventHandler
Public Event Damaged As CarEventHandler

C#
;)"Damaged("my car

VB.NET
)"Damaged("my car

event == null
.

:

C#
;)Car.EngineHandler d = new Car.CarEventHandler(CarExploded

237

.net

VB.NET
)Dim d As Car.EngineHandler = New Car.CarEventHandler(CarExploded

CarExploded
:
Damaged

C#
)public void CarExploded(string msg
{
;)Console.WriteLine(msg
}

VB.NET
)Public Sub CarExploded(ByVal msg As String
)Console.WriteLine(msg
End Sub

.3 AnonymousMethods C#
Delegates
. Delegate
Events
:

C#
;)t.SomeEvent += new SomeDelegate(MyEventHandler


Delegate Anonymous
Methods .
:

C#
{t.SomeEvent += delegate
;)"Console.WriteLine("Some Text
}

238

.net

.C#
:

C#
)t.SomeEvent += delegate(object sender, CarEventArgs e
{
;)Console.WriteLine("Some Text {0}",e.msg
}

Anonymousmethod
.

.4
6 :

VB.NET
Dim x
x = 10

Object
.
.net 2008
:

C#
var x = 2.3 // double

VB.NET
Dim x = 2.3 double


var return

value var .null

239

.net

var:

C#
class classname
{
//
;private var varInt = 10
return value . //
} {)var functionname(var x, var y
)(void somefunction
{
null //
;var varNull=null
null //
;var? varNullable = 12
//
;var m
}
}

.5 ExtensionMethods
ExtensionMethods .net2008
.
string
:
Regex

C#
public static class Extensions
{
)public static bool IsValidEmailAddress(this string s
{
;)"Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$
;)return regex.IsMatch(s
}
}

240

.net

VB.NET

Imports System.Runtime.CompilerServices
Module StringExtensions
<Extension()>_
Public Function IsValidEmailAddress(ByVal s As String) As Boolean
Dim regex As New Regex("\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")
Return regex.IsMatch(s)
End Function
End Module

: string

C#
string mailExample = "email@mail. com";
MessageBox.Show(mailExample.IsValidEmailAddress.toString());

VB.NET
Dim mailExample As String = "email@mail. com"
MessageBox.Show(mailExample.IsValidEmailAddress.toString())

AutomaticProperties .6
Get Set Properties
:

C#
public class myclass
{
private string _name;
public string name
{
get {return _name;}
set {_name=value;}
}
}

241

.net

VB.NET
Public Class [myclass]
Private _name As String
Public Property name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
End Class

C#
public class myclass
{
public string name{get; set;}
}

VB.NET
Public Class [myclass]
Public Property name() As String
Get
End Get
Set(ByVal value As String)
End Set
End Property
End Class

LamdaExpressions .7

AnonymousMethods

:2

242

.net

C#

static void TraditionalDelegateSyntax()


{
List<int> list = new List<int>();
list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 });
Predicate<int> callback = new Predicate<int>(IsEvenNumber);
List<int> evenNumbers = list.FindAll(callback);
Console.WriteLine("Here are your even numbers:");
foreach (int evenNumber in evenNumbers)
{
Console.Write("{0}\t", evenNumber);
}
}
static bool IsEvenNumber(int i)
{
return (i % 2) == 0;
}

VB.NET

Private Shared Sub TraditionalDelegateSyntax()


Dim list As New List(Of Integer)()
list.AddRange(New Integer() {20, 1, 4, 8, 9, 44})
Dim callback As New Predicate(Of Integer)(AddressOf IsEvenNumber)
Dim evenNumbers As List(Of Integer) = list.FindAll(callback)
Console.WriteLine("Here are your even numbers:")
For Each evenNumber As Integer In evenNumbers
Console.Write("{0}" & Chr(9) & "", evenNumber)
Next
End Sub
Private Shared Function IsEvenNumber(ByVal i As Integer) As Boolean
Return (i Mod 2) = 0
End Function

C#2008 AnonymousMethods
:

243

.net

C#
static void TraditionalDelegateSyntax()
{
List<int> list = new List<int>();
list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 });
Predicate<int> callback = new Predicate<int>(IsEvenNumber);
List<int> evenNumbers = list.FindAll(callback);
Console.WriteLine("Here are your even numbers:");
foreach (int evenNumber in evenNumbers)
{
Console.Write("{0}\t", evenNumber);
}
}
static bool IsEvenNumber(int i)
{
return (i % 2) == 0;
}

VB.NET
Dim list As New List(Of Integer)()
list.AddRange(New Integer() {20, 1, 4, 8, 9, 44})
Dim evenNumbers As List(Of Integer) = list.FindAll(AddressOf
ConvertedAnonymousMethod1)
Console.WriteLine("Here are your even numbers:")
For Each evenNumber As Integer In evenNumbers
Console.Write("{0}" & Chr(9) & "", evenNumber)
Next

LambdaExpressions .net2008
:

X => f(X)

: i%2==0 True
C#

(int i) => (i % 2) == 0;

VB.NET
Function(i As Integer) (i Mod 2) = 0

244

.net

int i
: Lambda

C#
List<int> list = new List<int>();
list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 });
List<int> evenNumbers = list.FindAll(i => (i % 2) == 0);
Console.WriteLine("Here are your even numbers:");
foreach (int evenNumber in evenNumbers)
{
Console.Write("{0}\t", evenNumber);
}

VB.NET

Dim list As New List(Of Integer)()


list.AddRange(New Integer() {20, 1, 4, 8, 9, 44})
Dim evenNumbers As List(Of Integer) = list.FindAll(Function(i As ) (i Mod 2) =
0)
Console.WriteLine("Here are your even numbers:")
For Each evenNumber As Integer In evenNumbers
Console.Write("{0}" & vbTab, evenNumber)
Next

:returnvalue
true , false
:

C#
List<int> evenNumbers = list.FindAll((i) =>
{
Console.WriteLine("value of i is currently: {0}", i);
bool isEven = ((i % 2) == 0);
return isEven;
});

...

:Lambda
. Lambda -

245

.net

OOP Overloads .Overrides


As .
.
Return .
End }{ .Lambda
Optinal .VB
.Generic

.8

ObjectInitializerSyntax


.
:.net2008

C#
public class Employee
{
;private string _name
;private string _age
;private string _salary
public string name
{
} ;get { return _name
} ;set { _name = value
}
public string age
{
} ;get { return _age
} ;set { _age = value
}
public string salary
{
} ;get { return _salary
} ;set { _salary = value
}
}

246

.net

VB.NET

Public Class Employee


Private _name As String
Private _age As String
Private _salary As String
Public Property name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property age() As String
Get
Return _age
End Get
Set(ByVal value As String)
_age = value
End Set
End Property
Public Property salary() As String
Get
Return _salary
End Get
Set(ByVal value As String)
_salary = value
End Set
End Property
End Class

: automaticproperty .net2008
VB.NET
Public Class Employee
Public Property name() As String
Get: End Get
Set(ByVal value As String)
End Set
End Property
Public Property age() As String
Get: End Get
Set(ByVal value As String)
End Set
End Property
Public Property salary() As String
Get:End Get
Set(ByVal value As String)
End Set
End Property
End Class

247

.net

C#
public class Employee
{
public string name { get; set; }
public string age { get; set; }
public string salary { get; set; }
}

.net 2008 Object Initializer Syntax



:

C#
Employee e = new Employee();
e.Name="Ahmed";
e.Age=15;
e.salary=6000;

VB.NET
Dim e As Employee = New Employee()
e.Name = "Ahmed"
e.Age = 15
e.salary = 6000

C#
Employee e = new Employee { Name = "Ahmed", Age = 15, salary = 6000 };

VB.NET
Dim e As Employee = New Employee With {.Name="Ahmed" ,.Age=15,.Salary=1500}

AnonymousTypes

.9

.net2008
. AnonymousTypes

248

.net

var

:

C#
;} var e = new { Name = "Ahmed", Age = 20

VB.NET
}Dim e As Employee = New Employee With {.Name="Ahmed" ,.Age=15,.Salary=1500

e.Name

e.Age

AnonymousTypes System.Object
.


LINQ
:

C#
;} var result = from emp in employee select new { emp.Name, emp.Salary

VB.NET
Dim namePriceQuery = From emp In employee Select emp.Name, emp.Salary

KeyProperties

-

249

.net

Hash Code .

Equality

:
. Scope .
. . .
...

PartialMethods .10

Partial
:

C#
partial class Car
{
}

250

.net

VB.NET
Partial Class Car
End Class

.net2005 PartialMethods
:

C#
)partial void methodname(string parm
{
}

VB.NET
)Partial Private Sub methodname(ByVal parm As String

End Sub

GarbageCollector .11
..

Objectlifetime .GC
OBJECT FROM CLASS Refernce
heap reference stack
.
reference stack

garbagecollector GC

251

.net


.
C++
GC .
=null GC

.

.1 .11 GC
GC
ProCsharp2008 :

.1 .12 GC

252

.net

)(:Finalize
overriding
.
:

C#
class example
{
)(~example
{
;)(Console.Beep
}
}

VB.NET
Class example
)(Protected Overrides Sub Finalize
Try
)(Console.Beep
Finally
)(MyBase.Finalize
End Try
End Sub
End Class

OperatorOverloading .12

Integer + - ....

.
String +
Structure Point
:

C#

public struct Point


{
;private int x, y
)public Point(int xPos, int yPos
{
;x = xPos
;y = yPos
}
}

253

.net

VB.NET
Public Structure Point
Private x As Integer, y As Integer
Public Sub New(ByVal xPos As Integer, ByVal yPos As Integer)
x = xPos
y = yPos
End Sub
End Structure

- +
.
y x
Point structure
.
C#

: structure

public struct Point


{
private int x, y;
public Point(int xPos, int yPos)
{
x = xPos;
y = yPos;
}
public static Point operator +(Point
{ return new Point(p1.x + p2.x, p1.y
public static Point operator -(Point
{ return new Point(p1.x - p2.x, p1.y
}

254

p1, Point p2)


+ p2.y); }
p1, Point p2)
- p2.y); }

.net

VB.NET
Public Structure Point
Private x As Integer, y As Integer
Public Sub New(ByVal xPos As Integer, ByVal yPos As Integer)
x = xPos
y = yPos
End Sub
Public Shared Operator +(ByVal p1 As Point, ByVal p2 As Point) As Point
Return New Point(p1.x + p2.x, p1.y + p2.y)
End Operator
Public Shared Operator -(ByVal p1 As Point, ByVal p2 As Point) As Point
Return New Point(p1.x - p2.x, p1.y - p2.y)
End Operator
End Structure

C#

Point p3 = p1 + p2;

VB.NET

Dim p3 As Point = p1 + p2

C#

.Points
:

p2-=p1;

VB.NET

p2-=p1

static
. overloading function
overloading
: -- ++

255

.net

C#
public static Point operator ++(Point
{
return new Point(p1.x + 1, p1.y +
}
public static Point operator --(Point
{
return new Point(p1.x - 1, p1.y }

p1)
1);
p1)
1);

== !=
: Equals overriding

C#
public override bool Equals(object o)
{
return o.ToString() == this.ToString();
}
public static bool operator ==(Point p1, Point p2)
{
return p1.Equals(p2);
}
public static bool operator !=(Point p1, Point p2)
{
return !p1.Equals(p2);
}

VB.NET
Public Overloads Overrides Function Equals(ByVal o As Object) As Boolean
Return o.ToString() = Me.ToString()
End Function
Public Shared Operator =(ByVal p1 As Point, ByVal p2 As Point) As Boolean
Return p1.Equals(p2)
End Operator
Public Shared Operator <>(ByVal p1 As Point, ByVal p2 As Point) As Boolean
Return Not p1.Equals(p2)
End Operator

overloading
:

256

.net

.13 Pointers
C++ pointer
value type reference type
pointertype .
unsafe
code pointers
:

.2 .12 Unsafe code .


pointers
:

257

.net

C#
class Program
{
)static void Main(string[] args
{
unsafe
{
!// Work with pointer types here
}
!// Can't work with pointers here
}
}

pointers
:

pointer

&

>-


pointer

-- ++
!= ==

- .

.2 .12 .
unsafecode
safecode .

unsafecode
.

dll's COM Components
.pointers
.
pixels Image
Processing GetPixel SetPixel

258

.net

pixels
unsafe code pointers pixels
GetPixel SetPixel

pointers ...

...
pointer :

C#
;public Node* Left

structure class unsafe :

C#
public unsafe struct Node
{
;public int Value
;public Node* Left
;public Node* Right
}

C#
)unsafe static void SquareIntPointer(int* myIntPointer
{
// Square the value just for a test.
;*myIntPointer *= *myIntPointer
}

* &
:

C#
;)SquareIntPointer(&myInt2

:
Value Node > -

C#
;n->Value=5

259

.net

VB.net
VB.net
System.Runtime.InteropServices Marshal
: C#

C#
Bitmap bitmap = new Bitmap(this.BackgroundImage);
unsafe
{
System.Drawing.Imaging.BitmapData bmpData = bitmap.LockBits(new
Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.ReadWrite,
PixelFormat.Format32bppArgb);
byte * pixel = (byte*)(void*)bmpData.Scan0;
//the last syntax is equivalent to:
//byte* pixel = (byte*)bmpData.Scan0.ToPointer();
pixel[0] = 255;
pixel += 4;
pixel[0] = 0;
}

: VB
VB.NET

Dim
Dim
Dim
Dim

bitmap As New Bitmap(Me.BackgroundImage)


width As Integer = bitmap.Width
height As Integer = bitmap.Height
bmpData As System.Drawing.Imaging.BitmapData = _
bitmap.LockBits(New Rectangle(0, 0, width, height) _
, System.Drawing.Imaging.ImageLockMode.ReadWrite, _
PixelFormat.Format32bppArgb)
System.Runtime.InteropServices.Marshal.WriteByte(bmpData.Scan0,
bmpData.Stride, 255)
System.Runtime.InteropServices.Marshal.WriteByte(bmpData.Scan0,
bmpData.Stride + 4, 0)
bitmap.UnlockBits(bmpData)

. ***

260

.net

QueryExpressions .14
QueryExpressions LINQ
.net 2008
.
:

C#
from d in developers
"where d.Language =="C#
;select d.Name

VB.NET
_ )(From d In developers
_ )"Where(d.Language = "C#
Select d.Name

:SQL

SQL
"Select name from developers where language = "C#



DataReader
.
LINQ :

C#
;using System.Linq

261

.net

VB.NET
Imports System.Linq

LINQ Array
:
Array

C#
;}"string[] userNames = {"Ahmed", "Ali","Mohammed", "Ahmed","Ramy", "Khaled

VB.NET
Dim userNames As String() = {"Ahmed", "Ali", "Mohammed", "Ahmed", "Ramy",
}""Khaled

*** LINQ QueryExpressions




XML
""Ahmed

C#
IEnumerable<string> subset = from users in userNames
;where users == "Ahmed" orderby users select users

VB.NET
= Dim subset As IEnumerable = From users In userNames Where users
"Ahmed"OrderBy users Select users

array :

C#
)foreach (string s in subset
;)Console.WriteLine("Item: {0}", s

VB.NET
For Each s As String In subset
)Console.WriteLine("Item: {0}", s
Next

262

.net

C#
:

C#
IEnumerable<string> subset = from users in userNames
where users.Length > 3
orderby users
;select users

VB.NET

)Dim subset As IEnumerable = From users In userNames Where (users.Length > 3


OrderBy users Select users


var DimDataType

NullableTypes .
Lambda .

PreprocessorDirectives .15

:

263

.net

Preprocessor Directives Regions


.

#region, #endregion .1 .15



:

C#
#region "Class Employee"
public class Employee
{
private string _name;
private string _age;
private string _salary;
public string name
{
get { return _name; }
set { _name = value; }
}
public string age
{
get { return _age; }
set { _age = value; }
}
public string name
{
get { return _salary; }
set { _salary = value; }
}
}
#endregion

264

.net

VB.NET
#Region "Class Employee"
Public Class Employee
Private _name As String
Private _age As String
Private _salary As String
Public Property name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property age() As String
Get
Return _age
End Get
Set(ByVal value As String)
_age = value
End Set
End Property
Public Property name() As String
Get
Return _salary
End Get
Set(ByVal value As String)
_salary = value
End Set
End Property
End Class
#End Region

265

.net

.3 .12 #region #endregion

#if, #elif, #else, #endif .2 .15


ConditionalCodeCompilation
Debug

Release

266

.net

C#
#if DEBUG
Console.WriteLine("App directory: {0}", Environment.CurrentDirectory);
Console.WriteLine("Box: {0}", Environment.MachineName);
Console.WriteLine("OS: {0}", Environment.OSVersion);
Console.WriteLine(".NET Version: {0}", Environment.Version);
#endif

VB.NET

#If DEBUG Then


Console.WriteLine("App directory: {0}", Environment.CurrentDirectory)
Console.WriteLine("Box: {0}", Environment.MachineName)
Console.WriteLine("OS: {0}", Environment.OSVersion)
Console.WriteLine(".NET Version: {0}", Environment.Version)
#End If

.elif else

#define, #undef .3 .15


Debug symbol
symbol
Symbol symbol
. Mono Debug

. .4 .12
:

267

.net

C#
#define DEBUG
#define MONO_BUILD
using System;
namespace PreprocessorDirectives
{
class Program
{
static void Main(string[] args)
{
#if MONO_BUILD
Console.WriteLine("Compiling under Mono!");
#else
Console.WriteLine("Compiling under Microsoft .NET");
#endif
}
}
}

VB.NET
#Define DEBUG
#Define MONO_BUILD
Imports System
Namespace PreprocessorDirectives
Class Program
Private Shared Sub Main(ByVal args As String())
#If MONO_BUILD Then
Console.WriteLine("Compiling under Mono!")
#Else
Console.WriteLine("Compiling under Microsoft .NET")
Dim INDEXERS As n, OPERATORS As n, [AND] As n
POINTERS()
#End If
End Sub
End Class
End Namespace

268

.net

XMLCommenting .16
Comments

.
Comment

C#
// here we will do something, set x=startvalue
;)(x = FirstClass.Default

VB.NET
' here we will do something, set x=startvalue
)(x = FirstClass.Default

Comments XML
.

Java .javadoc
///
XML XML
.

><c

><code

><example

><exception

269

.net

Documentation

<list>

<param>

< permission>
Build

<remarks>

return;

<returns>

Documentation

<see>

( )

<seealso>

<summary>

<value>

XMLDocumentation .3 .12


:



C#
/// <summary>
/// Employee Class of the company
/// </summary>
partial class Employee
{
/// <summary>
///
/// </summary>
/// <param name="Firstname">first name of the employee</param>
/// <param name="Lastname">last name of the employee</param>
/// <param name="age">age of the employee</param>
public Employee(string Firstname, string Lastname, int age)
{
}
}

270

.net

VB.NET
''' <summary>
''' Employee Class of the company
''' </summary>
Partial Class Employee
''' <summary>
'''
''' </summary>
''' <param name="Firstname">first name of the employee</param>
''' <param name="Lastname">last name of the employee</param>
''' <param name="age">age of the employee</param>

Public Sub New(ByVal Firstname As String, ByVal Lastname As String, ByVal


age As Integer)
End Sub
End Class

.XML .5 .12

Documentation
Documentation Build
Build
: XML

271

.net

.6 .12 Documentation
:

.7 .12 Documentation.

272

.net

Documentation
Visual Studio 2008 XML
NDoc :

.8 .12 NDoc

Documetation

).(Help
... Comments
Sourceforge :

http://ndoc.sourceforge.net/

273

.net

.netAssemblies .17
.netassemblies
MSDN

.1 .17

namespace

namespace
namespace

C#
namespace example
{
class someclass
{
)(void method
{
}
}
}

VB.NET
Namespace example
Class someclass
)(Private Sub method
End Sub
End Class
End Namespace

classCar namespace
method

C#
)(void method
{
;)(classCar x = new classCar
}

274

.net

VB.NET
Private Sub method()
Dim x As New classCar()
End Sub

C#

example import

using example;
namespace example
{
class someclass
{
void method()
{
}
classCar x=new classCar();
}
}

VB.NET
Imports example
Namespace example
Class someclass
Private Sub method()
End Sub
Private x As New classCar()
End Class
End Namespace

DefaultNamespace .2 .17
:

. .9 .12

275

.net

.3 .17 Formatofa.NET
Assembly

dumpbin.exe
:

Win32fileheader
console GUI Dll
.

CLRfileheader
.netapplication
managedfile resources .

. .net

CILcode
JIT
.

Typemetadata
.

Anassemblymanifest
.

276

.net

Optionalembeddedresources

.

PrivateAssemblies .4 .17
PrivateAssemblies
Visual Studio
.
setup
.
dll .

SharedAssemblies .5 .17
dll
System.Windows.Forms.dl

.
unique
COM COM
) globallyuniqueidentifier(GUID COM
strong name 128
:

277

.net

- publickeyvalue AssemblyKeyFile
. AssemblyCulture

DigitalSignature hash public


.key

:
publickey SDKssn.exe

CommandPrompt
sn -k MyTestKeyPair.snk

. Properties page
.Signing

.18 MultiThreading
.1 .18
multitasking systems
.
.net

.multithreading


.

278

.net

System.Threading

:

Thread Thread
ThreadPool Threads

Enum ThreadState Thread


ThreadStart Thread
ThreadPriority Thread
.5 .12 System.Threading
:
Semaphore .1
Mutex .2
Monitor .3

.2 .18 Synchronization
Synchronization
Thread
:

)http://en.wikipedia.org/wiki/Semaphore_(programming
http://en.wikipedia.org/wiki/Mutual_exclusion
http://en.wikipedia.org/wiki/Monitor_(synchronization)

279

.net

System.Threading.Thread .3.18
threads
:

)(Sleep

thread

IsAlive

thread

IsBackground thread background


Priority

ThreadState

thread

Name

thread

)(Abort

)(Join

thread )(Join

)(Resume

)(Start

)(Suspend

.6 .12 Thread

.
:

280

.net

C#
static void Main(string[] args)
{
order1();
order2();
Console.ReadKey();
}
static void order1()
{
for (int i = 0; i < 100; i++)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(i.ToString() + " ");
}
}
static void order2()
{
for (int i = 100; i > 0; i--)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(i.ToString() + " ");
}
}

VB.NET
Private Shared Sub Main(ByVal args As String())
order1()
order2()
Console.ReadKey()
End Sub
Private Shared Sub order1()
For i As Integer = 0 To 99
Console.ForegroundColor = ConsoleColor.Green
Console.Write(i.ToString() + " ")
Next
End Sub
Private Shared Sub order2()
For i As Integer = 100 To 1 Step -1
Console.ForegroundColor = ConsoleColor.Red
Console.Write(i.ToString() + " ")
Next
End Sub

281

.net

.10 .12 .

threads
:

C#
)static void Main(string[] args
{
;)(order1
;)(order2
;)(Console.ReadKey
}
)(static void order1
{
)for (int i = 0; i < 100; i++
{
;Console.ForegroundColor = ConsoleColor.Green
;)" " Console.Write(i.ToString() +
}
}
)(static void order2
{
)for (int i = 100; i > 0; i--
{
;Console.ForegroundColor = ConsoleColor.Red
;)" " Console.Write(i.ToString() +
}
}

282

.net

VB.NET
Private Shared Sub Main(ByVal args As String())
Dim t1 As New System.Threading.Thread(order1)
t1.Start()
Dim t2 As New System.Threading.Thread(order2)
t2.Start()
Console.ReadKey()
End Sub
Private Shared Sub order1()
For i As Integer = 0 To 99
Console.ForegroundColor = ConsoleColor.Green
Console.Write(i.ToString() + " ")
Next
End Sub
Private Shared Sub order2()
For i As Integer = 100 To 1 Step -1
Console.ForegroundColor = ConsoleColor.Red
Console.Write(i.ToString() + " ")
Next
End Sub

. .11 .12

Priority
:

C#

t1.Priority = System.Threading.ThreadPriority.Highest;

VB.NET
t1.Priority = System.Threading.ThreadPriority.Highest

283

.net

.12 .12 .
.

System.Threading

.4.18 Priority
Priority threads
thread :
.1 : 1 .
.2 : 2 .
1 2 1.
2 :
1 1 1 2 1 1 1 ... 2
.

284

.net


: scheduling

http://en.wikipedia.org/wiki/Scheduling_%28computing%29

: enum Priority

C#
public enum ThreadPriority
{
AboveNormal,
BelowNormal,
Highest,
Idle,
Lowest,
Normal, // Default value.
TimeCritical
}

VB.NET
Public Enum ThreadPriority
AboveNormal
BelowNormal
Highest
Idle
Lowest
Normal
' Default value.
TimeCritical
End Enum

C#
t1.Priority = System.Threading.ThreadPriority.Highest;

VB.NET
t1.Priority = System.Threading.ThreadPriority.Highest

Sleep()
. ... suppose

285

.net

ParameterizedThreadStart .5.18

)( Start

thread
:
ParameterizedThreadStart

C#

;))Thread t = new Thread(new ParameterizedThreadStart(functionname


;)t.Start(parms

VB.NET
))Dim t As New Thread(New ParameterizedThreadStar(functionname
)t.Start(parms

ThreadStart
)( BeginInvoke )(EndInvoke

Foregroundandbackground .6.18
:threads

:ForegroundThread

Foreground threads thread


.

:BackgroundThread

:
backgroundthreads

C#
;t.IsBackground = true

286

.net

VB.NET
t.IsBackground = True

ThreadsSynchronization .7.18
Threads
SyncLock
.
SyncLockEnd SyncLock

:

C#
)lock (myLock
{
)for (i = 0; i <= 1000; i++
{
;))(Console.WriteLine(i.ToString
}
;)Console.Write(number
}

VB.NET
SyncLock myLock
For i = 0 To 1000
))(Console.WriteLine(i.ToString
Next i
)Console.Write(number
End SyncLock

myLock
number
.

287

.net

: -

http://vb4arab.com/vb/showthread.php?t=6341

ThreadPool .8.18

C#
)for (int i = 1; i <= 5; i++
{
;)ThreadPool.QueueUserWorkItem(sometask.Execute
}

VB.NET
For i As Integer = 1 To 5
)ThreadPool.QueueUserWorkItem(AddressOf sometask.Execute
Next

: -

http://vb4arab.com/vb/showthread.php?t=6340

BackgroundWorker .9.18


BackgroundWorker
webservice

.

288

.net

thread
BackgroundWorker
)( RunWorkerAsync

RunWorkerCompleted
.

C#
)for (int i = 1; i <= 5; i++
{
;)ThreadPool.QueueUserWorkItem(sometask.Execute
}

VB.NET
For i As Integer = 1 To 5
)ThreadPool.QueueUserWorkItem(AddressOf sometask.Execute
Next

Windows Form
:
BackgroundWorker

.12 .12 BackgroundWorker


DoWork
:
RunWorkerCompleted

289

.net

C#

private void ProcessNumbersBackgroundWorker_DoWork(object sender,


DoWorkEventArgs e)
{
}
private void ProcessNumbersBackgroundWorker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
}

VB.NET

Private Sub ProcessNumbersBackgroundWorker_DoWork(ByVal sender As Object, ByVal


e As DoWorkEventArgs)
End Sub
Private Sub ProcessNumbersBackgroundWorker_RunWorkerCompleted(ByVal sender As
Object, ByVal e As RunWorkerCompletedEventArgs)
End Sub

C#
ProcessNumbersBackgroundWorker.RunWorkerAsync(args);

VB.NET
ProcessNumbersBackgroundWorker.RunWorkerAsync(args)

. DoWork

290

291

13

System.IO

.net

292

293

.net

.1 System.IO

BinaryReader
BinaryWriter

BinaryFiles

BufferedStream Buffer

Directory

DirectoryInfo
DriveInfo
Driver
File

FileInfo
FileStream
Stream
FileSystemWatcher
Path

StreamReader

StreamWriter
StringReader Reader Writer
StringWriter String
.1 .13 System.IO
.

294

.2

Directory

.net

DirectoryInfo

structure Directory
Object DirectoryInfo FileStreamInfo
Object Directory
static DirectoryInfo
.
FileFileInfo ...
DirectoryInfo FileInfo
FileStreamInfo :

Attributes
enumeration FileAttributes
CreationTime
Exists
Extension

FullName
LastAccessTime
LastWriteTime
Name
.2 .13 .

295

.3

.net

DirectoryInfo

FileStreamInfo
:

)( Create
)(CreateSubdirectory
)( Delete
)( GetDirectories
)( GetFiles Array FileInfo
)( MoveTo
Parent
Root Driver
.3 .13 .

) ( :
Constructor

C#
;)"DirectoryInfo dir1 = new DirectoryInfo(".

VB.NET
)"Dim dir1 As New DirectoryInfo(".

C#
;)"DirectoryInfo dir1 = new DirectoryInfo("C:\Ahmed

VB.NET
)"Dim dir1 As New DirectoryInfo("C:\Ahmed

296

.net

*** \
\n \r
:
@

C#
;)"DirectoryInfo dir1 = new DirectoryInfo(@"C:\Ahmed

C#
;)"DirectoryInfo dir1 = new DirectoryInfo(@"C:\Ahmed\Test
;)(dir1.Create

VB.NET
)"Dim dir1 As New DirectoryInfo("C:\Ahmed\Test
)(dir1.Create

C#

;)(FileInfo[] imageFiles = dir.GetFiles

VB.NET
)(Dim imageFiles As FileInfo() = dir.GetFiles

FileSystemInfo
:

C#
;)Console.WriteLine(dir1.CreationTime

VB.NET
)Console.WriteLine(dir1.CreationTime

GIF

FileInfo FileSystemInfo
.

297

.net

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo dir1 = new
DirectoryInfo(@"C:\Users\Ahmed\Documents\Visual Studio
2008\WebSites\WebSite4");
FileInfo[] imageFiles = dir1.GetFiles("*.gif");
foreach (FileInfo f in imageFiles)
{
Console.WriteLine("Name: {0} - Creation Date: {1} . \n\n",
f.Name, f.CreationTime);
}
Console.ReadKey();
}
}
}

VB.NET
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.IO
Namespace ConsoleApplication7
Class Program
Private Shared Sub Main(ByVal args As String())
Dim dir1 As New DirectoryInfo("C:\Users\Ahmed\Documents\Visual
Studio 2008\WebSites\WebSite4")
Dim imageFiles As FileInfo() = dir1.GetFiles("*.gif")

For Each f As FileInfo In imageFiles


Console.WriteLine("Name: {0} - Creation Date: {1} . " & Chr(10)
& "" & Chr(10) & "", f.Name, f.CreationTime)
Next
Console.ReadKey()
End Sub
End Class
End Namespace

298

.net

.1 .13

.4

Directory

FileSystemInfo

C#
;)"System.IO.Directory.Delete(@"C:\ahmed

VB.NET
)"System.IO.Directory.Delete("C:\ahmed

299

.net

DriveInfo

.5

Drivers
:Pro.CSharp2008
C#

Console.WriteLine("***** Fun with DriveInfo *****\n");


// Get info regarding all drives.
DriveInfo[] myDrives = DriveInfo.GetDrives();
// Now print drive stats.
foreach (DriveInfo d in myDrives)
{
Console.WriteLine("Name: {0}", d.Name);
Console.WriteLine("Type: {0}", d.DriveType);
// Check to see whether the drive is mounted.
if (d.IsReady)
{
Console.WriteLine("Free space: {0}", d.TotalFreeSpace);
Console.WriteLine("Format: {0}", d.DriveFormat);
Console.WriteLine("Label: {0}", d.VolumeLabel);
Console.WriteLine();
}
}
Console.ReadLine();

VB.NET
Console.WriteLine("***** Fun with DriveInfo *****" & Chr(10) & "")
' Get info regarding all drives.
Dim myDrives As DriveInfo() = DriveInfo.GetDrives()
' Now print drive stats.
For Each d As DriveInfo In myDrives
Console.WriteLine("Name: {0}", d.Name)
Console.WriteLine("Type: {0}", d.DriveType)
' Check to see whether the drive is mounted.
If d.IsReady Then
Console.WriteLine("Free space: {0}", d.TotalFreeSpace)
Console.WriteLine("Format: {0}", d.DriveFormat)
Console.WriteLine("Label: {0}", d.VolumeLabel)
Console.WriteLine()
End If
Next
Console.ReadLine()

300

.6

.net

FileInfo

- : -

)( AppendText StreamWritter
)( CopyTo
)( Create FileStream
)( CreateText StreamWriter
)( Delete
Directory
DirectoryName
Length
)( MoveTo
Name
)( Open
)( OpenRead
)( OpenText StreamReader
)( OpenWrite
.4 .13 .

StreamReader
. .
)(: Create

301

.net

C#
FileInfo f = new FileInfo(@"C:\Test.txt");
FileStream fs = f.Create();

VB.NET
Dim f As New FileInfo("C:\Test.txt")
Dim fs As FileStream = f.Create()

FileSystemInfo
Attributes
. ...

C#
if ((File.GetAttributes(path) & FileAttributes.Hidden) ==
FileAttributes.Hidden)
{
}

VB.NET

If (File.GetAttributes(Path) And FileAttributes.Hidden) = FileAttributes.Hidden


Then
End If

:
Or
C#

File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);

VB.NET
File.SetAttributes(path, File.GetAttributes(path) Or FileAttributes.Hidden)

302

.net

.1.6 )(Open

)(Open

FileMode.OpenOrCreate
:

C#
;)"FileInfo f2 = new FileInfo(@"C:\Test2.txt
FileStream fs2 = f2.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite,
;)FileShare.None

VB.NET

)"Dim f2 As New FileInfo("C:\Test2.txt


Dim fs2 As FileStream = f2.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite,
)FileShare.None

)( CreateNew IOException
)( Create

)( Open
FileNotFoundException

)( OpenOrCreate
)( Truncate
)( Append

Open
OpenWrite
.5 .13 .FileInfo
FileAccess : enum

303

.net

C#
public enum FileAccess
{
Read,
Write,
ReadWrite
}

VB.NET
Public Enum FileShare
None
Read
Write
ReadWrite
End Enum

OpenRead() .2.6
OpenWrite()
.

OpenText() .3.6
FileStream StreamReader
:

C#

FileInfo f5 = new FileInfo(@"C:\boot.ini");


StreamReader sreader = f5.OpenText();

VB.NET

Dim f5 As New FileInfo("C:\boot.ini")


Dim sreader As StreamReader = f5.OpenText()

304

.net

.4.6 )( CreateText
)(AppendText
.StreamWriter

.7

File

static .
:

)( ReadAllBytes arrayofbytes
)( ReadAllLines
)( ReadAllText
)( WriteAllBytes bytebybyte
)( WriteAllLines
)( WriteAllText
.6 .13 .File
- : ProCSharp2008

305

.net

C#
InitializeComponent();
string[] myTasks = {
"Fix bathroom sink", "Call Dave",
"Call Mom and Dad", "Play Xbox 360"
};
// Write out all data to file on C drive.
File.WriteAllLines(@"C:\tasks.txt", myTasks);
// Read it all back and print out.
foreach (string task in File.ReadAllLines(@"C:\tasks.txt"))
{
Console.WriteLine("TODO: {0}", task);
}

VB.NET
Dim myTasks As String() = {"Fix bathroom sink", "Call Dave", "Call Mom and
Dad", "Play Xbox 360"}
' Write out all data to file on C drive.
File.WriteAllLines("C:\tasks.txt", myTasks)
' Read it all back and print out.
For Each task As String In File.ReadAllLines("C:\tasks.txt")
Console.WriteLine("TODO: {0}", task)
Next


IDisposable .net
:

C#
using (CarClass newCare)
{
// do operations
}

VB.NET

Using newCare As CarClass


' do operations
End Using

C#
FileInfo f = new FileInfo(@"C:\test.txt");
using (StreamReader reader = f.OpenText())
{
// code here
}

306

.net

VB.NET
)"Dim f As New FileInfo("C:\test.txt
)(Using reader As StreamReader = f.OpenText
' code here
End Using

Stream .8
Stream

sequanceofbytes .
.net System.IO.Stream
:


CanRead, Stream
CanWrite
)( Close
)( Flush Buffer
Buffer

Length stream
Position stream
Read(), bytes
)(ReadByte
)( Seek stream
)( SetLength stram
Write(), bytes
)(WriteByte
.7 .13 .Stream

307

.net

FileStream .1.8
abstractclass
. streaming
-
. bytes

C#
private void filestreamexample(string msg, string beforeendmsg)
{
using (FileStream f1 = File.Open(@"C:\test.txt",
FileMode.Create))
{
byte[] msgArray = Encoding.Default.GetBytes(msg);
byte[] beforeendmsgArray = Encoding.Default.GetBytes(beforeendmsg);
f1.Write(msgArray, 0, msgArray.Length);
f1.Position = fStream.Lenght - 10;
f1.Write(beforeendmsgArray, 0, msgAsByteArray.Length);
// view total message.
long totalLenght = msgArray.Length + msgAsByteArray.Length;
byte[] filemsg = new byte[totalLenght];
for (int i = 0; i < totalLenght; i++)
filemsg[i] = (byte)f1.ReadByte();
Console.WriteLine(Encoding.Default.GetString(filemsg));
}
}

308

.net

VB.NET
Private Sub filestreamexample(ByVal msg As String, ByVal beforeendmsg As
String)
Using f1 As FileStream = File.Open("C:\test.txt", FileMode.Create)
Dim msgArray As Byte() = Encoding.[Default].GetBytes(msg)
Dim beforeendmsgArray As Byte() =
Encoding.[Default].GetBytes(beforeendm
f1.Write(msgArray, 0, msgArray.Length)
f1.Position = fStream.Lenght - 10
f1.Write(beforeendmsgArray, 0, msgAsByteArray.Length)
' view total message.
Dim totalLenght As Long = msgArray.Length + msgAsByteArray.Length
Dim filemsg As Byte() = New Byte(totalLenght - 1) {}
For i As Integer = 0 To totalLenght - 1
filemsg(i) = CByte(f1.ReadByte())
Next
Console.WriteLine(Encoding.[Default].GetString(filemsg))
End Using
End Sub

.2.8

StreamWriter,
StreamReader

stream

BinaryReader, BinaryWriter StringWriter, StringReader


.

StreamWriter, StreamReader .3.8



:

309

.net

StreamWriter

)( Close
)( Flush buffer
NewLine
)( Write
)( WriteLine
.8 .13 .StreamWriter

StreamReader
:

)( Peek
)( Read
)( ReadBlock buffer
)( ReadLine
)( ReadToEnd
.9 .13 .StreamReader

310

.net

C#
private void write(string msg)
{
using (StreamWriter w1 = File.CreateText("test.txt"))
{
w1.Write("Start");
w1.Write(writer.NewLine);
w1.WriteLine(msg);
}
}
private string read()
{
using (StreamReader s1 = File.OpenText("test.txt"))
{
string input = null;
string msg = "";
while ((input = sr.ReadLine()) != null)
{
Console.WriteLine(input);
msg += input;
}
return msg;
}
}

VB.NET
Private Sub write(ByVal msg As String)
Using w1 As StreamWriter = File.CreateText("test.txt")
w1.Write("Start")
w1.Write(writer.NewLine)
w1.WriteLine(msg)
End Using
End Sub
Private Function read() As String
Using s1 As StreamReader = File.OpenText("test.txt")
Dim input As String = Nothing
Dim msg As String = ""
While (input = sr.ReadLine()) IsNot Nothing
Console.WriteLine(input)
msg += input
End While
Return msg
End Using
End Function

311

.net

Console:

StringWriter, StringReader .4.8

string
:

C#
StringBuilder stbuilder = strWriter.GetStringBuilder();
stbuilder.Remove(0, 10);
stbuilder.Insert(0, "Ahmed Gamal");

VB.NET
Dim stbuilder As StringBuilder = strWriter.GetStringBuilder()
stbuilder.Remove(0, 10)
stbuilder.Insert(0, "Ahmed Gamal")

312

.net

BinaryWriter, BinaryReader .5.8


binary
. System.Object
: ReadXXXX()
C#

FileInfo f = new FileInfo("Binary.dat");


using (BinaryWriter bwriter = new BinaryWriter(f.OpenWrite()))
{
double dbl = 1234.67;
long lng = 34567000;
string str = "A, B, C";
// Write different data.
bwriter.Write(dbl);
bwriter.Write(lng);
bwriter.Write(str);
}
// Reading using ReadXXX;
using (BinaryReader breader = new BinaryReader(f.OpenRead()))
{
Console.WriteLine(breader.ReadDouble());
Console.WriteLine(breader.ReadInt64()); // == long as i think , i am not
sure.
Console.WriteLine(breader.ReadString());
}

313

.net

VB.NET
Dim f As New FileInfo("Binary.dat")
Using bwriter As New BinaryWriter(f.OpenWrite())
Dim dbl As Double = 1234.67
Dim lng As Long = 34567000
Dim str As String = "A, B, C"
' Write differnt data.
bwriter.Write(dbl)
bwriter.Write(lng)
bwriter.Write(str)
End Using
' Reading using ReadXXX;
Using breader As New BinaryReader(f.OpenRead())
Console.WriteLine(breader.ReadDouble())
Console.WriteLine(breader.ReadInt64())
' == long as i think , i am not sure.
Console.WriteLine(breader.ReadString())
End Using

FileSystemWatcher .9

System.IO.NotifyFilters enum
:
C#
public enum NotifyFilters
{
Attributes, CreationTime,
DirectoryName, FileName,
LastAccess, LastWrite,
Security, Size,
}

314

.net

VB.NET
Public Enum NotifyFilters
Attributes
CreationTime
DirectoryName
FileName
LastAccess
LastWrite
Security
Size
End Enum

events

: delegate

C#
void MyNotificationHandler(object source, FileSystemEventArgs e)
{
}

VB.NET
Private Sub MyNotificationHandler(ByVal source As Object, ByVal e As
FileSystemEventArgs)
End Sub

:
C#

void MyNotificationHandler(object source, RenamedEventArgs e)


{
}

VB.NET
Private Sub MyNotificationHandler(ByVal source As Object, ByVal e As
RenamedEventArgs)
End Sub

315

.net



q
WindowsForms
: c:\
C#

FileSystemWatcher watcher = new FileSystemWatcher();


// monitor files at:
watcher.Path = @"c:\";
// monitor files when
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite |
NotifyFilters.FileName | NotifyFilters.DirectoryName;
// watch files of type
watcher.Filter = "*.txt";
// watch events:
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);

watcher.EnableRaisingEvents = true;
Console.WriteLine("Press 'q' to quit app.");
while (Console.Read() != 'q') ;

VB.NET

Dim watcher As New FileSystemWatcher()


' monitor files at:
watcher.Path = "c:\"
' monitor files when
watcher.NotifyFilter = NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or
NotifyFilters.FileName Or NotifyFilters.DirectoryName
' watch files of type
watcher.Filter = "*.txt"
' watch events:
AddHandler watcher.Created, AddressOf OnChanged
AddHandler watcher.Deleted, AddressOf OnChanged

watcher.EnableRaisingEvents = True
Console.WriteLine("Press 'q' to quit app.")
While Console.Read() <> "q"c
End While

316

.net

OnChanged
OnChanged
: -

C#

static void OnChanged(object source, FileSystemEventArgs e)


{
Console.WriteLine("File Changed, File Path: {0} , Change: {1}, DateTime:
{2}", e.FullPath, e.ChangeType, DateTime.Now.ToString());
}

VB.NET

Private Shared Sub OnChanged(ByVal source As Object, ByVal e As


FileSystemEventArgs)
Console.WriteLine("File Changed, File Path: {0} , Change: {1}, DateTime:
{2}", e.FullPath, e.ChangeType, DateTime.Now.ToString())
End Sub

...
)
: (

. .2 .13

ObjectSerialization .10
.ObjectSerialization

317

.net

Serialization .1.10
:Serializable

C#

:
[ Serializable]
:

[Serializable]
public class serial
{
}

VB.NET
<Serializable()> _
Public Class serial
End Class

Serializable
Serializable
:
C#

serial sample = new serial();


using (Stream fs1 = new FileStream("data.txt",
FileMode.Create, FileAccess.Write, FileShare.None))
{
binFormat.Serialize(fw1, sample);
}

VB.NET
Dim sample As New serial()
Using fs1 As Stream = New FileStream("data.txt", FileMode.Create,
FileAccess.Write, FileShare.None)
binFormat.Serialize(fw1, sample)
End Using

318

.net



.ASP.net ViewState Serializable
: Serialization

BinaryFormatter
C#


System.Runtime.Serialization.Formatters.Binary

BinaryFormatter binFormatter = new BinaryFormatter();


using (Stream fs1 = new FileStream("data.txt",FileMode.Create,FileAccess.Write,
FileShare.None))
{
binFormat.Serialize(fs1, myobject);
}

VB.NET
Dim binFormatter As New BinaryFormatter()
Using fs1 As Stream = New FileStream("data.txt", FileMode.Create,
FileAccess.Write, FileShare.None)
binFormat.Serialize(fs1, myobject)
End Using

:Deserializing
C#

BinaryFormatter binFormatter = new BinaryFormatter();


using (Stream fs1 = File.OpenRead("data.txt"))
{
newobject car =
(objectclass)binFormatter.Deserialize(fs1);
}

VB.NET
Dim binFormatter As New BinaryFormatter()
Using fs1 As Stream = File.OpenRead("data.txt")
Dim car As newobject = DirectCast(binFormatter.Deserialize(fs1),
objectclass)
End Using

319

.net

XmlSerializer .2.10
XML

XML :

XML
><root
><Member
><Name>AHmed</Name
><Age>22</Age
></Member
></root

22 Element Name Age . Attribute


XML :

http://www.w3schools.com/xml/xml_whatis.asp

System.Xml.Serialization

XmlAttributeAttribute Attribute
XmlElementAttribute Element
XmlRootAttribute Root
XmlTextAttribute XMLText
.10 .13 .System.Xml.Serialization
XML :Serialization

C#
class Members
{
][XmlAttribute
;string Name
][XmlAttribute
;int Age
}

320

.net

VB.NET

Class Members
<XmlAttribute()> _
Private Name As String
<XmlAttribute()> _
Private Age As Integer
End Class

Serialization
. XML

321

322

14

2008

.net

WindowsForms

323

324

2008 .net

.1

Viusal
Visual

.
.net System.Windows.Forms
API GDI+
2D .net
3.0 WindowsPresentationFoundation
WPF .

.2 WindowsForms
Visual
Studio Windows
.Forms
WindowsForms.cs
Notepad
.
:
Forms

C#
class SimpleWindow : Form
{
}

325

2008 .net

VB.NET
Class SimpleWindow
Inherits Form
End Class

Main

: System.Windows.Forms

C#
using System;
using System.Windows.Forms;
namespace WindowsForms
{
class Program
{
static void Main()
{
Application.Run(new SimpleWindow());
}
}
}
class SimpleWindow : Form
{
}

VB.NET
Imports System
Imports System.Windows.Forms
Namespace WindowsForms
Class Program
Private Shared Sub Main()
Application.Run(New SimpleWindow())
End Sub
End Class
End Namespace
Class SimpleWindow
Inherits Form
End Class

: Cmd
Shell
csc /target:winexe *.cs

326

2
2008
.net

csc



:

.
.1 .14

. .....

ObjectB
Browser

.Objec
.1 .14 ct Explorrer

327

2008 .net

C#
class SimpleForm : Form
{
public SimpleForm(int height, int width, bool center)
{
Width = width;
Height = height;
if (center) CenterToScreen();
}
}

VB.NET
Class SimpleForm
Inherits Form
Public Sub New(ByVal height As Integer, ByVal width As Integer, ByVal
center As Boolean)
Width = width
Height = height
If center = True Then
CenterToScreen()
End If
End Sub
End Class

:
Run

C#
static void Main()
{
Application.Run(new MainWindow(200, 300, True));
}

VB.NET
Private Shared Sub Main()
Application.Run(New MainWindow(200, 300, [True]))
End Sub

... Args

.1.2

328

2008 .net

)( Add
)(AddRange
Remove
)(RemoveAt
)( Clear
Count

System.Windows.Forms
...

.2.2
Exit :

.2 .14 Menu .
MenuStrip ToolStripMenuItem
:

C#
;private System.Windows.Forms.MenuStrip menuStrip1
;private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem
;private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem

329

2008 .net

VB.NET
Private menuStrip1 As System.Windows.Forms.MenuStrip
Private fileToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Private exitToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem


BuildForm Constructor
.Constructor

C#
public SimpleForm()
{
Text="Example. Simple Form";
BuildForm();
}

VB.NET
Public Sub New()
Text = "Example. Simple Form"
BuildForm()
End Sub

Add
:

C#
fileToolStripMenuItem.Text = "&File";
menuStrip1.Items.Add(mnuFile);
exitToolStripMenuItem.Text = "E&xit";
menuStrip1.DropDownItems.Add(mnuFileExit);

VB.NET
fileToolStripMenuItem.Text = "File"
menuStrip1.Items.Add(mnuFile)
exitToolStripMenuItem.Text = "Exit"
menuStrip1.DropDownItems.Add(mnuFileExit)

: Exit Handler
C#
exitToolStripMenuItem.Click += new
System.EventHandler(this.exitToolStripMenuItem_Click);

330

2008 .net

VB.NET

AddHandler exitToolStripMenuItem.Click, AddressOf exitToolStripMenuItem_Click

Form
:

C#
Controls.Add(this.mnuMainMenu);
MainMenuStrip = this.menuStrip1;

VB.NET
Controls.Add(Me.mnuMainMenu)
MainMenuStrip = Me.menuStrip1

:Exit

C#
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}

VB.NET
Private Sub exitToolStripMenuItem_Click(ByVal sender As Object, ByVal e As
EventArgs)
Application.[Exit]()
End Sub

331

2008 .net

C#

class SimpleForm : Form


{
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
public SimpleForm()
{
Text = "Example. Simple Form";
BuildForm();
}
private void BuildForm(){
fileToolStripMenuItem.Text = "File";
menuStrip1.Items.Add(mnuFile);
exitToolStripMenuItem.Text = "Exit";
menuStrip1.DropDownItems.Add(mnuFileExit);
exitToolStripMenuItem.Click += new
System.EventHandler(this.exitToolStripMenuItem_Click);
Controls.Add(this.mnuMainMenu);
MainMenuStrip = this.menuStrip1;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e){
Application.Exit();
}
}

VB.NET

Class SimpleForm
Inherits Form
Private menuStrip1 As System.Windows.Forms.MenuStrip
Private fileToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Private exitToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Public Sub New()
Text = "Example. Simple Form"
BuildForm()
End Sub
Private Sub BuildForm()
fileToolStripMenuItem.Text = "&File"
menuStrip1.Items.Add(mnuFile)
exitToolStripMenuItem.Text = "E&xit"
menuStrip1.DropDownItems.Add(mnuFileExit)
AddHandler exitToolStripMenuItem.Click, AddressOf
exitToolStripMenuItem_Click
Controls.Add(Me.mnuMainMenu)
MainMenuStrip = Me.menuStrip1
End Sub
Private Sub exitToolStripMenuItem_Click(ByVal sender As Object, ByVal e As
EventArgs)
Application.[Exit]()
End Sub
End Class

332

2008 .net

.3 VisualStudio.net
Visual Studio 2008 FileNew Windows Forms
: Application

.3 .14 .Visual Studio 2008


ToolBox MenuStrip :

333

2008 .net

.4 .14 .Visual Studio 2008


Exit
:

334

2008 .net

.5 .14 .
F5.
....
.
VisualStudio
.

ToolBox
View
.ToolBox

335

2008 .net

All Windows Forms


AddTab ChooseItem
:

.6 .14 .ToolBox

TabsGroup

.7 .14 .
.
:
Ctrl+Tab

336

2008 .net

.8 .14 .

PropertiesWindows

.9 .14 .

337

2008 .net

SolutionExplorer

.10 .14 .
Forms Classes
. Resources

ClassView

338

2008 .net

.11 .14 .
.

VisualStudio.net
SolutionExplorer :
Form1.cs -1
][Design

.
DesignCode Class
.Diagram

339

2008 .net

Form1.Designer.cs -2

.12 .14 .
Form1.rex -3
.

340

.4

2008 .net

System.Windows.Forms

.1.4

System.Windows.Forms

System.Object
.net

System.MarshalByRefObject
byref

System.ComponentModel.Component
Interface IComponent

System.Windows.Forms.Control
.

System.Windows.Forms.ScrollableControl
Scrolls .

System.Windows.Forms.ContainerControl
Controls
.

System.Windows.Forms.Form
.
Form System.Windows.Forms.Form
...

341

.2.4

2008 .net

Form

AcceptButton
Enter
ActiveMDIChild

IsMDIChildIsMDIContainer

CancelButton
Esc
ControlBox ControlBox
FormBorderStyle
Menu
MaximizeBox
Minimize

ShowInTaskbar
StartPosition
ti
WindowState
enumeration FormWindowState
.1 .14 .Form
enumeration FormStartPosition :

342

2008 .net

FormWindowState :

.3.4

Form

)( Activate
)( Close
)( CenterToScreen
)( LayoutMDI
)( ShowDialog Dialog

.2 .14 .Form

.4.4

Form

Activated Activate
Closing
Closed
Deactivate
Load
- -

MDIChildActive
.3 .14 .Form

343

2008 .net

Controls
.

.5 Controls
.1.5 Controls

BackColor
ForeColor
BackgroundImage
Font
Cursor
Anchor Dock

AutoSize
Top
Left
Bottom
Right
Bounds
ClientRectangle
Height
Width
Enabled

344

2008 .net

Visible
ModifierKeys ModifierKeys Alt CtrlShift
MouseButtons ) - (
TabIndex Tab
TabStop Tab
Opacity 0 1
Text
Controls

.4 .14 .Control

.2.5

Controls

Click
DoubleClick
MouseEnter
MouseLeave
MouseDown
MouseUp
MouseMove, .
MouseHover
MouseWheel Wheel
KeyPress

345

2008 .net

KeyUp
KeyDown
DragDrop
DragEnter
DragLeave
DragOver
Paint
.5 .14 .Control

.6

System.Windows.Forms.Control


Controls
.
.

.1.6

Button

:
:FlatStyle .
:TextAlign .

346

.2.6

2008 .net

CheckBox

:
:CheckState .
:ThreState ) - - ( .

.3.6

RadioButton


panel.

347

.4.6

2008 .net

ComboBox ListBox

.
Collection.List Items.Add
.... Items.Remove

.5.6

TextBox

:
: ReadOnly .
: PasswordChar .
: MultiLine .
: MaxLength .
: ScrollsBar .
.
: WordWrap

348

2008 .net

System.Windows.Forms.ScrollableControl
.ScrollBars enumeration

C#
private void TextBox1_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
if ((e.KeyChar < '0' | e.KeyChar > '9'))
{
e.Handled = true;
}
}

VB.NET
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If (e.KeyChar < "0"c Or e.KeyChar > "9"c) Then
e.Handled = True
End If
End Sub

C#
private void Button1_Click(object sender, System.EventArgs e)
{
//
int index;
//
string SearchWord = "Ahmed";
//
TextBox1.Focus();
//
index = TextBox1.Text.IndexOf(SearchWord);
//
TextBox1.SelectionStart = index;
TextBox1.SelectionLength = SearchWord.Length;
}

349

2008 .net

VB.NET
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
'
Dim index As Integer
'
Dim SearchWord As String = "Ahmed"
'
TextBox1.Focus()
'
index = TextBox1.Text.IndexOf(SearchWord)
'
TextBox1.SelectionStart = index
TextBox1.SelectionLength = SearchWord.Length
End Sub

Label

.6.6

Panel GroupoBox

.7.6

350

.8.6

2008 .net

RichTextBox

TextBox
Notepad Wordpad
:
:Wordwrap .
:Lines .
:Select .
:SelectionXXX .SelectionColor
: DetectUrls .
:
)( :LoadFile .
)( :SaveFile .


- :

351

2008 .net

C#
RichTextBox1.LoadFile(@"C:\Ahmed.txt", RichTextBoxStreamType.PlainText);
RichTextBox1.SaveFile(@"C:\Ahmed2.txt", RichTextBoxStreamType.PlainText);

VB.NET
RichTextBox1.LoadFile("C:\Ahmed.txt", RichTextBoxStreamType.PlainText)
RichTextBox1.SaveFile("C:\Ahmed2.txt", RichTextBoxStreamType.PlainText)

rtf
:
RichTextBoxStreamType.RichText

C#
RichTextBox1.LoadFile(@"C:\Ahmed.rtf ", RichTextBoxStreamType.RichText);
RichTextBox1.SaveFile(@"C:\Ahmed2.rtf ", RichTextBoxStreamType.RichText);

VB.NET
RichTextBox1.LoadFile("C:\Ahmed.rtf ", RichTextBoxStreamType.RichText)
RichTextBox1.SaveFile("C:\Ahmed2.rtf", RichTextBoxStreamType.RichText)

C#
int index = 0;
while ((index = richTextBox1.Text.IndexOf(textBox1.Text, index)) != -1)
{
richTextBox1.Select(index, textBox1.Text.Length);
richTextBox1.SelectionColor = System.Drawing.Color.Red;
index += textBox1.Text.Length;
}
MessageBox.Show(";)"

VB.NET
Dim index As Integer = 0
While (index = richTextBox1.Text.IndexOf(textBox1.Text, index)) <> -1
richTextBox1.[Select](index, textBox1.Text.Length)
richTextBox1.SelectionColor = System.Drawing.Color.Red
index += textBox1.Text.Length
End While

352

2008 .net

.13 .14 .

.9.6

Timer

Ticker Interval
.
Interval 1000
Enabled True :Tick

C#
label1.Text = DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" +
;DateTime.Now.Second

353

2008 .net
VB.NET

label1.Text = DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" +


DateTime.Now.Second

.14 .14 .

.10.6

TreeView

.15 .14 .TreeView


Nodes
.
:

354

2008 .net

http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.aspx

.11.6

ProgressBar

Minimum - Maximum
Step Style
Style enumeration
.ProgressBarStyle
.Value

.12.6

TrackBar

Progressbar Trackbar
.

355

.13.5

2008 .net

DateTimePicker

.16 .14 .DateTimePicker


Format
. Value
. MinDate - MaxDate
...
:

http://msdn.microsoft.com/en-us/library/aa984065(VS.71).aspx

Dialogs .7


.
Resizeable
FormBorderStyle FixedDialog MinimizeBox
... MaximizeBox .

356

2008 .net

Dialog
enumeration DialogResult
:
Abort, Cancel, Ignore, No, None, OK, Retry, Yes
OK AcceptButton
.
Cancel CancelButton
:
Dialog ShowDialog

C#
;)(newDialog.ShowDialog

VB.NET
)(newDialog.ShowDialog

C#
)if (newDialog.ShowDialog() == DialogResult.Cancel
{
// do something
}
)else if (newDialog.ShowDialog() == DialogResult.Ok
{
// do something else
}

VB.NET
If newDialog.ShowDialog() = DialogResult.Cancel Then
' do something
ElseIf newDialog.ShowDialog() = DialogResult.OK Then
' do something else
End If

357

2008 .net

public Dialog
:

C#
public System.Windows.Forms.TextBox TextBox1;

VB.NET
Public TextBox1 As System.Windows.Forms.TextBox

MessageBox

.1.7

MessageBox Dialogs
:

C#
MessageBox.Show("Welcome ...");

VB.NET
Public TextBox1 As System.Windows.Forms.TextBox

overloads 20 Show
:


C#

MessageBox.Show("Welcome ...", "Title", MessageBoxButtons.OK,


MessageBoxIcon.Exclamation);

VB.NET

MessageBox.Show("Welcome ...", "Title", MessageBoxButtons.OK,


MessageBoxIcon.Exclamation)

358

2008 .net

C#
DialogResult reslt = MessageBox.Show("Do you want to save", "Title",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
if (reslt = DialogResult.Yes)
MessageBox.Show("you want to save.");
else if (reslt = DialogResult.No)
MessageBox.Show("you don't want to save.");
else if (reslt = DialogResult.Cancel)
MessageBox.Show("you cancel this operation.");

VB.NET
Dim reslt As DialogResult = MessageBox.Show("Do you want to save", "Title",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1)
If reslt = DialogResult.Yes Then
MessageBox.Show("you want to save.")
ElseIf reslt = DialogResult.No Then
MessageBox.Show("you don't want to save.")
ElseIf reslt = DialogResult.Cancel Then
MessageBox.Show("you cancel this operation.")
End If

...
:

http://msdn.microsoft.com/en-us/library/system.windows.messagebox.show.aspx

359

2008 .net

DialogControls .2.7

...

ColorDialog .3.7

ToolBox
:

.17 .14 .ColorDialog


PictureBox :

C#
)if (colorDialog1.ShowDialog() == DialogResult.OK
;pictureBox1.BackColor = colorDialog1.Color
else
;)"MessageBox.Show("cancel operation

360

2008 .net

VB.NET
If colorDialog1.ShowDialog() = DialogResult.OK Then
pictureBox1.BackColor = colorDialog1.Color
Else
)"MessageBox.Show("cancel operation
End If


AllowFullOpen
:

.18 .14 ColorDialog .


:
FullOpen

361

2008 .net

.19 .14 ColorDialog .


:

http://msdn.microsoft.com/en-us/library/ms646375.aspx

FontDialog .4.7

362

2008 .net

. FontDialog .20 .14

C#
fontDialog1.ShowColor = true;
fontDialog1.Font = textBox1.Font;
fontDialog1.Color = textBox1.ForeColor;
if (fontDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Font = fontDialog1.Font;
textBox1.ForeColor = fontDialog1.Color;
}

VB.NET
fontDialog1.ShowColor = True
fontDialog1.Font = textBox1.Font
fontDialog1.Color = textBox1.ForeColor
If fontDialog1.ShowDialog() = DialogResult.OK Then
textBox1.Font = fontDialog1.Font
textBox1.ForeColor = fontDialog1.Color
End If

http://msdn.microsoft.com/en-us/library/system.windows.forms.fontdialog(VS.80).aspx

363

2008 .net

OpenAndSaveDialogs .5.7



:
Multiline=True
SaveFileDialog OpenFileDialog
.
:

C#
string fileToOpen = "";
OpenFileDialog openFile = new OpenFileDialog();
openFile.DefaultExt = "txt";
openFile.Filter = "Word documents (*.txt)|*.txt";

VB.NET

Dim fileToOpen As String = ""


Dim openFile As New OpenFileDialog()
openFile.DefaultExt = "txt"
openFile.Filter = "Word documents (*.txt)|*.txt"
If openFile.ShowDialog() = DialogResult.OK Then
fileToOpen = openFile.FileName
End If

C#
if (fileToOpen != "")
{
using (System.IO.StreamReader s1 = System.IO.File.OpenText(fileToOpen))
{
string input = null;
textBox1.Text = "";
while ((input = s1.ReadLine()) != null)
{
textBox1.Text += input;
}
}
}

364

2008 .net

VB.NET

If fileToOpen <> "" Then


Using s1 As System.IO.StreamReader = System.IO.File.OpenText(fileToOpen)
Dim input As String = Nothing
textBox1.Text = ""
While (input = s1.ReadLine()) IsNot Nothing
textBox1.Text += input

End While
End Using
End If

C#
string fileToSave = "";
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
fileToSave = saveFileDialog1.FileName;

VB.NET
Dim fileToSave As String = ""
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
fileToSave = saveFileDialog1.FileName
End If

:
C#

if (fileToSave != "")
{
using (System.IO.StreamWriter w1 = System.IO.File.CreateText(fileToSave))
{
w1.WriteLine(textBox1.Text);
}
}

365

2008 .net

VB.NET

If fileToSave <> "" Then


Using w1 As System.IO.StreamWriter = System.IO.File.CreateText(fileToSave)
w1.WriteLine(textBox1.Text)
End Using
End If

.OpenFileDialog .21 .14


:

http://msdn.microsoft.com/enus/library/aa287592(VS.71).aspx
http://msdn.microsoft.com/en
us/library/system.windows.forms.savefiledialog.aspx

. ...

366

2008 .net

PrintDialog .6.6

.22 .14 .PrintDialog


:

http://msdn.microsoft.com/en-us/library/system.windows.forms.printdialog.aspx

.8
MouseDown

Properties

367

2008 .net

MouseDown .23 .14

C#
if (e.Button == MouseButtons.Left)
MessageBox.Show("Left click");
if (e.Button == MouseButtons.Right)
MessageBox.Show("Right click");
if (e.Button == MouseButtons.Middle)
MessageBox.Show("Middle click");

VB.NET
If e.Button = MouseButtons.Left Then
MessageBox.Show("Left click")
End If
If e.Button = MouseButtons.Right Then
MessageBox.Show("Right click")
End If
If e.Button = MouseButtons.Middle Then
MessageBox.Show("Middle click")
End If

: MouseMove

368

2008 .net

C#
;this.Text = "X: " + e.X + ", Y:" + e.Y

VB.NET
Me.Text = "X: " + e.X + ", Y:" + e.Y

.9

KeyUp :

C#
;)(this.Text = "key: " + e.KeyCode.ToString

VB.NET
)(Me.Text = "key: " + e.KeyCode.ToString

key

Modifier :

C#
this.Text = string.Format("Key: {0} Modifier: {1}", e.KeyCode.ToString(),
;))(e.Modifiers.ToString

369

2008 .net
VB.NET

Me.Text = String.Format("Key: {0} Modifier: {1}", e.KeyCode.ToString(),


))(e.Modifiers.ToString

If

370

371

15
GDI+

372

373

GDI+

.1 GDI+

System.Drawing
D2 :
.1
.2
.3
.4
.5

:System.Drawing
.
: System.Drawing.Drawing2D
gradientbrushes geometrictransforms
: System.Drawing.Imaging
.
: System.Drawing.Printing
.
:System.Drawing.Text .

.2

System.Drawing

Bitmap
Brush
BufferedGraphics Buffer double
buffering
SystemColors Color

FontFamily Font
.
Graphics

374

Icon

GDI+

SystemIcons

Image abstractclass
ImageAnimator
Pen
Point
Rectangle
Size
StringFormat
Region
.1 .15 .System.Drawing

DoubleBuffering
buffer
flicker :

http://msdn.microsoft.com/en-us/library/b367a457.aspx

http://msdn.microsoft.com/en-us/library/system.drawing.aspx

.3 Graphics
Graphics :
- PictureBox:

375

GDI+

C#
Graphics
s myGraphic = Form1.
.CreateGrap
phics();

VB.NET
Dim myGr
raphic As Graphics = Form1.Cre
eateGraphi
ics()

C#

Pa
aintEven
ntArgs

private void Form1_Paint(ob


bject sende
er, PaintE
EventArgs e)
e
{
phics myGraphic = e.
.Graphics();
Grap
}

VB.NET
Private Sub Form1_
_Paint(ByV
Val sender As Object
t, ByVal e As PaintE
EventArgs)
ics = e.Gra
aphics()
Dim myGraphic As Graphi
End Sub

dc()


FromHd
FromHw
wnd()
FromIm
mage()
Clear()
rc()
DrawAr
eziers()
- .

Bezziers - DrawBe
urve()
DrawCu
llipse()
DrawEl
con()
DrawIc

376

GDI+

)( DrawLine
)( DrawLines
)( DrawPie
)( DrawPath
)( DrawRectangle
)( DrawRectangles
)( DrawString
)( FillEllipse
)( FillPie
)( FillPolygon
)( FillRectangle
)( FillPath
.2 .15 Graphics
:

http://msdn.microsoft.com/en-us/library/system.drawing.graphics_members.aspx

DrawXXX Pen
.
FillXXX Brush

377

GDI+

.4 Pen

Pen Pens.Blue

:

C#
;)Pen myPen = new Pen(Color.Black, 3

VB.NET
)Dim myPen As New Pen(Color.Black, 3

. 3
:

C#
;myPen.StartCap = LineCap.ArrowAnchor

VB.NET
myPen.StartCap = LineCap.ArrowAnchor

http://msdn.microsoft.com/en-us/library/system.drawing.pen.aspx

.5 Brush

C#
;)SolidBrush myBrush = new SolidBrush(Color.Yellow

VB.NET
)Dim myBrush As New SolidBrush(Color.Yellow

378

GDI+

C#

HatchBrush myBrush = new HatchBrush(HatchStyle.BackwardDiagonal, Color.Green,


Color.White);

VB.NET
Dim myBrush As New HatchBrush(HatchStyle.BackwardDiagonal, Color.Green,
Color.White)

http://msdn.microsoft.com/en-us/library/system.drawing.brush.aspx

.6

C#
myGraphic.DrawLine(Pens.Blue, 20, 20, 100, 100);

VB.NET
myGraphic.DrawLine(Pens.Blue, 20, 20, 100, 100)

C#
myGraphic.DrawRectangle(Pens.Blue, New Rectangle(20, 20, 100, 100));

VB.NET

myGraphic.DrawRectangle(Pens.Blue, New Rectangle(20, 20, 100, 100))

:
C#

379

GDI+

myGraphic.DrawBezier(Pens.Blue, 10, 20, 50, 80, 10, 80, 100, 50);

VB.NET
myGraphic.DrawBezier(Pens.Blue, 10, 20, 50, 80, 10, 80, 100, 50)

C#
Graphics myGraphic = e.Graphics;
Pen myPen = new Pen(Color.Blue, 3);
myPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
myGraphic.DrawLine(myPen, 20, 20, 100, 100);

VB.NET
Dim myGraphic As Graphics = e.Graphics
Dim myPen As New Pen(Color.Blue, 3)
myPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot
myGraphic.DrawLine(myPen, 20, 20, 100, 100)

C#
GraphicsPath myGraphicPath = new GraphicsPath();
myGraphicPath.StartFigure();
myPath.AddLine(10, 10, 30, 60);
myPath.AddLine(30, 60, 60, 10);
myPath.AddLine(60, 10, 10, 10);
myGraphicPath.CloseFigure();
myGraphic.DrawPath(myPen, myGraphicPath);

VB.NET
Dim myGraphicPath As New GraphicsPath()
myGraphicPath.StartFigure()
myPath.AddLine(10, 10, 30, 60)
myPath.AddLine(30, 60, 60, 10)
myPath.AddLine(60, 10, 10, 10)
myGraphicPath.CloseFigure()
myGraphic.DrawPath(myPen, myGraphicPath)

FillPath

380

GDI+

.7
GDI
.200 200

C#
myGraphic.DrawString("Hello GDI+", new Font("Times New Roman", 30),
Brushes.Red, 200, 200);

VB.NET
myGraphic.DrawString("Hello GDI+", new Font("Times New Roman", 30),
Brushes.Red, 200, 200)

StringFormat
:

C#
Graphics myGraphic = e.Graphics;
StringFormat drawFormat = new StringFormat();
drawFormat.FormatFlags = StringFormatFlags.DirectionVertical;
myGraphic.DrawString("Hello GDI+", new Font("Times New Roman", 30),
Brushes.Red, 100, 20, drawFormat);

VB.NET
Dim myGraphic As Graphics = e.Graphics
Dim drawFormat As New StringFormat()
drawFormat.FormatFlags = StringFormatFlags.DirectionVertical
myGraphic.DrawString("Hello GDI+", New Font("Times New Roman", 30),
Brushes.Red, 100, 20, drawFormat)

. .1 .15

381

GDI+

http://www.java2s.com/Tutorial/CSharp/0480__2D/Clockanimation.htm

GDI
.

http://msdn.microsoft.com/en-us/library/ms533798(VS.85).aspx

382

383

16
Windows
Presentation
Foundation

384

385

WPF

.1
WPF .1.1
WindowsPresentationFoundation WPF
.net framework 3.0 Extensible
Application Markup Language XAML )(
WindowsForms GDI+ DirectX
APIs Windows Media Player API's
.
WPF
.

XAML .2.1
XAML
ASP.net XAML HTML - -
XAML ....

MicrosoftExpression .3.1

photoshop
.. Adobe Flash

Expression
XAML
.

386

WPF


.
WPF XAML .
WPF .

.2 WPF

WPF

TraditionalDesktopApplications -1
exe WPF
.

NavigationBased -2
WPF
Forward Backward pages
.

XBAPApplications -3
WPF
JAVAApplet URL XBAP application
localmachine .

387

WPF

SilverlightApplication -4
WPF
embededflash Silverlight
.

.3 WPF
: System.Windows . WPF
:System.Windows.Controls
Tool Tips.
:System.Windows.Markup .XAML
:System.Windows.Media
.3D
:System.Windows.Navigation

Navigation

Based .
:System.Windows.Shapes .2D

.4 WPF
WPF XAML
WPF .XAML
HTML
:
HTML Tags

388

WPF

HTML
><a href="Ahmed.html">Ahmed</a

Link Ahmed.html
.Ahmed
:
HTML

HTML
><img src="ahmed.jpg" alt="ahmed picture" border="0" /

ToolTip Tag.
HTML :

http://www.html4arab.com/

+ +
+ DreamWaver
- Notepad .
XAML
:

XAML
>"<Button Height="80" Width="100

XAML
><Button Height="80" Width="100" Content="ClickMe"/

XAML
>"<Button Height = "80" Width = "100
><Button.Content
><ScrollBar Width = "75" Height = "40"/
></Button.Content
></Button

Scroll !ContentControl

389

WPF
XAML

>"<ScrollBar Height = "80" Width = "100


><Button Width = "75" Height = "40"/
> </ScrollBar

.5
Visual Studio New Project WPF Application
:

.1 .16 WPF.
XAML
:

390

WPF

.2 .16
.XAML


XAML

Window
Grid



XAML
- . -
Window Title
Title ="WPF
:
" Example

.3 .16 XAML .
XAML :

391

WPF

XAML
<Window x:Class="WpfApplication2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300" Title="WPF Example">
<Grid>
<Button Height="23" Margin="99,0,105,91" Name="button1"
VerticalAlignment="Bottom" Click="button1_Click">Button</Button>
<TextBox Height="23" Margin="77,80,81,0" Name="textBox1"
VerticalAlignment="Top" />
</Grid>
</Window>

.

:

C#
private void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = "Welcome WPF";
}

VB.NET

Private Sub button1_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)


textBox1.Text = "Welcome WPF"
End Sub

. .4 .16

392

WPF

XAML
><x:Code
[<![CDATA
)void CodeExample(object sender, RoutedEventArgs e
{
;)"MessageBox.Show("ahmed
}
>]]
></x:Code

:
Click

XAML
"<Button Height="23" Margin="99,0,105,91" Name="button1
>VerticalAlignment="Bottom" Click="CodeExample">Button</Button

VB.net Click Visual


Studio ...

-
Syntax XAML :
http://msdn.microsoft.com/en-us/library/ms788723.aspx

:
FormLoad Window
XAML
"Loaded = "Window_Loaded" Closed = "Window_Closed

.
WPF MicrosoftExpressionBlend
:
MicrosoftExpression

393

WPF

394

WPF

.5 .16 .Expression Blend


XAML Visual Studio
...

395

WPF

.6 WPF
WPF
.

Lable, Button

: media
:

Groupbox Panel

Canvas. StackPanel
WPF

.6 .16 WPF .
XAML :

396

WPF

XAML
<Window x:Class="WpfApplication3.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="240" Width="343">
<Grid>
<Button Name="btnPurchaseOptions" Margin="10.5,51,10.5,41">
<StackPanel>
<StackPanel Orientation = "Horizontal"></StackPanel>
</StackPanel>
</Button>
<Expander Name="helpExpander" Header="Help" Height="23"
HorizontalAlignment="Left" Margin="70,70,0,0" VerticalAlignment="Top"
Width="51.757"></Expander>
<Expander Name="fileExpander" Header="File" Height="23"
HorizontalAlignment="Left" Margin="22,70,0,0" VerticalAlignment="Top"
Width="44.95"></Expander>
<Slider Height="21" Margin="21.757,0,19,75" Name="slider1"
VerticalAlignment="Bottom">
<Slider.BitmapEffect>
<DropShadowBitmapEffect />
</Slider.BitmapEffect>
</Slider>
<ProgressBar Height="15" Margin="23,0,19,50" Name="progressBar1"
VerticalAlignment="Bottom" Value="50" />
</Grid>
</Window>

WPF
. Ellipse: ComboBox List :

397

WPF

.ComboBox .7 .16
:
SpellCheck

XAML
<TextBox SpellCheck.IsEnabled="True" Height="23" Margin="20,44,16,0"
Name="textBox1" VerticalAlignment="Top" Grid.Row="10" />

C#
string alterWords = "";
SpellingError error = textBox1.GetSpellingError(0);
if (error != null)
{
foreach (string s in error.Suggestions)
{
alterWords += s + "\n";
}
MessageBox.Show("Alternative Words:\n" + alterWords);
}

VB.NET
Dim alterWords As String = ""
Dim [error] As SpellingError = textBox1.GetSpellingError(0)
If [error] IsNot Nothing Then
For Each s As String In [error].Suggestions
alterWords += s + "" & Chr(10) & ""
Next
MessageBox.Show("Alternative Words:" & Chr(10) & "" + alterWords)
End If

398

WPF

.TextBox Spell Cheker .8 .16

DataBinding .7
Slider
WPF
: TextBox

XAML
DataContext = "{Binding ElementName=slider1}" Content = "{Binding Path=Value}"

XAML

: XAML

<Slider Height="27" Margin="20,40,16,0" Name="slider1" VerticalAlignment="Top"


/>
<Label Height="28" DataContext = "{Binding ElementName=slider1}" Content =
"{Binding Path=Value}" Margin="20,72,16,0" Name="label1"
VerticalAlignment="Top" BorderThickness="0">

399

WPF

.9 .16 .

WPF2D .8
WPF
GDI+ .WPF
:
System.Windows.Shapes
System.Windows.Media.Drawing
System.Windows.Media.Visual

.1.8 Shapes

System.Windows.Shapes

XAML
"<Rectangle Height="100" Width="200" Stroke="Red" StrokeThickness="2
>Fill="Aqua" /

400

WPF

.10 .16 .

ObjectBrowser

.11 .16 .Object Browser


:

401

WPF

.12 .16 .Object Browser


:
Shape

.13 .16 .Shape

402

WPF

.2.8 Pen

XAML

"<Pen Thickness="10" LineJoin="Round" EndLineCap="Triangle" StartLineCap="Round


>/

.GDI+

.3.8 Brush

:
:DrawingBrush .
:ImageBrush .
:LinearGradientBrush .
:RadialGradientBrush .
:SolidColorBrush .
Solid :

XAML
>"<Ellipse Height ="50" Width ="50
><Ellipse.Fill
><SolidColorBrush Color ="Aqua"/
></Ellipse.Fill
></Ellipse

RadialGradientBrush :

403

WPF

XAML
<Ellipse Width ="75" HorizontalAlignment="Left" Margin="28,30,0,96">
<Ellipse.Fill>
<RadialGradientBrush GradientOrigin="0.5,0.5" Center="0.5,0.5"
RadiusX="0.5" RadiusY="0.5">
<GradientStop Color="Yellow" Offset="0" />
<GradientStop Color="Red" Offset="0.25" />
<GradientStop Color="Blue" Offset="0.75" />
<GradientStop Color="LimeGreen" Offset="1" />
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>

XAML
<Rectangle Height ="100" Width ="300">
<Rectangle.Fill>
<ImageBrush>
<ImageBrush.ImageSource>
<BitmapImage UriSource ="pic.JPG"/>
</ImageBrush.ImageSource>
</ImageBrush>
</Rectangle.Fill>
</Rectangle>

.Brush .14 .16

404

WPF

http://msdn.microsoft.com/en-us/library/aa970904.aspx

Transformations .4.8


.
:
XAML

<Button Height="23" Margin="72,72,0,0" Name="button1" VerticalAlignment="Top"


HorizontalAlignment="Left" Width="75">Button
<Button.RenderTransform>
<SkewTransform AngleX ="30" AngleY ="20"/>
</Button.RenderTransform>
</Button>
<TextBox Margin="142,11,59,0" Name="textBox1" Height="23"
VerticalAlignment="Top">Ahmed
<TextBox.RenderTransform>
<TransformGroup>
<SkewTransform AngleX ="20" AngleY ="20"/>
<RotateTransform Angle ="45"/>
<SkewTransform AngleX ="5" AngleY ="20"/>
</TransformGroup>
</TextBox.RenderTransform>
</TextBox>

.15 .16
.Transformation
WPF
:

405

WPF

http://www.codeproject.com/KB/WPF/TransformationsIntro.aspx

.16 .16 .MSDN

.9 Animation WPF
Animation
System.Windows.Media.Animation
By To From
...
Timeline :

406

WPF

AccelerationRatio,
DecelerationRatio
AutoReverse
0 BeginTime
This
Duration
FillBehavior,
RepeatBehavior

C#

Timeline .1 .16
: Label

DoubleAnimation dblAnim = new DoubleAnimation();


dblAnim.From = 10;
dblAnim.To = 30;
label1.BeginAnimation(Label.FontSizeProperty, dblAnim);

VB.NET

Dim dblAnim As New DoubleAnimation()


dblAnim.From = 10
dblAnim.[To] = 30
label1.BeginAnimation(Label.FontSizeProperty, dblAnim)

407

WPF

C#
dblAnim.Duration = new Duration(TimeSpan.FromSeconds(4));

VB.NET
dblAnim.Duration = new Duration(TimeSpan.FromSeconds(4))

C#
dblAnim.AutoReverse = true;

VB.NET
dblAnim.AutoReverse = true

C#

dblAnim.RepeatBehavior = RepeatBehavior.Forever;

VB.NET
dblAnim.RepeatBehavior = RepeatBehavior.Forever

C#

dblAnim.RepeatBehavior = new RepeatBehavior(4);

VB.NET
dblAnim.RepeatBehavior = new RepeatBehavior(4)

408

WPF

XAML .10


XAML
Button
: ProCSharp2008 -

XAML
<Button Name="myAnimatedButton" Width="120" Height = "40"
RenderTransformOrigin="0.5,0.5" Content = "OK">
<Button.RenderTransform>
<RotateTransform Angle="0"/>
</Button.RenderTransform>
<!-- The animation is triggered when the button is clicked -->
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<DoubleAnimationUsingKeyFrames
Storyboard.TargetName="myAnimatedButton"
Storyboard.TargetProperty=
"(Button.RenderTransform).(RotateTransform.Angle)"
Duration="0:0:2" FillBehavior="Stop">
<DoubleAnimationUsingKeyFrames.KeyFrames>
<LinearDoubleKeyFrame Value="360" KeyTime="0:0:1"
/>
<DiscreteDoubleKeyFrame Value="180"
KeyTime="0:0:1.5" />
</DoubleAnimationUsingKeyFrames.KeyFrames>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>

Styles .11

styles
. Style DarkStyle

409

WPF

WPF
Style

:
Style

XAML
<Window.Resources>
<Style x:Key ="darkstyle">
<Setter Property ="Button.FontSize" Value ="15"/>
<Setter Property ="Button.Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Color="Black" Offset="0" />
<GradientStop Color="Blue" Offset="0.25" />
<GradientStop Color="Brown" Offset="1" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>

XAML

<Button Name="b1" Width = "100"


Style ="{StaticResource darkstyle}" Content = "Button 1"
HorizontalAlignment="Right" Margin="0,61,30,61" />
<Button Name="b2" Width = "100"
Style ="{StaticResource darkstyle}" Content = "Button 2"
HorizontalAlignment="Left" Margin="25,61,0,61" />

. .17 .16

410

WPF

.1.11 Style


Style
Style :

XAML
"<Button Name="b2" Width = "100
"Style ="{StaticResource darkstyle}" Content = "Button 2
>HorizontalAlignment="Left" Margin="25,61,0,61" FontSize="30" /

.18 .16 .

.2.11 Style

Style Style :

XAML
>"}<Style x:Key ="darkredstyle" BasedOn = "{StaticResource darkstyle

.3.11 Style Triggers

Triggers
Style :

411

WPF

XAML
<Window.Resources>
<Style x:Key ="txtstyle" TargetType = "{x:Type TextBox}">
<Setter Property = "Background" Value = "White"/>
<Style.Triggers>
<Trigger Property = "IsFocused" Value = "True">
<Setter Property = "Background" Value = "Yellow"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>

. .19 .16

ProCSharp2008
Styles
:
Style
C#
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// Add items to our list box.
lstStyles.Items.Add("TiltStyle");
lstStyles.Items.Add("GreenStyle");
lstStyles.Items.Add("MouseOverStyle");
}
protected void comboStyles_Changed(object sender, RoutedEventArgs args)
{
// Get the selected style name from the list box.
System.Windows.Style currStyle = (System.Windows.Style)
FindResource(lstStyles.SelectedValue);
// Set the style of the button type.
this.btnMouseOverStyle.Style = currStyle;
}
}

412

WPF

VB.NET
Partial Public Class MainWindow
Inherits Window
Public Sub New()
InitializeComponent()
' Add items to our list box.
lstStyles.Items.Add("TiltStyle")
lstStyles.Items.Add("GreenStyle")
lstStyles.Items.Add("MouseOverStyle")
End Sub
Protected Sub comboStyles_Changed(ByVal sender As Object, ByVal args As
RoutedEventArgs)
' Get the selected style name from the list box.
Dim currStyle As System.Windows.Style =
DirectCast(FindResource(lstStyles.SelectedValue), System.Windows.Style)
' Set the style of the button type.
Me.btnMouseOverStyle.Style = currStyle
End Sub
End Class

:
C#
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// Add items to our list box.
lstStyles.Items.Add("TiltStyle");
lstStyles.Items.Add("GreenStyle");
lstStyles.Items.Add("MouseOverStyle");
}
protected void comboStyles_Changed(object sender, RoutedEventArgs args)
{
// Get the selected style name from the list box.
System.Windows.Style currStyle = (System.Windows.Style)
FindResource(lstStyles.SelectedValue);
// Set the style of the button type.
this.btnMouseOverStyle.Style = currStyle;
}
}

413

WPF

VB.NET
Partial Public Class MainWindow
Inherits Window
Public Sub New()
InitializeComponent()
' Add items to our list box.
lstStyles.Items.Add("TiltStyle")
lstStyles.Items.Add("GreenStyle")
lstStyles.Items.Add("MouseOverStyle")
End Sub
Protected Sub comboStyles_Changed(ByVal sender As Object, ByVal args As
RoutedEventArgs)
' Get the selected style name from the list box.
Dim currStyle As System.Windows.Style =
DirectCast(FindResource(lstStyles.SelectedValue), System.Windows.Style)
' Set the style of the button type.
Me.btnMouseOverStyle.Style = currStyle
End Sub
End Class

. .20 .16

Templates .12
Styles
:Templates

414

WPF

XAML
<Grid.Resources>
<!-- A simple template for a round button for items in this grid -->
<ControlTemplate x:Key ="roundButtonTemplate" TargetType ="{x:Type
Button}">
<Grid>
<Ellipse Name ="OuterRing" Width ="75" Height ="75" Fill
="DarkGreen"/>
<Ellipse Name ="InnerRing" Width ="60" Height ="60" Fill
="MintCream"/>
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Grid.Resources>

XAML

<Button Name ="myButton" Foreground ="Black" FontSize ="20" FontWeight ="Bold"


Template ="{StaticResource roundButtonTemplate}"
Click ="myButton_Click">Click!
</Button>

. .21 .16

415

WPF

3DWPF .13
WPF
WPF
. Avalon

3D 2D
Projection
Graphics :

http://developer.nvidia.com/docs/IO/11278/Intro-to-Graphics.pdf

... WPF
Graphics -
3D HelloWorld Graphics -
-
3 - Projection
3D .
System.Windows.Media.Media3D
.

C#
;using System.Windows.Media.Media3D

VB.NET
;Imports System.Windows.Media.Media3D

Viewport3D

:

416

WPF

XAML

<Viewport3D Name="mainViewport" ClipToBounds="True">


<Viewport3D.Camera>
<PerspectiveCamera
FarPlaneDistance="100"
LookDirection="-11,-10,-9"
UpDirection="0,1,0"
NearPlaneDistance="1"
Position="11,10,9"
FieldOfView="70" />
</Viewport3D.Camera>
<ModelVisual3D>
<ModelVisual3D.Content>
<DirectionalLight
Color="White"
Direction="-2,-3,-1" />
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D>

:
C#
MeshGeometry3D triangleMesh = new MeshGeometry3D();
Point3D point0 = new Point3D(0, 0, 0);
Point3D point1 = new Point3D(5, 0, 0);
Point3D point2 = new Point3D(0, 0, 5);
triangleMesh.Positions.Add(point0);
triangleMesh.Positions.Add(point1);
triangleMesh.Positions.Add(point2);
triangleMesh.TriangleIndices.Add(0);
triangleMesh.TriangleIndices.Add(2);
triangleMesh.TriangleIndices.Add(1);
Vector3D normal = new Vector3D(0, 1, 0);
triangleMesh.Normals.Add(normal);
triangleMesh.Normals.Add(normal);
triangleMesh.Normals.Add(normal);
Material material = new DiffuseMaterial(
new SolidColorBrush(Colors.DarkKhaki));
GeometryModel3D triangleModel = new GeometryModel3D(
triangleMesh, material);
ModelVisual3D model = new ModelVisual3D();
model.Content = triangleModel;
this.mainViewport.Children.Add(model);

417

WPF

VB.NET
Dim triangleMesh As New MeshGeometry3D()
Dim point0 As New Point3D(0, 0, 0)
Dim point1 As New Point3D(5, 0, 0)
Dim point2 As New Point3D(0, 0, 5)
triangleMesh.Positions.Add(point0)
triangleMesh.Positions.Add(point1)
triangleMesh.Positions.Add(point2)
triangleMesh.TriangleIndices.Add(0)
triangleMesh.TriangleIndices.Add(2)
triangleMesh.TriangleIndices.Add(1)
Dim normal As New Vector3D(0, 1, 0)
triangleMesh.Normals.Add(normal)
triangleMesh.Normals.Add(normal)
triangleMesh.Normals.Add(normal)
Dim material As Material = New DiffuseMaterial(New
SolidColorBrush(Colors.DarkKhaki))
Dim triangleModel As New GeometryModel3D(triangleMesh, material)
Dim model As New ModelVisual3D()
model.Content = triangleModel
Me.mainViewport.Children.Add(model)

. .22 .16
:

418

WPF
C#

private Model3DGroup CreateTriangleModel(Point3D p0, Point3D p1, Point3D p2){


MeshGeometry3D mesh = new MeshGeometry3D();
mesh.Positions.Add(p0);
mesh.Positions.Add(p1); mesh.Positions.Add(p2);
mesh.TriangleIndices.Add(0);
mesh.TriangleIndices.Add(1);
mesh.TriangleIndices.Add(2);
Vector3D normal = CalculateNormal(p0, p1, p2);
mesh.Normals.Add(normal);
mesh.Normals.Add(normal);
mesh.Normals.Add(normal);
Material material = new DiffuseMaterial(new
SolidColorBrush(Colors.DarkKhaki));
GeometryModel3D model = new GeometryModel3D(mesh, material);
Model3DGroup group = new Model3DGroup();
group.Children.Add(model);
return group;
}
private Vector3D CalculateNormal(Point3D p0, Point3D p1, Point3D p2){
Vector3D v0 = new Vector3D(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
Vector3D v1 = new Vector3D(p2.X - p1.X, p2.Y - p1.Y, p2.Z - p1.Z);
return Vector3D.CrossProduct(v0, v1);
}

VB.NET

Private Function CreateTriangleModel(ByVal p0 As Point3D, ByVal p1 As Point3D,


ByVal p2 As Point3D) As Model3DGroup
Dim mesh As New MeshGeometry3D()
mesh.Positions.Add(p0)
mesh.Positions.Add(p1)
mesh.Positions.Add(p2)
mesh.TriangleIndices.Add(0)
mesh.TriangleIndices.Add(1)
mesh.TriangleIndices.Add(2)
Dim normal As Vector3D = CalculateNormal(p0, p1, p2)
mesh.Normals.Add(normal)
mesh.Normals.Add(normal)
mesh.Normals.Add(normal)
Dim material As Material = New DiffuseMaterial(New
SolidColorBrush(Colors.DarkKhaki))
Dim model As New GeometryModel3D(mesh, material)
Dim group As New Model3DGroup()
group.Children.Add(model)
Return group
End Function
Private Function CalculateNormal(ByVal p0 As Point3D, ByVal p1 As Point3D,
ByVal p2 As Point3D) As Vector3D
Dim v0 As New Vector3D(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z)
Dim v1 As New Vector3D(p2.X - p1.X, p2.Y - p1.Y, p2.Z - p1.Z)
Return Vector3D.CrossProduct(v0, v1)
End Function

419

WPF

C#

MeshGeometry3D triangleMesh = new MeshGeometry3D();


Point3D point0 = new Point3D(0, 0, 0);
Point3D point1 = new Point3D(5, 0, 0);
Point3D point2 = new Point3D(0, 0, 5);
triangleMesh.Positions.Add(point0);
triangleMesh.Positions.Add(point1);
triangleMesh.Positions.Add(point2);
triangleMesh.TriangleIndices.Add(0);
triangleMesh.TriangleIndices.Add(2);
triangleMesh.TriangleIndices.Add(1);
Vector3D normal = new Vector3D(0, 1, 0);
triangleMesh.Normals.Add(normal);
triangleMesh.Normals.Add(normal);
triangleMesh.Normals.Add(normal);
Material material = new DiffuseMaterial(
new SolidColorBrush(Colors.DarkKhaki));
GeometryModel3D triangleModel = new GeometryModel3D(
triangleMesh, material);
ModelVisual3D model = new ModelVisual3D();
model.Content = triangleModel;
this.mainViewport.Children.Add(model);

VB.NET

Dim triangleMesh As New MeshGeometry3D()


Dim point0 As New Point3D(0, 0, 0)
Dim point1 As New Point3D(5, 0, 0)
Dim point2 As New Point3D(0, 0, 5)
triangleMesh.Positions.Add(point0)
triangleMesh.Positions.Add(point1)
triangleMesh.Positions.Add(point2)
triangleMesh.TriangleIndices.Add(0)
triangleMesh.TriangleIndices.Add(2)
triangleMesh.TriangleIndices.Add(1)
Dim normal As New Vector3D(0, 1, 0)
triangleMesh.Normals.Add(normal)
triangleMesh.Normals.Add(normal)
triangleMesh.Normals.Add(normal)
Dim material As Material = New DiffuseMaterial(New
SolidColorBrush(Colors.DarkKhaki))
Dim triangleModel As New GeometryModel3D(triangleMesh, material)
Dim model As New ModelVisual3D()
model.Content = triangleModel
Me.mainViewport.Children.Add(model)

420

WPF

.23 .16 .

:

http://www.kindohm.com/technical/wpf3dtutorial.htm

421

WPF

.24 .16 .
:

.25 .16 .

422

WPF

.14 XNA

Direct3D OpenGL
XNA
API's DirectX DirectX

.
XNA DirectX Next Generation Architecture:
Express XNA
XNA :
:

http://www.c-sharpcorner.com/UploadFile/mgold/XNAIntro04192007233237PM/XNAIntro.aspx

423

WPF

DirectX ...
DirectX ...

MicrosoftExpressionStudio .15
MicrosoftExpressionWeb .1.15

XHTML, CSS, XML, XSLT . :

.26 .16 .Expression Web

424

WPF



HTML styles
Asp.net
.php
:

http://www.microsoft.com/expression/features/default.aspx?key=web

MicrosoftExpressionDesign .2.15

425

WPF

.27 .16 .Expression Design


:

http://www.microsoft.com/expression/features/default.aspx?key=design

MicrosoftExpressionMedia .3.15

426

WPF

.28 .16 .Expression Design


:

http://www.microsoft.com/expression/features/default.aspx?key=media

MicrosoftExpressionEncoder .4.15
Silver
Light Flash Macromedia
Adobe.

427

WPF

.29 .16 .Expression Encoder


:

http://www.microsoft.com/expression/features/default.aspx?key=encoder

MicrosoftExpressionBlend .5.15

...

428

WPF


Expression Blend
New Project ) WPF Application (*.exe
:

.29 .16 Expression Blend


Framework
.
View ActiveDocumentView Split XAML
:

429

WPF

.30 .16 Expression Blend




:

.31 .16 Expression Blend

430

WPF

.32 .16 Expression Blend


Canvas Canvas
:

XAML

><Canvas
>"<Canvas x:Name="MainImageCanvas" Canvas.Left="40" Canvas.Top="120

-
MediaElement
XAML :

XAML
"<MediaElement x:Name="MainImage" Source="c:/example/futex.jpg" Width="300
> "Height="300
></MediaElement

431

WPF

Canvas
XAML :

XAML

><Canvas.RenderTransform
><TransformGroup
"<SkewTransform x:Name="MainSkewTransform" AngleY="-19" AngleX="0
>CenterX="0" CenterY="0"/
"<ScaleTransform x:Name="MainScaleTransform" ScaleY="1" ScaleX = "1
>CenterX="0" CenterY="0"/
></TransformGroup
></Canvas.RenderTransform
></Canvas

F5 :

.33 .16 .

Canvas
XAML
:

432

WPF
XAML

<Canvas x:Name="ReflectionImageCanvas" Canvas.Left="260" Canvas.Top="640">


<MediaElement x:Name="ReflImage" Source="c:/example/futex.jpg" Width="300"
Height="300" Volume="0">
</MediaElement>
<Canvas.RenderTransform>
<TransformGroup>
<SkewTransform x:Name="ReflectionSkewTransform" AngleY="19"
AngleX="-41" CenterX="0" CenterY="0" />
<ScaleTransform x:Name="ReflectionScaleTransform" ScaleY="-1"
ScaleX="1" CenterX="0" CenterY="0" />
</TransformGroup>
</Canvas.RenderTransform>
</Canvas>

. .34 .16

: XAML

433

WPF
XAML

<Canvas x:Name="ReflectionImageCanvas" Canvas.Left="260" Canvas.Top="640">


<MediaElement x:Name="ReflImage" Source="c:/example/futex.jpg" Width="300"
Height="300" Volume="0">
</MediaElement>
<Canvas.RenderTransform>
<TransformGroup>
<SkewTransform x:Name="ReflectionSkewTransform" AngleY="19"
AngleX="-41" CenterX="0" CenterY="0" />
<ScaleTransform x:Name="ReflectionScaleTransform" ScaleY="-1"
ScaleX="1" CenterX="0" CenterY="0" />
</TransformGroup>
</Canvas.RenderTransform>
<Canvas.OpacityMask>
<LinearGradientBrush StartPoint="0.5,0.0" EndPoint="0.5,1.0">
<GradientStop Offset="0.345" Color="#00000000"
x:Name="ReflGradientStop1" />
<GradientStop Offset="1.0" Color="#CC000000"
x:Name="ReflGradientStop2" />
</LinearGradientBrush>
</Canvas.OpacityMask>
</Canvas>

Top Left
:

. .35 .16

434

WPF


:XAML

XAML
<Canvas>
<Canvas x:Name="MainImageCanvas" Canvas.Left="40" Canvas.Top="120">

<MediaElement x:Name="MainImage" Source="c:/example/FUTEX.JPG"


Width="300" Height="300" >
</MediaElement>
<Canvas.RenderTransform>
<TransformGroup>
<SkewTransform x:Name="MainSkewTransform" AngleY="-19"
AngleX="0" CenterX="0" CenterY="0"/>
<ScaleTransform x:Name="MainScaleTransform" ScaleY="1" ScaleX =
"1" CenterX="0" CenterY="0"/>
</TransformGroup>
</Canvas.RenderTransform>
</Canvas>
<Canvas x:Name="ReflectionImageCanvas" Canvas.Left="267" Canvas.Top="645">
<MediaElement x:Name="ReflImage" Source="c:/example/futex.jpg"
Width="300" Height="300" Volume="0">
</MediaElement>
<Canvas.RenderTransform>
<TransformGroup>
<SkewTransform x:Name="ReflectionSkewTransform" AngleY="19"
AngleX="-41" CenterX="0" CenterY="0" />
<ScaleTransform x:Name="ReflectionScaleTransform" ScaleY="-1"
ScaleX="1" CenterX="0" CenterY="0" />
</TransformGroup>
</Canvas.RenderTransform>
<Canvas.OpacityMask>
<LinearGradientBrush StartPoint="0.5,0.0" EndPoint="0.5,1.0">
<GradientStop Offset="0.345" Color="#00000000"
x:Name="ReflGradientStop1" />
<GradientStop Offset="1.0" Color="#CC000000"
x:Name="ReflGradientStop2" />
</LinearGradientBrush>
</Canvas.OpacityMask>
</Canvas>
</Canvas>


MediaElement
...
.

435

WPF


XAML
MicrosoftExpression
.
:

http://expression.microsoft.com/en-us/cc136522.aspx

436

437

17

ADO.net

438

439

ADO.net

Active Data Object.Net ADO.net


ADO 6
Data Providers
.DAO,RDO
ADO
Client/Server ADO.net Disconnected
.
:
. XML . . managedcode. :

http://msdn.microsoft.com/en-us/library/904fck4k(VS.71).aspx

440

ADO.net

.1 ADO.net

System.Data
Connected Disconnected

Connected .

.2 ADO.netDataProvider
: Connection -1 .
: Command -2 SQL .
:DataReader DbDataReader IDataReader -3
.
: DataAdapter DbDataAdapter IDataAdapter -4

.
: Parameter DbParameter IDataParameter -5
.

.1.2 DataProviders
:System.Data.OleDb

.
:System.Data.SqlClient

441

ADO.net

SQLServer
.
:System.Data.SqlServerCe
SQL Server CE
.PocketPC
:System.Data.Odbc
Odbc .
:System.Data.OracleClient
.

.2.2 ThirdParty
ADO.NETDataProviders

MYSQL FoxPro DB2


OleDb
DataProviders ADO.net

:

http://www.sqlsummit.com/dataprov.htm

442

ADO.net

System.Data .3

Exceptions
:

:IDbConnection

C#
public interface IDbConnection : IDisposable
{
string ConnectionString { get; set; }
int ConnectionTimeout { get; }
string Database { get; }
ConnectionState State { get; }
IDbTransaction BeginTransaction();
IDbTransaction BeginTransaction(IsolationLevel il);
void ChangeDatabase(string databaseName);
void Close();
IDbCommand CreateCommand();
void Open();
}

VB.NET
Public Interface IDbConnection
Inherits IDisposable
Property ConnectionString() As String
ReadOnly Property ConnectionTimeout() As Integer
ReadOnly Property Database() As String
ReadOnly Property State() As ConnectionState
Function BeginTransaction() As IDbTransaction
Function BeginTransaction(ByVal il As IsolationLevel) As IDbTransaction
Sub ChangeDatabase(ByVal databaseName As String)
Sub Close()
Function CreateCommand() As IDbCommand
Sub Open()
End Interface

:IDbCommand

:

443

ADO.net

C#
public interface IDbCommand : IDisposable
{
string CommandText { get; set; }
int CommandTimeout { get; set; }
CommandType CommandType { get; set; }
IDbConnection Connection { get; set; }
IDataParameterCollection Parameters { get; }
IDbTransaction Transaction { get; set; }
UpdateRowSource UpdatedRowSource { get; set; }
void Cancel();
IDbDataParameter CreateParameter();
int ExecuteNonQuery();
IDataReader ExecuteReader();
IDataReader ExecuteReader(CommandBehavior behavior);
object ExecuteScalar();
void Prepare();
}

VB.NET

Public Interface IDbCommand


Inherits IDisposable
Property CommandText() As String
Property CommandTimeout() As Integer
Property CommandType() As CommandType
Property Connection() As IDbConnection
ReadOnly Property Parameters() As IDataParameterCollection
Property Transaction() As IDbTransaction
Property UpdatedRowSource() As UpdateRowSource
Sub Cancel()
Function CreateParameter() As IDbDataParameter
Function ExecuteNonQuery() As Integer
Function ExecuteReader() As IDataReader
Function ExecuteReader(ByVal behavior As CommandBehavior) As IDataReader
Function ExecuteScalar() As Object
Sub Prepare()
End Interface

: IDbDataParameter
:
C#
public interface IDbDataParameter : IDataParameter
{
byte Precision { get; set; }
byte Scale { get; set; }
int Size { get; set; }
}

444

ADO.net

VB.NET

Public Interface IDbDataParameter


Inherits IDataParameter
Property Precision() As Byte
Property Scale() As Byte
Property Size() As Integer
End Interface

: IDataParameter
:
C#

public interface IDataParameter


{
DbType DbType { get; set; }
ParameterDirection Direction { get; set; }
bool IsNullable { get; }
string ParameterName { get; set; }
string SourceColumn { get; set; }
DataRowVersion SourceVersion { get; set; }
object Value { get; set; }
}

VB.NET

Public Interface IDataParameter


Property DbType() As DbType
Property Direction() As ParameterDirection
ReadOnly Property IsNullable() As Boolean
Property ParameterName() As String
Property SourceColumn() As String
Property SourceVersion() As DataRowVersion
Property Value() As Object
End Interface

: IDbDataAdapter
C#
public interface IDbDataAdapter : IDataAdapter
{
IDbCommand DeleteCommand { get; set; }
IDbCommand InsertCommand { get; set; }
IDbCommand SelectCommand { get; set; }
IDbCommand UpdateCommand { get; set; }
}

445

ADO.net

VB.NET
Public Interface IDbDataAdapter
Inherits IDataAdapter
Property DeleteCommand() As
Property InsertCommand() As
Property SelectCommand() As
Property UpdateCommand() As
End Interface

IDbCommand
IDbCommand
IDbCommand
IDbCommand

: IDataAdapter

C#
public interface IDataAdapter
{
MissingMappingAction MissingMappingAction { get; set; }
MissingSchemaAction MissingSchemaAction { get; set; }
ITableMappingCollection TableMappings { get; }
int Fill(System.Data.DataSet dataSet);
DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType);
IDataParameter[] GetFillParameters();
int Update(DataSet dataSet);
}

VB.NET
Public Interface IDataAdapter
Property MissingMappingAction() As MissingMappingAction
Property MissingSchemaAction() As MissingSchemaAction
ReadOnly Property TableMappings() As ITableMappingCollection
Function Fill(ByVal dataSet As System.Data.DataSet) As Integer
Function FillSchema(ByVal dataSet As DataSet, ByVal schemaType As
SchemaType) As DataTable()
Function GetFillParameters() As IDataParameter()
Function Update(ByVal dataSet As DataSet) As Integer
End Interface

: IDataReader
C#
public interface IDataReader : IDisposable, IDataRecord
{
int Depth { get; }
bool IsClosed { get; }
int RecordsAffected { get; }
void Close();
DataTable GetSchemaTable();
bool NextResult();
bool Read();
}

446

ADO.net

VB.NET

Public Interface IDataReader


Inherits IDisposable
Inherits IDataRecord
ReadOnly Property Depth() As Integer
ReadOnly Property IsClosed() As Boolean
ReadOnly Property RecordsAffected() As Integer
Sub Close()
Function GetSchemaTable() As DataTable
Function NextResult() As Boolean
Function Read() As Boolean
End Interface

: IDataRecord
C#
public interface IDataRecord
{
int FieldCount { get; }
object this[string name] { get; }
object this[int i] { get; }
bool GetBoolean(int i);
byte GetByte(int i);
char GetChar(int i);
DateTime GetDateTime(int i);
Decimal GetDecimal(int i);
float GetFloat(int i);
short GetInt16(int i);
int GetInt32(int i);
long GetInt64(int i);
//...
bool IsDBNull(int i);
}

447

ADO.net

VB.NET
Public Interface IDataRecord
ReadOnly Property FieldCount() As Integer
Default ReadOnly Property Item(ByVal name As String) As Object
Get
End Get
End Property
Default ReadOnly Property Item(ByVal i As Integer) As Object
Get
End Get
End Property
Function GetBoolean(ByVal i As Integer) As Boolean
Function GetByte(ByVal i As Integer) As Byte
Function GetChar(ByVal i As Integer) As Char
Function GetDateTime(ByVal i As Integer) As DateTime
Function GetDecimal(ByVal i As Integer) As Decimal
Function GetFloat(ByVal i As Integer) As Single
Function GetInt16(ByVal i As Integer) As Short
Function GetInt32(ByVal i As Integer) As Integer
Function GetInt64(ByVal i As Integer) As Long
'...
Function IsDBNull(ByVal i As Integer) As Boolean
End Interface

SQLServer .4
.1.4
. ADO.net
Employee

. WindowsForms
SQL Server
: Express

http://msdn.microsoft.com/vstudio/express/sql

448

ADO.net

.
View ServerExplorer
CreateNewSqlServerDatabase :

.1 .17

SQL Server
Server Explorer
.

Create

.2 .17

SQL Server
.

449

ADO.net

***
-
. . -
: ***
Anerrorhasoccurredwhileestablishingaconnectiontotheserver.WhenconnectingtoSQLServer2005,
this failure may be caused by the fact that under the default settings SQL Server does not allow remote
connections.(provider:NamedPipesProvider,error:40CouldnotopenaconnectiontoSQLServer)

Configuration Microsoft SQL Server 2005


SQL Server 2005 Surface Area Configuration Tools
Surface Area Configuration for Services and connections
. Localandremoteconnections
:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=192622&SiteID=1

450

ADO.net

.3 .17 .
Stored Procedure
:

.4 .17 .

451

ADO.net

setprimarykey autonumber Identity


Specfications yes Increment 1
:

.5 .17 Primary Key .


.
.
.
Employee_Info

:

452

ADO.net

.6 .17 .

:

.6 .17 .

453

ADO.net

: SQLServer

9,223,372,036,854,775,807

9,223,372,036,854,775,808

bigint

2,147,483,647

2,147,483,648

int

32,767

32,768

smallint

255

tinyint

bit

10^381

10^38+1

decimal

10^381

10^38+1

numeric

+922,337,203,685,477.5807

922,337,203,685,477.5808

money

+214,748.3647

214,748.3648

smallmoney

1.79E+308

1.79E+308

float

3.40E+38

3.40E+38

real

Dec31,9999

Jan1,1753

datetime (3.33
milliseconds
accuracy)

Jun6,2079

Jan1,1900

smalldatetime
(1minute
accuracy)

454

8000

char

8000 nonUnicode

varchar


) varchar(max

ADO.net

nonUnicode
231

text

nonUnicode 2,147,483,647

nchar

Unicode 4,000

nvarchar

Unicode 4,000

) nvarchar(max

nonUnicode
230

ntext

Unicode 1,073,741,823 .

binary

of8,000 .

varbinary

of8,000 .

) varbinary(max

231

image

2,147,483,647 .

.1 .17 .SQLServer
.net
: .net
(SQL CLR

SQLSERVER

CLR .net

Bigint

>Int64,Nullable<Int64

SqlInt64

Binary

][Byte

SqlBytes,SqlBinary

Server)

455

SqlBoolean

Boolean,Nullable<Boolean>

bit

char

cursor

SqlDateTime

DateTime,Nullable<DateTime>

date

SqlDateTime

DateTime,Nullable<DateTime>

datetime

SqlDateTime

DateTime,Nullable<DateTime>

datetime2

DateTimeOffset,
Nullable<DateTimeOffset>

DATETIMEOFFSET

SqlDecimal

Decimal,Nullable<Decimal>

decimal

SqlDouble

Double,Nullable<Double>

float

image

SqlInt32

Int32,Nullable<Int32>

int

SqlMoney

Decimal,Nullable<Decimal>

money

SqlChars,SqlString

String,Char[]

nchar

ntext

SqlDecimal

Decimal,Nullable<Decimal>

numeric

SqlChars,SqlString

String,Char[]

nvarchar

SqlChars,SqlString

Char,String,Char[],
Nullable<char>

nvarchar(1),nchar(1)

SqlSingle

Single,Nullable<Single>

real

Byte[]

rowversion

SqlInt16

Int16,Nullable<Int16>

smallint

456

ADO.net

SqlMoney

Decimal,Nullable<Decimal>

smallmoney

Object

sql_variant

table

text

TimeSpan

TimeSpan,Nullable<TimeSpan>

time

timestamp

SqlByte

Byte,Nullable<Byte>

tinyint

SqlGuid

Guid,Nullable<Guid>

uniqueidentifier

Userdefinedtype(UDT)

SqlBytes,SqlBinary

Byte[]

varbinary

SqlBytes,SqlBinary

byte,Byte[],Nullable<byte>

varbinary(1),binary(1)

varchar

SqlXml

xml

. SQLServer .2 .17

SQLStatements .2.4

SQL
.StructuredQueryLanguage
Access MS sql - Oracle :
. Server

457

ADO.net


-
.

.

:

SQ
QL
.7 .17

SQL
SELECT Colums_Nam
C
e FROM Tab
;ble_Name

:


.SQL
S


:Se
elect
_ :Colum .
_Name
.

:From

458

ADO.net

:Table_Name .
) ( Syntax :
* .
* = = : .
* ;
.
:

SQL
;SELECT FName FROM Tb_Main

SQL
;SELECT FName,LName FROM Tb_Main

* :

SQL
;SELECT * FROM Tb_Main


DISTINCT ...
:

SQL
;SELECT DISTINCT FNAme FROM Tb_Main

SQL
... ORDER BY colum

459

ADO.net

SQL
... ORDER BY colum DESC

SQL
;SELECT * FROM Tb_Main ORDER BY FName DESC


- -
:

SQL
; SELECT * FROM Tb_Main ORDER BY FName,Lname

SQL
;SELECT * FROM Tb_Main WHERE Field = Value

> < >= <= >< =.


LIKEBETWEEN
18 :

SQL
;SELECT * FROM tb_Main WHERE age = 18

50:

SQL
;SELECT FName,LName FROM tb_Main WHERE age < 50

Value -
) ( :

SQL
;'SELECT * FROM tb_Main WHERE Fname = 'ahmed

#
:

460

ADO.net

SQL
;SELECT * Form Table1 WHERE Date > #12/03/04#

:
And Or
.
17
:

SQL
;SELECT Fname FROM tb_main WHERE age > 17 AND marry = false

: LIKE
LIKE ...
LIKE :

SQL
;'SELECT * FROM Table WHERE Field LIKE '%Name%

% ... .
:
...hm
:

SQL
;'SELECT * FROM Tb_Main WHERE FName like '%hm%

A % :

SQL
;'SELECT * FROM Tb_Main WHERE FName like 'A%

461

ADO.net

% .

%
MSAccess *
%
"_" Access "" .

%
)_ (underscore

A

N

] [
'Like '[A-N]ack

]^[
'Like '[^B]ack

.3 .17 LIKE .
: A
3.

SQL
;'__SELECT * FROM Tb_Main WHERE FName like 'A

BETWEEN

.
BETWEEN :

SQL
;SELECT colum FROM table WHERE field BETWEEN v1 AND v2

462

ADO.net

20 :60

SQL
* SELECT
FROM tb_main
;WHERE age BETWEEN 20 AND 60

- -
.
:

SQL
;SELECT func(colum) FROM table WHERE condition

:AVG


:

SQL
;SELECT AVG(Age) FROM tb_main


-- .

...
:25

SQL
;SELECT AVG(Age) FROM tb_main WHERE age < 25

463

ADO.net

Expr100 ... -
- As :

SQL
;SELECT AVG(Age) AS AVGAGE FROM tb_main WHERE age < 25

...

: Sum,Max,Min
- -
:

SQL
;SELECT max(Age) AS mxAGE FROM tb_main

:Count
:

SQL
)*(SELECT COUNT
;FROM Table1

SQL
)SELECT COUNT(DISTINCT Title
;FROM Table1

464

ADO.net

TSql
. :

SQL

SELECT tb_main.Fname, tb_main.lname, Tb_R1.passport, tb_r1.bclass, tb_r1.from


FROM tb_main, tb_r1
;WHERE tb_main.Number = tb_r1.Number

:
: . .

: FROM .
:
.

: DDL

DDL
:

SQL
;)CREATE TABLE tb1 ( colum type, colum type,........

Tb2 Name )
...
( String - Age : Number

SQL
; )CREATE TABLE tb1 (name text,age number

Name ...
Text :

SQL
;) CREATE TABLE tb1 (name text(6),age number

465

ADO.net

... - Null
:

SQL
;) CREATE TABLE tb1 (name text(6) Not Null,age number

... :

SQL
;DROP Table tb1

CASCADE
:

SQL
;DROP Table tb1 CASCADE

-
- .
:

SQL
;ALTER TABLE tb1 ADD colum type

: ) - ( :

SQL
;ALTER TABLE tb1 ADD birth_Date date,Gender Text

Gender ...
CASCADE - - :

SQL
;ALTER TABLE tb1 DROP gender CASCADE

466

ADO.net

DML :
DML
Tb_Main :

SQL
;)INSERT INTO table VALUES (v1, v2,......


"" .##
: - - - - - -
- - - -/ -.
:

SQL
INSERT INTO tb_main VALUES
(11,'ahmed','gamal',6666666,18,'Cairo','Hammada2091','First
;)''Year','','',false,

:
:

SQL
UPDATE table_name
SET colum1 = v1 , colum2 = v2
;WHERE colum = v

= 28 = www.vb4arab.com

) ( Ahmed ) : ( Gamal

SQL
UPDATE tb_main
'SET age=25 , site='www.vb4arab.com
;'WHERE fname='ahmed' AND lname='Gamal

... :

467

ADO.net

SQL
;DELETE FROM table WHERE colum = value

..
:

SQL
;DELETE FROM tb_main WHERE age>40

... :

SQL
;DELETE * FROM table

StoredProcedures .3.4
StoredPrcoedure
:

SQL
;SELECT [First Name] FROM employee_info WHERE age>21

Procedure :

TSQL
CREATE PROCEDURE dbo.GetAge
@firstname char(10) output
AS
]SELECT @firstname =[First Name
FROM Employee_info
WHERE age > 21

Create Alter . StoredPrcoedure return value Input . Output

468

ADO.net

. StoredProcedure :

.8 .17 .Stored Procedure


Excute

469

ADO.net

.9 .17 .Stored Procedure




:

TSQL
ALTER PROCEDURE dbo.GetAge

@condition int,
@firstname char(10) output
AS
]SELECT @firstname =[First Name
FROM Employee_info
WHERE age > @condition

SQLServer
.

Update Delete Insert


Select .

470

ADO.net

SQLInjection .4.4

Stored Procedure
.

:

C#

string cmd = "select id from Users where nams like '"+textBox1.Text+"' and pass
;"'"like '"+textBox2.Text+

ID
:
'(insert into Users values(1,'NewUser','1234

NewUser !!! 1234
:
a' or 't'='t

:
drop table Tablename
!!!
Stored Procedure
...

471

ADO.net

.5.4


:

.9 .17 .
Database Diagram Add New
:

.10 .17 .Database Diagram


SqlServer
SQLServer :

http://msdn.microsoft.com/en-us/sqlserver/default.aspx

...

472

ADO.net

.5
ConnectionStringBuilder .1.5
Connection String
:

C#
SqlConnectionStringBuilder cnStrBuilder = new SqlConnectionStringBuilder();
cnStrBuilder.InitialCatalog = "Employee";
cnStrBuilder.DataSource = @"(local)\SQLEXPRESS";
cnStrBuilder.ConnectTimeout = 30;
cnStrBuilder.Password = "124";
cnStrBuilder.UserID = "Ahmed";
SqlConnection cn = new SqlConnection();
cn.ConnectionString = cnStrBuilder.ConnectionString;
cn.Open();

VB.NET
Dim cnStrBuilder As New SqlConnectionStringBuilder()
cnStrBuilder.InitialCatalog = "Employee"
cnStrBuilder.DataSource = "(local)\SQLEXPRESS"
cnStrBuilder.ConnectTimeout = 30
cnStrBuilder.Password = "124"
cnStrBuilder.UserID = "Ahmed"
Dim cn As New SqlConnection()
cn.ConnectionString = cnStrBuilder.ConnectionString
cn.Open()

:
InitialCatalog
DataSource
ConnectTimeout
.

473

ADO.net

. - Password
. - UserID
:

http://msdn.microsoft.com/enus/library/system.data.sqlclient.sqlconnectionstringbuilder_members.aspx

Command .2.5
Command
:
StoredProcedure TableDirect Text Text Command
:

C#

string strSQL = "Select * From Employee_Info";


SqlCommand myCommand = new SqlCommand(strSQL, cn);

VB.NET

Dim strSQL As String = "Select * From Employee_Info"


Dim myCommand As New SqlCommand(strSQL, cn)

:
C#
SqlCommand testCommand = new SqlCommand();
testCommand.Connection = cn;
testCommand.CommandText = strSQL;

474

ADO.net

VB.NET
)(Dim testCommand As New SqlCommand
testCommand.Connection = cn
testCommand.CommandText = strSQL

ExecuteReader
:
:ExecuteReader
DataReader .
Update
:ExecuteNonQuery
Delete .
:ExecuteScalar
.xxxxxx
: ExecuteXmlReader XML XmlReader
XML .XmlReader

ParameterizedCommandObjects
SQLInjection
Parameters
.StoredProcedure
:

C#
string strSQL = "Select [First Name]+[Last Name] as [Full Name], Age From
;Employee where ID=" + ID
;)SqlCommand myCommand = new SqlCommand(strSQL, cn

VB.NET
Dim strSQL As String = "Select [First Name]+[Last Name] as [Full Name], Age
From Employee where ID=" + ID
)Dim myCommand As New SqlCommand(strSQL, cn

475

ADO.net

SQL Injection
:SqlParameter

C#

string sql = string.Format("Select [First Name]+[Last Name] as [Full Name], Age


From Employee where ID=@ID");
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
// Fill params collection.
SqlParameter param = new SqlParameter();
param.ParameterName = "@ID";
param.Value = 10;
param.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(param);
//
cmd.ExecuteNonQuery();
}

VB.NET
Dim sql As String = String.Format("Select [First Name]+[Last Name] as [Full
Name], Age From Employee where ID=@ID")
Using cmd As New SqlCommand(sql, Me.sqlCn)
' Fill params collection.
Dim param As New SqlParameter()
param.ParameterName = "@ID"
param.Value = 10
param.SqlDbType = SqlDbType.Int
cmd.Parameters.Add(param)
'
cmd.ExecuteNonQuery()
End Using

Stored
Procedure
:

476

ADO.net

TSQL

ALTER PROCEDURE dbo.GetAge

@condition int,
@firstname char(10) output
AS
SELECT @firstname=[First Name] from Employee_info where age > @condition
WHERE age > @condition

GetAge

C#
using (SqlCommand cmd = new SqlCommand("GetAge", cn))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter();
param.ParameterName = "@condition";
param.SqlDbType = SqlDbType.Int;
param.Value = myAge;
param.Direction = ParameterDirection.Input;
cmd.Parameters.Add(param);
param = new SqlParameter();
param.ParameterName = "@firstnameName";
param.SqlDbType = SqlDbType.Char;
param.Size = 10;
param.Direction = ParameterDirection.Output;
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
MessageBox.Show(cmd.Parameters["@firstName"].Value.ToString());
}

477

ADO.net

VB.NET
Using cmd As New SqlCommand("GetAge", cn)
cmd.CommandType = CommandType.StoredProcedure
Dim param As New SqlParameter()
param.ParameterName = "@condition"
param.SqlDbType = SqlDbType.Int
param.Value = myAge
param.Direction = ParameterDirection.Input
cmd.Parameters.Add(param)
param = New SqlParameter()
param.ParameterName = "@firstnameName"
param.SqlDbType = SqlDbType.[Char]
param.Size = 10
param.Direction = ParameterDirection.Output
cmd.Parameters.Add(param)
cmd.ExecuteNonQuery()
MessageBox.Show(cmd.Parameters("@firstName").Value.ToString())
End Using

Text Command
.

DataReaders .3.5
:
DataReader

C#
string listItem = "";
while (myDataReader.Read())
{
listItem = "Full Name: " + myDataReader["Full Name"].ToString() + " Age: "
+ myDataReader["Age"].ToString();
listBox1.Items.Add(listItem);
}

VB.NET

Dim listItem As String = ""


While myDataReader.Read()
listItem = "Full Name: " + myDataReader("Full Name").ToString() + " Age: "
+ myDataReader("Age").ToString()
listBox1.Items.Add(listItem)
End While

478

ADO.net

true Read
...
myDataReader["Age"]
.
myDataReader[2]
FieldCount
:

C#

for (int i = 0; i < myDataReader.FieldCount; i++)


{
listItem = "Full Name: " + myDataReader["Full Name"].ToString() + " Age: "
+ myDataReader["Age"].ToString();
listBox1.Items.Add(listItem);
myDataReader.Read();
}

VB.NET

For i As Integer = 0 To myDataReader.FieldCount - 1


listItem = "Full Name: " + myDataReader("Full Name").ToString() + " Age: "
+ myDataReader("Age").ToString()
listBox1.Items.Add(listItem)
myDataReader.Read();
Next

: NextResult

DataReader
:

C#
string strSQL = "Select * From Employee_info;Select * from projects";
SqlCommand myCommand = new SqlCommand(strSQL, cn);
do
{
while (myDataReader.Read())
{
for (int i = 0; i < myDataReader.FieldCount; i++)
listItem = "Data: " + myDataReader[0].ToString();
}
}
while (myDataReader.NextResult());

479

ADO.net

VB.NET
"Dim strSQL As String = "Select * From Employee_info;Select * from projects
)Dim myCommand As New SqlCommand(strSQL, cn
Do
)(While myDataReader.Read
For i As Integer = 0 To myDataReader.FieldCount - 1
)(listItem = "Data: " + myDataReader(0).ToString
Next
End While
)(Loop While myDataReader.NextResult

DataAccessLayer .6

Layers
:

http://www.al-asiri.com/ShowRecord.aspx?Action=Open&id=cefa426c-d9e0-4625-a66b87fd6082ff89

http://vb4arab.com/vb/showthread.php?t=10969

data layer
:
. .


.

480

ADO.net


layer
...

.

-1

C#
;)(private SqlConnection cn = new SqlConnection
)public void OpenConnection(string connectionString
{
;cn.ConnectionString = connectionString
;)(cn.Open
}
)(public void CloseConnection
{
;)(cn.Close
}

VB.NET
)(Private cn As New SqlConnection
)Public Sub OpenConnection(ByVal connectionString As String
cn.ConnectionString = connectionString
)(cn.Open
End Sub
)(Public Sub CloseConnection
)(cn.Close
End Sub

-2 .




OverLoading Enums .
***

481

ADO.net

C#
public void DeleteEmployee(int id){
string sql = string.Format("Delete from Employee where ID = {0}",id);
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
try{
cmd.ExecuteNonQuery();
}
catch (SqlException ex) {
Exception error = new Exception("some error occures: ", ex);
throw error;
}
}
}
public void DeleteEmployee(string name){
string sql = string.Format("Delete from Employee where [First Name] =
'{0}'", name);
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
try{
cmd.ExecuteNonQuery();
}
catch (SqlException ex){
Exception error = new Exception("some error occures: ", ex);
throw error;
}
}
}
enum deletecondition{
morethan = 0,
lessthan = 1,
equal = 2
}
public void DeleteEmployee(int age, deletecondition delcondition){
string sql = "";
if (delcondition == deletecondition.morethan)
sql = string.Format("Delete from Employee where age > {0}", age);
else if (delcondition == deletecondition.lessthan)
sql = string.Format("Delete from Employee where age < {0}", age);
else
sql = string.Format("Delete from Employee where age = {0}", age);
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
Exception error = new Exception("some error occures: ", ex);
throw error;
}
}
}

482

ADO.net

VB.NET

Public Sub DeleteEmployee(ByVal id As Integer)


Dim sql As String = String.Format("Delete from Employee where ID = '{0}'",
id)
Using cmd As New SqlCommand(sql, Me.sqlCn)
Try
cmd.ExecuteNonQuery()
Catch ex As SqlException
Dim [error] As New Exception("some error occures: ", ex)
Throw [error]
End Try
End Using
End Sub
Public Sub DeleteEmployee(ByVal name As String)
Dim sql As String = String.Format("Delete from Employee where [First Name]
= '{0}'", name)
Using cmd As New SqlCommand(sql, Me.sqlCn)
Try
cmd.ExecuteNonQuery()
Catch ex As SqlException
Dim [error] As New Exception("some error occures: ", ex)
Throw [error]
End Try
End Using
End Sub
Enum deletecondition
morethan = 0
lessthan = 1
equal = 2
end enum
Public Sub DeleteEmployee(ByVal age As Integer, ByVal delcondition As
deletecondition)
Dim sql As String = ""
If delcondition = deletecondition.morethan Then
sql = String.Format("Delete from Employee where age > {0}", age)
ElseIf delcondition = deletecondition.lessthan Then
sql = String.Format("Delete from Employee where age < {0}", age)
Else
sql = String.Format("Delete from Employee where age = {0}", age)
End If
Using cmd As New SqlCommand(sql, Me.sqlCn)
Try
cmd.ExecuteNonQuery()
Catch ex As SqlException
Dim [error] As New Exception("some error occures: ", ex)
Throw [error]
End Try
End Using
End Sub

483

ADO.net

-3
.
.

.

C#
public void InsertEmployee(string fname, string lname, int age)
{
// Format and execute SQL statement.
string sql = string.Format("Insert Into Employee_info" +
"([First Name], [Last Name]) Values" +
"('{0}', '{1}')", fname, lname);
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
cmd.ExecuteNonQuery();
}
}
public void UpdateEmployee(int id, string newFirstName) {
string sql = string.Format("Update Employee Set [First Name] = '{0}' Where
ID = '{1}'",
newFirstName, id);
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn)) {
cmd.ExecuteNonQuery();
}
}

VB.NET

Public Sub InsertEmployee(ByVal fname As String, ByVal lname As String, ByVal


age As Integer)
' Format and execute SQL statement.
Dim sql As String = String.Format("Insert Into Employee_info" + "([First
Name], [Last Name]) Values" + "('{0}', '{1}')", fname, lname)
Using cmd As New SqlCommand(sql, Me.sqlCn)
cmd.ExecuteNonQuery()
End Using
End Sub
Public Sub UpdateEmployee(ByVal id As Integer, ByVal newFirstName As String)
Dim sql As String = String.Format("Update Employee Set [First Name] = '{0}'
Where ID = '{1}'", newFirstName, id)
Using cmd As New SqlCommand(sql, Me.sqlCn)
cmd.ExecuteNonQuery()
End Using
End Sub

484

ADO.net

. -4

SqlInjection Parameters
.
ID
DataLayer
.
: StoredProcedure

TSQL
CREATE PROCEDURE GetFirstNameByID
@id int,
@fName char(10) output
AS
SELECT @fName=[First Name] FROM Employee_info WHERE ID > @id

:
C#
public string SelectName(int id)
{
using (SqlCommand cmd = new SqlCommand("GetFirstNameByID", cn))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter();
param.ParameterName = "@id";
param.SqlDbType = SqlDbType.Int;
param.Value = ID;
param.Direction = ParameterDirection.Input;
cmd.Parameters.Add(param);
param = new SqlParameter();
param.ParameterName = "@fName";
param.SqlDbType = SqlDbType.Char;
param.Size = 10;
param.Direction = ParameterDirection.Output;
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
return cmd.Parameters["@fName"].Value.ToString();
}
return carPetName;
}

485

ADO.net

VB.NET

Public Sub InsertEmployee(ByVal fname As String, ByVal lname As String, ByVal


age As Integer)
' Format and execute SQL statement.
Dim sql As String = String.Format("Insert Into Employee_info" + "([First
Name], [Last Name]) Values" + "('{0}', '{1}')", fname, lname)
Using cmd As New SqlCommand(sql, Me.sqlCn)
cmd.ExecuteNonQuery()
End Using
End Sub
Public Sub UpdateEmployee(ByVal id As Integer, ByVal newFirstName As String)
Dim sql As String = String.Format("Update Employee Set [First Name] = '{0}'
Where ID = '{1}'", newFirstName, id)
Using cmd As New SqlCommand(sql, Me.sqlCn)
cmd.ExecuteNonQuery()
End Using
End Sub

dll DataLayer DataLayer Class


: myDataLayer

C#
myDataLayer example=new myDataLayer();
example.OpenConnection(myconnectionstring);
example.DeleteEmployee(10);
example.DeleteEmployee("Ahmed");

VB.NET

Dim example As New myDataLayer()


example.OpenConnection(myconnectionstring)
example.DeleteEmployee(10)
example.DeleteEmployee("Ahmed")

!!!
. dll


.

486

ADO.net

AsynchronousDataAccess .7


Disconnected
:

C#
SqlConnection cn = new SqlConnection();
cn.ConnectionString = @"Data Source=(local)\SQLEXPRESS;Integrated
Security=SSPI;" +
"Initial Catalog=AutoLot;Asynchronous Processing=true";
cn.Open();

VB.NET
Dim cn As New SqlConnection()
cn.ConnectionString = "Data Source=(local)\SQLEXPRESS;Integrated
Security=SSPI;" + "Initial Catalog=AutoLot;Asynchronous Processing=true"
cn.Open()

Asynchronous Processing = true


: ConnectioString
EndExecuteReader() BeginExecuteReader()
EndExecuteNonQuery() BeginExecuteNonQuery()
EndExecuteXmlReader() BeginExecuteXmlReader()
EndExecuteReader BeginExecuteReader
:

C#
string strSQL = "WaitFor Delay '00:00:05';Select * From Employee_info";
SqlCommand myCommand = new SqlCommand(strSQL, cn);

VB.NET

Dim strSQL As String = "WaitFor Delay '00:00:05';Select * From Employee_info"


Dim myCommand As New SqlCommand(strSQL, cn)

487

ADO.net

C#
IAsyncResult itfAsynch;
itfAsynch = myCommand.BeginExecuteReader(CommandBehavior.CloseConnection);

VB.NET
Dim itfAsynch As IAsyncResult
itfAsynch = myCommand.BeginExecuteReader(CommandBehavior.CloseConnection)

C#
while (!itfAsynch.IsCompleted)
{
// .
System.Threading.Thread.Sleep(1000);
}

VB.NET
While Not itfAsynch.IsCompleted
' .
Thread.Sleep(1000)
End While

Loop
.
C#

SqlDataReader myDataReader = myCommand.EndExecuteReader(itfAsynch);


while (myDataReader.Read())
{
MessageBox.Show(myDataReader[1].ToString());
}
myDataReader.Close();

VB.NET
Dim myDataReader As SqlDataReader = myCommand.EndExecuteReader(itfAsynch)
While myDataReader.Read()
MessageBox.Show(myDataReader(0).ToString())
End While
myDataReader.Close()

488

ADO.net

Transactions .8

1 .2
:
500 .1
500 .2



.rollback
transaction
DBMS .
SqlTransaction
System.Data.SqlClient
.net :
:System.EnterpriseServices COM+
.
:System.Transactions .transactions
WCF : WWF transaction.
Stored Procedure
transactions TRANSACTION ROLLBACK COMMIT
:

489

ADO.net

http://msdn.microsoft.com/en-us/library/ms187844.aspx

IDbTransaction DBTransaction ADO.net


:

C#
public interface IDbTransaction : IDisposable
{
IDbConnection Connection { get; }
IsolationLevel IsolationLevel { get; }
void Commit();
void Rollback();
}

VB.NET
Public Interface IDbTransaction
Inherits IDisposable
ReadOnly Property Connection() As IDbConnection
ReadOnly Property IsolationLevel() As IsolationLevel
Sub Commit()
Sub Rollback()
End Interface

Save SqlTransaction
-
.
- )
: (

C#
SqlCommand cmdGet = new SqlCommand("update customers set
totalmoney.ToString() + " where ID" + custID.ToString(),
cmdSelect.ExecuteNonQuery();
SqlCommand cmdSet = new SqlCommand("update customers set
totalmoney.ToString() + " where ID" + SuppID.ToString(),
cmdSelect.ExecuteNonQuery();

490

total=total-" +
cn);
total=total+" +
cn);

ADO.net

VB.NET
Dim cmdGet As New SqlCommand("update customers set total=total-" +
totalmoney.ToString() + " where ID" + custID.ToString(), cn)
cmdSelect.ExecuteNonQuery()
Dim cmdSet As New SqlCommand("update customers set total=total+" +
totalmoney.ToString() + " where ID" + SuppID.ToString(), cn)
cmdSelect.ExecuteNonQuery()



.
C#
SqlCommand cmdGet = new SqlCommand("update customers set total=total-" +
totalmoney.ToString() + " where ID" + custID.ToString(), cn);
SqlCommand cmdSet = new SqlCommand("update customers set total=total+" +
totalmoney.ToString() + " where ID" + SuppID.ToString(), cn);
SqlTransaction sqltr = null;
try
{
sqltr = sqlCn.BeginTransaction();
cmdGet.Transaction = sqltr;
cmdSet.Transaction = sqltr;
cmdGet.ExecuteNonQuery();
cmdSet.ExecuteNonQuery();
if (throwEx)
{
throw new ApplicationException("all operation canceld, some errors
occures");
}
sqltr.Commit();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
tx.Rollback();
}

491

ADO.net

VB.NET
Dim cmdGet As New SqlCommand("update customers set total=total-" +
totalmoney.ToString() + " where ID" + custID.ToString(), cn)
Dim cmdSet As New SqlCommand("update customers set total=total+" +
totalmoney.ToString() + " where ID" + SuppID.ToString(), cn)
Dim sqltr As SqlTransaction = Nothing
Try
sqltr = sqlCn.BeginTransaction()
cmdGet.Transaction = sqltr
cmdSet.Transaction = sqltr
cmdGet.ExecuteNonQuery()
cmdSet.ExecuteNonQuery()
If throwEx Then
Throw New ApplicationException("all operation canceld, some errors
occures")
End If
sqltr.Commit()
Catch ex As Exception
MessageBox.Show(ex.Message)
tx.Rollback()
End Try

transaction
Commit
catch throw Exception
. Rollback
throwEx=true
.

1
.2 1
***

.

492

ADO.net

.9
ADO.net connectedlayer

disconnectedlayer

.
DataAdapter
DataSet .
DataSet DataTable DataRow
.DataColumn
DataSet

.

.1.9 DataSet
DataSet -
- :

:
: DataTableCollection .
: DataRelationCollection .
: PropertyCollection .DataSet

493

ADO.net

:
: DataSetName.
: RemotingFormat serialize binary
XML .
:
)( : AcceptChanges DataSet
AcceptChanges .
)( : RejectChanges DataSet
AcceptChanges.
)( : Clear DataSet
)( : Clone structure
)( : Copy .
)( : GetChanges
AcceptChanges.
)( : HasChanges Boolean
AcceptChanges .
)( :Merge .DataSet
)( ReadXml )( : WriteXml XML DataSet

: DataSet
DataSet :

494

ADO.net
C#

;)"DataSet empDataSet = new DataSet("My Employee

VB.NET
)"Dim empDataSet as DataSet = New DataSet("My Employee

.net Data DataSet


:

.11 .17 DataSet .

.2.9 DataTable

:
)( : Copy .
: DataSet DataSet Table

495

ADO.net

. PrimaryKey : PrimaryKey
. : TableName
. : ParentRelations

DataTable .3.9

C#
DataTable EmployeeTable = new DataTable();
EmployeeTable.PrimaryKey = new DataColumn[] { EmployeeTable.Columns[0] };

VB.NET
Dim EmployeeTable As New DataTable()
EmployeeTable.PrimaryKey = New DataColumn() {EmployeeTable.Columns(0)}

: DataSet DataTable

C#
empDataSet.Tables.Add(EmployeeTable);

VB.NET
empDataSet.Tables.Add(EmployeeTable)

DataColumn .4.9

DataTable DataColumns
:

496

ADO.net

AllowDBNull
Null
AutoIncrement
SQLServer AutoIncrementSeed

AutoIncrementStep

Caption
DataType
DefaultValue
DataTable Table
Primarykey Unique
.DataColumn .4 .17

:DataColumns


:
C#
DataColumn EmpIDColumn = new DataColumn("ID", typeof(int));
EmpIDColumn.Caption = "Employee ID";
EmpIDColumn.ReadOnly = true;
EmpIDColumn.AllowDBNull = false;
EmpIDColumn.AutoIncrement = true;
EmpIDColumn.AutoIncrementSeed = 1;
EmpIDColumn.AutoIncrementStep = 1;
EmpIDColumn.Unique = true;
DataColumn EmpNameColumn = new DataColumn("Name", typeof(string));
EmpNameColumn.Caption = "Employee Name";
DataColumn EmpAgeColumn = new DataColumn("Age", typeof(int));
EmpNameColumn.Caption = "Employee Age";

497

ADO.net

VB.NET
Dim EmpIDColumn As New DataColumn("ID", GetType(Integer))
EmpIDColumn.Caption = "Employee ID"
EmpIDColumn.[ReadOnly] = True
EmpIDColumn.AllowDBNull = False
EmpIDColumn.AutoIncrement = True
EmpIDColumn.AutoIncrementSeed = 1
EmpIDColumn.AutoIncrementStep = 1
EmpIDColumn.Unique = True
Dim EmpNameColumn As New DataColumn("Name", GetType(String))
EmpNameColumn.Caption = "Employee Name"
Dim EmpAgeColumn As New DataColumn("Age", GetType(Integer))
EmpNameColumn.Caption = "Employee Age"

: DataTable

C#

EmployeeTable.Columns.AddRange(new DataColumn[] { EmpIDColumn, EmpNameColumn,


EmpAgeColumn });

VB.NET

EmployeeTable.Columns.AddRange(New DataColumn() {EmpIDColumn, EmpNameColumn,


EmpAgeColumn})

DataRow .5.9
:

objects array ItemArray


Table
AcceptChanges()
RejectChanges()
AcceptChanges()

498

ADO.net

)( BeginEdit
)( EndEdit
)( CancelEdit
)( Delete )(AcceptChanges
)( IsNull null
RowState enum
DataRowState
.5 .17 .DataRow
- DataRowState :

.12 .17 .DataRowState enum

DataRows
DataRow :

C#
;)(DataRow r = new DataRow

499

ADO.net

VB.NET
Dim r As DataRow = new DataRow();

DataRow DataRow
.

C#
DataRow EmpRow = EmployeeTable.NewRow();
EmpRow["Name"] = "Ahmed Gamal";
EmpRow["Age"] = 22;
EmployeeTable.Rows.Add(EmpRow);
EmpRow = EmployeeTable.NewRow();
EmpRow[1] = "Ahmed Essawy";
EmpRow[2] = 23;
EmployeeTable.Rows.Add(EmpRow);

VB.NET
Dim EmpRow As DataRow = EmployeeTable.NewRow()
EmpRow("Name") = "Ahmed Gamal"
EmpRow("Age") = 22
EmployeeTable.Rows.Add(EmpRow)
EmpRow = EmployeeTable.NewRow()
EmpRow(1) = "Ahmed Essawy"
EmpRow(2) = 23
EmployeeTable.Rows.Add(EmpRow)

ID
.Index

500

ADO.net

DataSet :
:
C#

Text1.Text = "";
foreach (DataTable dt in empDataSet.Tables)
{
Text1.Text += dt.TableName + ":\n\r";
for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
{
Text1.Text += (curCol + 1).ToString() + dt.Columns[curCol].ColumnName +
"\n\r";
}
Text1.Text = "Rows: \n\r";
for (int curRow = 0; curRow < dt.Rows.Count; curRow++)
{
for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
{
Text1.Text += dt.Rows[curRow][curCol].ToString() + " - ";
}
}
}

VB.NET

Text1.Text = ""
For Each dt As DataTable In empDataSet.Tables
Text1.Text += dt.TableName + ":" & Chr(10) & "" & Chr(13) & ""
For curCol As Integer = 0 To dt.Columns.Count - 1
Text1.Text += (curCol + 1).ToString() + dt.Columns(curCol).ColumnName +
"" & Chr(10) & "" & Chr(13) & ""
Next
Text1.Text = "Rows: " & Chr(10) & "" & Chr(13) & ""
For curRow As Integer = 0 To dt.Rows.Count - 1
For curCol As Integer = 0 To dt.Columns.Count - 1
Text1.Text += dt.Rows(curRow)(curCol).ToString() + " - "
Next
Next
Next

501

ADO.net

DataTableReader .6.9
DataTable

C#
Text1.Text = "";
DataTableReader dtReader = dt.CreateDataReader();
while (dtReader.Read())
{
for (int i = 0; i < dtReader.FieldCount; i++)
{
Text1.Text += dtReader.GetValue(i).ToString();
}
}

VB.NET
Text1.Text = ""
Dim dtReader As DataTableReader = dt.CreateDataReader()
While dtReader.Read()
For i As Integer = 0 To dtReader.FieldCount - 1
Text1.Text += dtReader.GetValue(i).ToString()
Next
End While

XML Serializing .10


C#

EmpDataSet.WriteXml("Employee.xml");

VB.NET

EmpDataSet.WriteXml("Employee.xml")

:
C#
EmpDataSet.ReadXml("Employee.xml");

502

ADO.net

VB.NET
EmpDataSet.ReadXml("Employee.xml")

: Employee.xml

XML
<?xml version="1.0" standalone="yes"?>
<Employee_XML>
<Employee>
<ID>1</ID>
<Name>Ahmed Gamal</Name>
<Age>22</Age>
</Employee>
<Employee>
<ID>2</ID>
<Name>Ahmed Essawy</Name>
<Age>23</Age>
</Employee>
</Employee_XML>

DataGrid .11

: DataGridView

DataGridView .13 .17

503

A
ADO.net

Choose
e DataSource

New DataSource DataBase
D
e
.

Con DataSSource
nnectionStrring

***
Connection
C
nString

.Data Source

DataGri
.14 .17 idView

504

ADO.net


= dataGrid AddQuery
:

.15 .17 .
:

505

ADO.net

. .16 .17

DataAdapter .12
: DataAdapter
C#

string connectionString = @"Data Source=AHMED-PC\SQLEXPRESS;Initial


Catalog=Employee;Integrated Security=True;Pooling=False";
DataSet ds = new DataSet("Employee");
SqlDataAdapter dAdapt = new SqlDataAdapter("Select * From Employee_info",
connectionString);
dAdapt.Fill(ds, "Employee_info");

VB.NET
Dim connectionString As String = "Data Source=AHMED-PC\SQLEXPRESS;Initial
Catalog=Employee;Integrated Security=True;Pooling=False"
Dim ds As New DataSet("Employee")
Dim dAdapt As New SqlDataAdapter("Select * From Employee_info",
connectionString)
dAdapt.Fill(ds, "Employee_info")

506

507

18
LINQ

508

509

LINQ

LINQ .

.1
ADO.net
Language Integrated Query LINQ


XMLFile
.
LINQ :
LINQtoSQL -1
LINQtoXML -2
LINQtoObjects -3
Array
LINQ :

C#
from d in developers
"where d.Language == "C#
;select d.Name

SQL
"SELECT name FROM developers WHERE language="C#

510

LINQ

C#
public class Developer
{
public string Name;
public string Language;
}
Developer[] developers = new Developer[]
{ new Developer { Name = " Ahmed", Language="C#" },
new Developer { Name="Khaled", Language="Java" },
new Developer { Name="Ali", Language="C++"}
};

VB.NET

Public Class Developer


Public Name As String
Public Language As String
End Class
Dim developers As Developer() = new With { New Developer { .Name = " Ahmed",
.Language="C#" }, New Developer { .Name="Khaled", .Language="Java", New
Developer { .Name="Ali", .Languag="C++"} }

C#
IEnumerable<string> LINQresult = from d in developers
where d.Language == "C#"
select d.Name;

VB.NET
Dim LINQresult As IEnumerable(Of String) = From d In developers _
Where (d.Language = "C#") _
Select d.Name

C#

foreach (string s in LINQresult)


{
MessageBox.Show(s);
}

VB.NET
For Each s As String In LINQresult
MessageBox.Show(s)
Next

511

LINQ

C#
IEnumerable<string> LINQresult = from d in developers
;select d.Name

VB.NET
_ )(Dim LINQresult As IEnumerable(Of String) = From d In developers
Select d.Name

.net :

C#
IEnumerable<string> LINQresult = from d in developers
where d.Name.Length > 3
orderby d.Name
;select d.Name

VB.NET
_ Dim LINQresult As IEnumerable(Of String) = From d In developers
_ )Where (d.Name.Length > 3
_ )Order By (d.Name
Select d.Name


Where

From

Select

LINQ Select
IntelliSense
Select From
.
:

512

LINQ

from id in source
{
from id in source /
| ]Join id in source on expr equals expr [into id
| Let id = expr
| Where condition
]Orderby ordering, ordering, ... [Ascending | Descending
}


...

.2 LINQ
LINQ 51
.


Aggregate
:
;)int product = ints.Aggregate(1, (a, b) => a * b

ints .

All
:
;)bool isMarried = employees.All(emp => emp.statues == 1

Any
:
> = bool isMarried=employees.Any(emp
;)employees.statues==1

Average :
;)(double avg = ints.Average

ints .

513

LINQ

Cast :
;)(>var newString = ints.Cast<string

ints .
query1
Concat
query2 :
;)var result = query1.Concat(query2


Contains
:
;)bool find=employees.Contains(new employee(Mohammed

Query .
Count :
;)(int count = employees.Count

DefualtIfEmpty :
;)var result = ints.DefualtIfEmpty(100


"" null .Object

:
Distinct
;)(var pure = query.Distinct

:
ElementAt
;)Employee newemp = query.ElementAt(4

ElementAtOrDef 4

ualt

:
;)Employee newemp = query.ElementAtOrDefualt(4

:
Empty
;)(>var newresult = System.Query.Sequence.Empty<employee

EqualAll :
;)bool iseuql = query1.EqualAll(query2

Except
:
;)var result = query1.Except(query2

...

514

LINQ

First :
;)(Employee firstone = employees.First

*** .

:
Employee firstone = employees.First(emp => emp.ismarried
;)== 1

FirstOrDefault
:
>= Employee firstone = employees.FirstOrDefault(emp
;)emp.ismarried == 1

Fold Aggergate
GroupBy GroupBy
SqlStatement :
;)var newGroup = employees.GroupBy(emp => emp.Country

key .
GroupJoin . Join
Intersect :
;)var inter = query1.Intersect(query2

Join inner join . SqlStatements


Last First :
;)(Employee lastone=employees.Last
>= Employee lastone=employees.Last(emp
;)emp.Country==Egypt

LastOrDefault
:
>= Employee firstone = employees.LastOrDefault(emp
;)emp.ismarried == 1

LongCount Count Long :


;)(long empCount = employees.LongCount

Max :
;)(int num = ints.Max

515

LINQ

Min :
;)(int num = ints.Min



OfType int
:

;)(>var newResult = list.OfType<int

OrderyBy ) ( :
;)var orderlist = employees.OrderBy(emp => emp.Age

OrderyByDescen :
>= employees.OrderyByDescending(emp
ding
Range

= var orderlist
;)emp.ID

:
;)var newlist = System.Query.Sequence.Range(1, 5

" "1 :
Repeat
;)var list = System.Query.Sequence.Repeat(1, 5

Reverse :
;)(var revList = list.Reverse

Select :
;)var newSelect = list.Select(emp => emp


var newSelect = employees.Select(emp => new { emp.Name,
;)} emp.Age

SelectMany Group
SelectMany :
;)var newSelect = groupedlist.Select(l => l

Single :
;)(var result = query.Single

SingleOrDefaul
t:
;)(var result = query.SingleOrDefault

10
Skip
:
;)var newResult = query1.Skip(10

516

LINQ

SkipWhile
: 100

;)var newResult = query1.SkipWhile(x => x < 100

Sum :
;)(Double sum = ints.Sum

Take :
;)var top = ints.Take(3


TakeWhile
: 100
;)var top = ints.TakeWhile(x => x < 100


ThenBy
:

var orderemp=employees.OrderBy(emp => emp.Age ThenBy emp
;)=> emp.Salary

ThenByDesecndi :
orderemp=employees.OrderBy(emp => emp.Age
ng

var
;)ThenByDesecnding emp => emp.Salary

ToArray :
;)(Employee[] emps = query.ToArray

ToDictonary .
ToList >List<T
ToLookup >V
ToSequence Sequence
Lookup<K,

.
Union
:
;)var result = query1.Union(query2

Where .
.1 .18 .LINQ

517

LINQ

) (LINQ
http://www.vb4arab.com/vb/uploaded/2730/11202261862.pdf

:

ImplicitlyTypedLocalVariables :

C#
var subset = from i in numbers
where i < 10
;select i

* :LambdaExpressions: LINQ

Lambda Expressions
LINQ .

LINQToDataSet .3
DataSet
LINQ .
DataSet DataTable

:

518

LINQ

C#
DataSet ds = LoadDataSetSomeway();
DataTable employees = ds.Tables["Employee"];
var query =
from emp in employees.AsEnumerable()
where emp.Field<long>("Age").Year >= 40
select emp;

VB.NET
Dim ds As DataSet = LoadDataSetSomeway()
Dim employees As DataTable = ds.Tables("Employee")
Dim query = From emp In employees.AsEnumerable() _
Where emp.Field(Of Long)("Age").Year >= 40 _
Select emp

LINQToXML .4
XML LINQ XML
XML
.
: XML

519

LINQ

XML
<?xml version="1.0"?>
<Items>
<Item Number="122">
<ItemName>Item1</ItemName>
<Quantity>100</Quantity>
<Price>23</Price>
</Item>
<Item Number="123">
<ItemName>Item2</ItemName>
<Quantity>10</Quantity>
<Price>14.5</Price>
</Item>
<Item Number="124">
<ItemName>Item3</ItemName>
<Quantity>31</Quantity>
<Price>1000</Price>
</Item>
<Item Number="125">
<ItemName>Item4</ItemName>
<Quantity>22</Quantity>
<Price>97</Price>
</Item>
</Items>

: XML Load

C#

XElement purchaseOrder = XElement.Load("Items.xml", LoadOptions.SetBaseUri |


LoadOptions.SetLineInfo);

VB.NET
Dim purchaseOrder As XElement = XElement.Load("Items.xml",
LoadOptions.SetBaseUri Or LoadOptions.SetLineInfo)

C#
var newSearch

520

= from item in Items.<Item>


select item.@Number;

LINQ

VB.NET
Dim newSearch = From item In Items.<Item>() _
Select item.@Number

100

C#
var newSearch

= from item In Items.<Item>


where item.<Price>.Value > 100
select item.@Number

VB.NET
Dim newSearch = From item In Items.<Item>() _
Where (item.<Price>.Value > 100) _
Select item.@Number

LINQToSQL .5
SQL Server LINQ
.




: 30
C#

var query = from c in Employee


where c.Age > 30 && c.Country == "Egypt"
select new { c.Name, c.GraduationDate };

VB.NET

Dim query = From c In Employee _


Where (c.Age > 30) AndAlso c.Country = "Egypt" _
Select New With {c.Name, c.GraduationDate}

521

LINQ

StoredProcedures
Attributes Procedure
)
: (

C#
var c = db.ProceduresName("Egypt");

VB.NET
Dim c = db.ProceduresName("Egypt")



.CompiledQuery LINQ
CompiledQuery
: Compile CompiledQuery.Compile
C#

var c = CompiledQuery.Compile((DataContext context, string CountryName, int


age) =>
from c in Employee
where c.Age > age && c.Country == CountryName
select new { c.CustomerID, c.CompanyName, c.City });

VB.NET

Dim c = CompiledQuery.Compile(Function(context As DataContext, CountryName As


String, age As Integer) From c In Employee _
Where c.Age > age AndAlso c.Country = CountryName _
Select New With {c.CustomerID, c.CompanyName, c.City})


: Compile

522

LINQ

C#
foreach (var row in query(dc, "Egypt", 22))
{
}
foreach (var row in query(dc, "USA", 28))
{
}
foreach (var row in query(dc, "Saudi", 38))
{
}

VB.NET
For Each row As var In query(dc, "Egypt", 22)
Next
For Each row As var In query(dc, "USA", 28)
Next
For Each row As var In query(dc, "Saudi", 38)
Next

SQL

SELECT SUM( emp.salary ) AS TotalSalary FROM Employee emp JOIN Department dem
ON emp.DepartmentID = dep.ID GROUP BY dep.ID

C#

: LINQ

var c = from emp in db.Employee


join dep in db.Department
on emp.DepartmentID equals dep.ID
into TotalSalary
select TotalSalary.Sum(emp => emp.Salary);

VB.NET
Dim c = From emp In db.Employee() _
Join dep In db.Department _
On emp.DepartmentID Equals dep.ID _
Into(TotalSalary) _
Select TotalSalary.Sum( emp => emp.Salary )

523

LINQ

LINQ


: LINQ SQL PIVOT
: - C#

var query = db.ExecuteQuery<EmployeeInfo>(@" With EmployeeHierarchy


(EmployeeID, LastName, FirstName, ReportsTo, HierachyLevel)
AS
( SELECT EmployeeID, LastName, ForstName, ReportsTo, 1 as HierarchyLevel
FROM Employees
WHERE ReportsTo IS NULL
UNION ALL
SELECT e.EmployeeID, e.LastName, e.FirstName, e.ReportsTo,
eh.HierarchyLevel + 1 AS HierarchyLevel
FROM Emplyees e
INNER JOIN EmployeeHierarchy eh
ON e.ReportsTo = eh.EmplyeeID
)
SELECT *
FROM EmployeeHierarchy
ORDER BY HierarvhyLevel, LastName, FirstName");

VB.NET
Dim query = db.ExecuteQuery(Of EmployeeInfo)(" With EmployeeHierarchy
(EmployeeID, LastName, FirstName, ReportsTo, HierachyLevel)
AS
( SELECT EmployeeID, LastName, ForstName, ReportsTo, 1 as HierarchyLevel
FROM Employees
WHERE ReportsTo IS NULL
UNION ALL
SELECT e.EmployeeID, e.LastName, e.FirstName, e.ReportsTo,
eh.HierarchyLevel + 1 AS HierarchyLevel
FROM Emplyees e
INNER JOIN EmployeeHierarchy eh
ON e.ReportsTo = eh.EmplyeeID
)
SELECT *
FROM EmployeeHierarchy
ORDER BY HierarvhyLevel, LastName, FirstName")

524

LINQ

LINQ Inseret

C#

var NewEmp = new Employee { FirstName = "Ahmed", Age = 25, Country="Egypt"};


db.Employee.Add( NewEmp );

VB.NET
Dim NewEmp = New With {.FirstName = "Ahmed", .Age = 25, .Country = "Egypt"}
db.Employee.Add(NewEmp)

. 25

Update

C#
var EditEmp = db.Employee.Single (c => c.Country == "Egypt");
EditEmp.Age = 30;

VB.NET
Dim EditEmp = db.Employee.Single(Function(c) c.Country = "Egypt")
EditEmp.Age = 30

. 30

Delete

C#
var deleteEmp = db.Employee.Single(c => c.Age > 50);
db.Employee.Remove(deleteEmp);

VB.NET
Dim deleteEmp = db.Employee.Single(Function(c) c.Age > 50)
db.Employee.Remove(deleteEmp)

. 50

525

LINQ

SubmitChanges .6

)( db.SubmitChanges .

LINQ

ChangeConflictExeption
:

C#
try
{
;)(Db2.SubmitChanges
;break
}
)catch (ChangeConflictExeption ex
{
;)MessageBox.Show(ex.Message
;)Db2.Refresh(somequery, RefreshMode.KeepChanges
}

VB.NET
Try
)(Db2.SubmitChanges
Exit Try
Catch ex As ChangeConflictExeption
)MessageBox.Show(ex.Message
)Db2.Refresh(somequery, RefreshMode.KeepChanges
End Try

Refresh
.
SubmitChanges
:

526

LINQ

C#
Db.SubmitChanges(ConflictMode.FailOnFirstConflict);
Db.SubmitChanges(ConflictMode.ContinueOnConflict);

VB.NET
Db.SubmitChanges(ConflictMode.FailOnFirstConflict)
Db.SubmitChanges(ConflictMode.ContinueOnConflict)

. ConflictMode

LinqToSQL .7

LINQ TO SQL Classes 2008


:

. .1 .18

527

LINQ

ServerExplorer
:

.2 .18 .

- DataAccessLayer
:
-

C#
;)partial void InsertEmployee_info(Employee_info instance
;)partial void UpdateEmployee_info(Employee_info instance
;)partial void DeleteEmployee_info(Employee_info instance

528

LINQ

VB.NET
Partial Private Sub InsertEmployee_info(ByVal instance As Employee_info)
End Sub
Partial Private Sub UpdateEmployee_info(ByVal instance As Employee_info)
End Sub
Partial Private Sub DeleteEmployee_info(ByVal instance As Employee_info)
End Sub

LINQ LINQ
:

http://www.vbcoffee.net/SamerSelo/linqcourseebook.pdf

529

530

19
WWF

531

532

WWF

.net3.0 WindowsWorkflowFoundation
WWF API
workflow .

viusalstudio workflows .
WF Workflow
BusinessProcess
.

: Check
.
BusinessProcess tasks
.BusinessProcess
Workflow
trace
.

.1 WF
WF visio
WF . WF
namespacesassemblies .net

WorkflowActivity

533

WWF

Activities
if else Delay Invoke
:

.1.1 WF
Workflow :EmptyWorkflow

.1 .19 .Workflow

EmptyWorkflow

:

534

WWF

Sequential Workflow .2.1


Diagrams UML

:

.2 .19 Sequential Workflows

State Machine Workflow .3.1


:

535

WWF

.3 .19 StateMachine Workflow

536

WWF

.2 WWF


.
Sequential Workflow Console Application
:

.4 .19 Sequential Workflow

Activity

Code

:codeActivity1_ExecuteCode

537

WWF

C#
private void codeActivity1_ExecuteCode(object sender, EventArgs e)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("***** First WPF Example *****\n\n");
Console.ForegroundColor = ConsoleColor.White;
}

VB.NET
Private Sub codeActivity1_ExecuteCode(ByVal sender As Object, ByVal e As
EventArgs)
Console.ForegroundColor = ConsoleColor.Yellow

Console.WriteLine("***** First WPF Example *****" & Chr(10) & "" & Chr(10)
& "")
Console.ForegroundColor = ConsoleColor.White
End Sub


Condition While Loop
:
Loop Boolean function
.true false
. declarativerulecondition
true AskAgain
. false
- Condition
:

538

WWF

C#

While Activity .5 .19


:

public string Password { get; set; }


private void AskAgain(object sender, ConditionalEventArgs e)
{
Console.Write("Enter Password: ");
Password = Console.ReadLine();
if (Password == "Ahmed Gamal")
e.Result = false;
else
e.Result = true;
}

VB.NET

Public Property Password() As String


Get
End Get
Set(ByVal value As String)
End Set
End Property
Private Sub AskAgain(ByVal sender As Object, ByVal e As ConditionalEventArgs)
Console.Write("Enter Password: ")
Password = Console.ReadLine()
If Password = "Ahmed Gamal" Then
e.Result = False
Else
e.Result = True
End If
End Sub

Activity
: Activity ThisPasswordisWrong
C#

private void codeActivity2_ExecuteCode(object sender, EventArgs e)


{
Console.WriteLine("This Password is Wrong...");
}

VB.NET
Private Sub codeActivity2_ExecuteCode(ByVal sender As Object, ByVal e As
EventArgs)
Console.WriteLine("This Password is Wrong...")
End Sub

539

WWF

Sequential WF :

.6 .19 Sequential Workflow


:

540

WWF

.7 .19
*** WF

trace .Debug

WF Code Library .3
WF ASP.net Windows
Forms Console .dll
.

541

542

20
WCF

543

WCF

.net

Winsock . Sockets
WCF WebServices .

WebService .1
WebService .net
ASP.net )
(Interface Interface
XML
Request httpprotocol
.





.
XML
.


IIS Windows2000 .

544

WCF

.1.1 WebService .net


WebService
) ( ) ( :
result = (input-32) * 5/9
NewProject ASP.netWebService
:
localhost
http://localhost/ConvertWebService
WebConfig ASP.net
Global.asax .Service1.asmx
Service1 WebService
..
ConvertWS
.net
.
WebService TextBox
:
VB.net

C#
])" "=[WebMethod(Description
)public decimal Convert(decimal degree
{
;decimal result
;result = (degree - 32) * 5 / 9
;return result
}

VB.NET
_ >)" "=<WebMethod(Description:
Function Convert(ByVal degree As Decimal) As Decimal
Dim result As Double
result = (degree - 32) * 5 / 9
Return result
End Function

545

WCF

IIS .
InternetExplorer :
http://localhost/ConvertWebService/ConvertSW.asmx
.

.
WebMethod
:
: BufferResponse -1 buffering
True. False
: CacheDuration -2 Cash

: EnableSession -3 Session .

.2 .1 WebService



WebService
. ConvertSW
Project. AddWebRefernce
ConvertSW.asmx
ViusalStudio .
:

546

WCF

C#
;)(LocalHost.ConvertSW conv = new LocalHost.ConvertSW

VB.NET
)(Dim conv As New LocalHost.ConvertSW

Textbox1 Label1


conv :

C#
;))Label1.Text = Convert.toString(conv.Convert(textBox1.text

VB.NET
))Label1.Text = Convert.toString(conv.Convert(textBox1.text


Update
UpdateWebReference.

.3.1

Web Service
:

http://www.webservicex.net/WCF/

70

http://www.webservicex.net/ValidateEmail.asmx

547

WCF


:
IsValidEmail True .False
Web Refernce


MessageBox .
:

C#
net.webservicex.www.ValidateEmail x = new
;)(WindowsApplication1.net.webservicex.www.ValidateEmail
;)bool r = x.IsValidEmail(textBox1.Text
)if (r
;)" "(MessageBox.Show
else
;)" "(MessageBox.Show

VB.NET
Dim x As net.webservicex.www.ValidateEmail = New
)(WindowsApplication1.net.webservicex.www.ValidateEmail
)Dim r As Boolean = x.IsValidEmail(textBox1.Text
If r Then
)" "(MessageBox.Show
Else
)" "(MessageBox.Show
End If

http://www.webservicex.net/globalweather.asmx


:
GetCitiesByCountry

548

WCF
C#

net.webservicex.www1.GlobalWeather m = new
;)(WindowsApplication1.net.webservicex.www1.GlobalWeather
;))"MessageBox.Show(m.GetCitiesByCountry("Egypt

VB.NET
)"MessageBox.Show("Welcome
Dim m As Net.webservicex.www1.GlobalWeather = New
)(WindowsApplication1.net.webservicex.www1.GlobalWeather
))"MessageBox.Show(m.GetCitiesByCountry("Egypt

TextBox
...
:
GetWeather

C#
net.webservicex.www1.GlobalWeather m = new
;)(WindowsApplication1.net.webservicex.www1.GlobalWeather
;))"MessageBox.Show(m.GetWeather("Asyut", "Egypt

VB.NET
Dim m As net.webservicex.www1.GlobalWeather = New
)(WindowsApplication1.net.webservicex.www1.GlobalWeather
))"MessageBox.Show(m.GetWeather("Asyut", "Egypt



.


. .
RSS

549

WCF

ISPN
.

.2 WCF
.NET 3.0 Windows
CommunicationFoundation WCF API's
webservicesremoteaccess.

x y x=y
...
.

API's
MSMQ DCOM

.net

System.Runtime.Remoting Web XML


Services

NamedPipes,Sockets,
andP2P .net
-
.
.net WCF
.

550

WCF

.1.2 WCF
VisualStudio2008 WCF WCFService
:
Library

.1 .20 .WCF
WCF RSS WWF
WebSite WCFService
.
assembly:
WCFServiceWCFServicehost -

551

WCF

WCFclient :
:Address . :Binding . :Contract - .WCF

.2.2 Address

WCF :

scheme://<MachineName>[:Port]/Path

scheme
MachineName
Port
Path Services .
:

net.tcp://localhost:8080/MyWCFService

:
WCFLiabrary :IService1.cs

C#
][OperationContract
;)int Add(int x, int y

VB.NET
_ >)(<OperationContract
Private Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
End Function

Service1.cs :

552

WCF

C#
)public int Add(int x, int y
{
;return x + y
}

VB.NET
Public Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
Return x + y
End Function


Run WCFTestClient
Invoke .
WebServices
:

.2 .20 .WCF
:

http://msdn.microsoft.com/en-us/library/bb310550.aspx

553

554

21

555

556

.1 Debugging -


Debug .

BreakPoints

Visual Studio
F11
. F5
BreakPoint F9
:

557

.1 .21 .BreakPoint




.F11

:

558

.2 .21 .

559



.
... Double
:

Debug

.

:

.3 .21 .
:

560

.4 .21 .
Add Watch
:

.5 .21 .
:

.6 .21 .Watch

561

.2

Publish
Setup Build
. Publish
C:\ahmed .
. CDDVD
.
. Finish .
Publish

562

.7 .21 / .
Setup ProgramFiles .
installshield setup factory Setup
NewProject
:

563

.8 .21 .

C#vsVB.net .3
C# Vb.net
..net
.
.net C#

Syntax
.net VB.net C# VB
.

564

C# VB.net
...
: ;
: :

C#
;int x
;)(ClassName x = new ClassName

VB.NET
Dim X As Integer
)(Dim X As ClassName = New ClassName

: VB.net = C# == != >< .

:
: VB.net End
VB.NET
if x=1 Then
End if

C# :

C#
)if (x == 1
{
}

C#

;using System
namespace MyNameSpace
{
class HelloWorld
{
)static void Main(string[] args
{
;)"System.Console.WriteLine("HelloWorld
}
}
}

565

VB.NET
Imports System
Namespace MyNameSpace
Class HelloWorld
'Entry point which delegates to C-style main
Private Function
Public Overloads Shared Sub Main()
Main(System.Environment.GetCommandLineArgs())
End Sub
Overloads Shared Sub Main(ByVal args() As String)
System.Console.WriteLine("Hello World")
End Sub 'Main
End Class 'HelloWorld
End Namespace 'MyNameSpace

#C And,Or,Not,OrElse .net . ! || &&


. + C# VB.net & : VB.net ElseIf #C elseif : : C# End :

C#
for (int i = 2; i <= 10; i += 2)
{
System.Console.WriteLine(i);
System.Console.WriteLine(i*10);
}

:
C#

for (int i = 2; i <= 10; i += 2)


System.Console.WriteLine(i);

:
VB.net
VB.NET
For c = 2 To 10 Step 2
System.Console.WriteLine(c)
Next

566

While for each .


)( . VB.net
* : ][

C#
;} int[] nums = { 1, 2, 3
)for (int i = 0; i < nums.Length; i++
;)]Console.WriteLine(nums[i

VB.NET
}Dim nums() As Integer = {1, 2, 3
For i As Integer = 0 To nums.Length - 1
))Console.WriteLine(nums(i
Next

Comment VB.net

/* */

C# XML

Comments .
Mod VB.net .
#C %
VB.net BitwiseOperations Assignment C#
.
- -

.
casesensitive VB.net Ahmed ahmed
Basic
.

- VB.net -
optionalparameters VB.net . #C
with VB.net . #C

567

Catch ... When VB.net VB.net Compile BackGround .

- C# : -
#C unsignedtypes VB.net
.
#C VB.net
unsafe unmaneged code Pointers
imageprocessing .
#C C++ Low
LevelCode .
increment decrement VB.net :

VB.NET
A=A+1
A-=1

C# :

C#
A++
A

sizeof C# .VB.net
.

568

:
VB6.0 VB.net C/C++/Java

#C
C# .
:

http://support.microsoft.com/kb/308470

.4 Mono
VM VM

.
Microsoft VisualBasic C# MFC
.

Mono .
Mono .net 2008
.net2.0 ASP.net
-
- :

http://www.mono-project.com/plans

569

Download Mono
Mono .
Command Line Mono
:
:mcs/gmcs
:Vbnc
:ilasm/ilasm2 CIL
- Visual
StudioCommandLine gmcs mcs gmcs
. .net2.0
sample.cs C# Command Line
Mono :

Shell
gmcs/target:library/out:Sample.dllSample.cs

!
build exe
...
mono
MonoDevelop : VISUALSTUDIO

570

.9 .21 c# MonoDevelop .

.5 .net

PocketPC

Windows Mobile

571

Windows CE 2003
.
Hard Disk
RAM
ROM
.

PocketPC .net

) (


.


.
-1 . VisualStudio.net
-2 VB .
-3 SmartDevice PocketPC2003 Smartphone2003
WindowsCE5.0 .
-4 . DeviceApplication
-5 Button

C#
;)"MessageBox.Show("Welcome...

572

VB.NET
)"MessageBox.Show("Welcome...

-6 F5 deploy
PC .
- 7 exe
.netcompactframework
. PocketPC
-8


:

C#
;SystemSettings.ScreenOrientation = ScreenOrientation.Angle90

VB.NET
;SystemSettings.ScreenOrientation = ScreenOrientation.Angle90

: TouchKeyboard

C#
;InputPanel1.Enabled = true

VB.NET
InputPanel1.Enabled = True

Reset : coredll.dll

573

C#

private int CTL_CODE(int DeviceType, int Func, int Method, int Access)
{
return (DeviceType << 16) | (Access << 14) | (Func << 2) | Method;
}
private int ResetPocketPC()
{
const int FILE_DEVICE_HAL = 257;
const int METHOD_BUFFERED = 0;
const int FILE_ANY_ACCESS = 0;
int bytesReturned = 0;
int IOCTL_HAL_REBOOT;
IOCTL_HAL_REBOOT = CTL_CODE(FILE_DEVICE_HAL, 15, METHOD_BUFFERED,
FILE_ANY_ACCESS);
return KernelIoControl(IOCTL_HAL_REBOOT, IntPtr.Zero, 0, IntPtr.Zero, 0,
bytesReturned);
}

VB.NET

Private Function CTL_CODE(ByVal DeviceType As Integer, ByVal Func As Integer,


ByVal Method As Integer, ByVal Access As Integer) As Integer
Return (DeviceType << 16) Or (Access << 14) Or (Func << 2) Or Method
End Function
Private Function ResetPocketPC() As Integer
Const FILE_DEVICE_HAL As Integer = &H101
Const METHOD_BUFFERED As Integer = 0
Const FILE_ANY_ACCESS As Integer = 0
Dim bytesReturned As Integer = 0
Dim IOCTL_HAL_REBOOT As Integer
IOCTL_HAL_REBOOT = CTL_CODE(FILE_DEVICE_HAL, 15, METHOD_BUFFERED,
FILE_ANY_ACCESS)
Return KernelIoControl(IOCTL_HAL_REBOOT, IntPtr.Zero, 0, IntPtr.Zero, 0,
bytesReturned)
End Function

.net
PocketPC

. SQLServerCE XML
:

http://msdn2.microsoft.com/en-us/library/aa458721.aspx

574

575

576

22

ASP.NET

577

578

ASP.net

.1
ConsoleDesktop Applications


webservice ASP.net serversidelanguages
:
: HTML .
: Scripts JavaScript VBScript
.
:
.
:

HTML

.

.

579

ASP.net

:
http://
http DomainNameServer
DNS DNS Physical
IP DNS :

.1 .22 IP .DNS
IP port - 80
. httpRequest
static
dynamic
. httpResponse
- http.

ClientSideWebSites
HTML
:

www.html4arab.com

580

ASP.net

FrontPage DreamWaver
HTML .
Java vbscript HTML
Forms
vbscript : -

http://ahmedgamal-technical.blogspot.com/2008/08/vbscript.html

: javascript

http://www.w3schools.com/JS/default.asp

...

WebApplication WebService

.

: IIS
ASP ASP.net ASP.net
.
setup visual studio IIS
WebDev.WebServer.exe IIS
setup Control Panel
Notepad

581

ASP.net

Add And Remove Programmes Add


WindowsCompomnent InternetInforamtionServices .IIS
** .



Notepad index.html
:

HTML
><html
><head
><title>My First Pgae</title
></head
><body
><center><img src="http://l.yimg.com/a/i/ww/beta/y3.gif"></centeR
><br
><font color=red size=3>Yahoo!</font
><br
><a href="http://www.yahoo.com">Link Here</a
></body
></html

.
:

582

ASP.net

HTML
<html>
<head>
<title>My First Pgae</title>
</head>
<body>
<h2>Welcome !!</h2>
<br>
<form name="form1">
<table border=0>
<tr>
<td>Name</td>
<td>
<input type=text name=textname size=10>
</td>
</tr>
<tr>
<td>Password</td>
<td><input type=password name=textpass size=10><td>
</tr>
</table>
<br>
<input name="button1" type=button value="do anything"();">
&nbsp;&nbsp;&nbsp;
<input type=reset value="Clear">
</form>
</body>
</html>


Button1
:

HTML
<input name="button1" type=button value="do anything" onClick="doCheck();">

HTML

: Script

<script language="javascript">
function doCheck()
{
if(form1.textname.value!="" || form1.textpass.value!="")
{
alert(form1.textname.value);
document.write(form1.textpass.value);
}
else
alert("enter data first !");
}
</script>

583

ASP.net

VisualStudio
ASP.net Visual Studio
Website ASP.netWebSite

.2 .22 ) (ASP.NET
:

584

ASP.net

.3 .22 HTML .

HTML ASP.net
Button :

585

ASP.net

.4 .22 HTML ASP.NET


:

... . ASP.net

.2 ASP.net
VisualStudio
.

586

ASP.net

ASP.net
Standerd TextBox Label Button
:

C#
;Label1.Text= TextBox1.Text

VB.NET
Label1.Text= TextBox1.Text

... ASP.net.


HTML HTML
Submit
Label
Ahmed
HTML :

HTML
><p
><span id="Label1">Ahmed</span
></p
><p
><input name="TextBox1" type="text" value="Ahmed" id="TextBox1" /
></p
><p
><input type="submit" name="Button1" value="Button" id="Button1" /
></p

Label1
.

587

ASP.net

.
Form POST GET
Form GET
:

HTML
>"<form id="form2" runat="server" method="get

.5 .22 GET Method .



POST .

.

588

ASP.net

CodeBehind
ASP ASP.net
:
ASPClassic
ASP.NET
<%
v_Id = Request.QueryString("id")
Response.Write("<form action=test7.asp?id=" & v_id & " method=post>")
Response.Write("<font color=red><b><center>Write your
C.V.</center></b></font><br>")
%>
<table>
<tr>
<td>Computer Skills :</td>
<td><input type=text name=v_cs size=30></td>
</tr>
<tr>
<td>Characteristics :</td>
<td><input type=text name=v_char size=30></td>
</tr>
<tr>
<td>Interest's :</td>
<td><input type=text name= v_inter size=30></td>
</tr>
<tr>
<td>Language Skills :</td>
<td><input type=text name=v_ls size=30></td>
</tr>
<tr>
<td>Education :</td>
<td><textarea name=v_edu cols =30 rows=6>write your Study Field
here</textarea></td>
</tr>
<tr>
<td>Experince :</td>
<td><textarea name=v_exp cols =30 rows=6>write your Experiences
here</textarea></td>
</tr>
</table>
<br>
<hr width=75%>
<center>
<font color=red><b><center>Join Demand</center></b></font><br>
<textarea name=v_Join cols=40 rows=9 WRAP=physical></textarea>
<br><br>
<input type=submit value= Continue>
<input type=reset value=Erase>
</center>
</form>

589

A
ASP.net



*.css

ASP.nett
: *.aspxx






A
ASP
aspx



*.css



.
-
.
VisualStudio


Deeploy

.

ASP
P.net


WebssiteDirectory



-

:-

590

ASP.net

: App_Browsers
.
: App_Code Classes .
: App_Data .
: App_GlobalResources . *.resx
: App_Themes .
: App_WebReferences Proxy Web Service
.
: Bin *.dll .

CompilationCycle
SingleFile Class
System.Web.UI.Page _aspx.

.6 .22 .ASP.Net

591

ASP.net

Mode CodeBehind
)(InitializeComponent
Compile CS + ASPX
System.Web.UI.Page .

.7 .22 .ASP.NET
*** ...

592

ASP.net

.3 System.Web.UI.Page
:

Application
Cache
IsPostBack Load
Load Submit
MasterPageFile
Request HttpRquest
Response HttpResponse
Server

HttpServerUtility
Session Session

Theme - -
.1 .22 .System.Web

.1.3 Request
Request
.Request
: ) (
.Request

593

ASP.net

Action
:
GetPost

HTML
>"<form name="form1" id="form1" action="Process.asp" method = "GET
...
></form

:
.net

HTML
>"<form id="form1" runat="server


.POST
ASP.net HttpRequest
System.Web.UI.Page.Request
:
-

ApplicationPath
Browser

Cookies
HttpMethod SetGet
Form
Post
QueryString
Get URL

594

ASP.net


IsSecureConnection Http
RawUrl URL
ServerVariables
UserHostAddress IP
UserHostName
)( MapPath

)( SaveAs http
.2 .22 Request
...Request

Form
:Post

C#
;)"firstName = Request.Form("txtFirstName

VB.NET
)"firstName = Request.Form("txtFirstName

GET :

C#
;]"firstName = Request.QueryString["txtFirstName

595

ASP.net

VB.NET
firstName = Request.QueryString("txtFirstName")

ID
.

C#
string theInfo = "";
string isAOL = string.Format("Is AOL? {0} <br/>", Request.Browser.AOL);
string isActivex = string.Format("Support ActiveX? {0} <br/>",
Request.Browser.ActiveXControls);
string isBeta = string.Format("Is Beta? {0} <br/>", Request.Browser.Beta);
string isJava = string.Format("Support Java Applets? {0} </br>",
Request.Browser.JavaApplets);
string isCookies = string.Format("Support Cookies? {0} <br/>",
Request.Browser.Cookies);
string isVB = string.Format("Support VBScript? {0} <br/>",
Request.Browser.VBScript);

VB.NET

Dim theInfo As String = ""


Dim isAOL As String = String.Format("Is AOL? {0} <br/>", Request.Browser.AOL)
Dim isActivex As String = String.Format("Support ActiveX? {0} <br/>",
Request.Browser.ActiveXControls)
Dim isBeta As String = String.Format("Is Beta? {0} <br/>",
Request.Browser.Beta)
Dim isJava As String = String.Format("Support Java Applets? {0} </br>",
Request.Browser.JavaApplets)
Dim isCookies As String = String.Format("Support Cookies? {0} <br/>",
Request.Browser.Cookies)

Response .2.3
Request

:

596

ASP.net

ContentEncoding
Cache Cookies Request
IsClientConnected
)( Clear BodyHeaders
)( End
)( Flush **
**
)( Redirect URL
)( Write
.3 .22 Response
:Write

C#
;)">Response.Write("<u>This is javascript code</u
;)">Response.Write("<script>alert('hiiiii');</script

VB.NET
)">Response.Write("<u>This is javascript code</u
)">Response.Write("<script>alert('hiiiii');</script

597

ASP.net

.4 ASP.net
ASP.net HTML *.aspx

.

Event .

AutoPostBack

Text Box Check Box & Radio Buttons
ListBoxComboBox .false

.1.4

System.Web.UI.Control
:

Controls
)( HasControls
ID - -
Page
Parent
Visible
.4 .22 Control

598

ASP.net

System.Web.UI.WebControls.WebControl
:

BackColor

BorderColor
BorderStyle
BorderWidth
Enabled
CssClass class styles
Font
ForeColor
Height
Width
TabIndex Tab
ToolTip Tips
.5 .22 WebControl

599

ASP.net

:
Controls Collection

: HasControls()

C#
string Information = "";
if (myPanel.HasControls())
{
foreach (Control c in PanelName.Controls)
{
if (!object.ReferenceEquals(c.GetType(),
typeof(System.Web.UI.LiteralControl)))
{
Information += string.Format("Control Name: {0} <br/>",
c.ToString());
Information += string.Format("ID: {0} <br/>", c.ID);
Information += string.Format("Control Visible: {0} <br/>",
c.Visible);
Information += string.Format("ViewState: {0} <br/>",
c.EnableViewState);
Information += "<br/><hr/><br/>";
Response.Wite(Information);
}
}
}

VB.NET
Dim Information As String = ""
If myPanel.HasControls() Then
For Each c As Control In PanelName.Controls
If Not Object.ReferenceEquals(c.[GetType](),
GetType(System.Web.UI.LiteralControl)) Then
Information += String.Format("Control Name: {0} <br/>",
c.ToString())
Information += String.Format("ID: {0} <br/>", c.ID)
Information += String.Format("Control Visible: {0} <br/>",
c.Visible)
Information += String.Format("ViewState: {0} <br/>",
c.EnableViewState)
Information += "<br/><hr/><br/>"
Response.Wite(Information)
End If
Next
End If

600

ASP.net

C#
;)(TextBox t1 = new TextBox
;)"t1.ID = string.Format("dynamict1
;)myPanel.Controls.Add(t1

VB.NET
)(Dim t1 As New TextBox
)"t1.ID = String.Format("dynamict1
)myPanel.Controls.Add(t1

ASP.net
ASP.net :
Simplecontrols
ASP.net HTML TextBox
Label Buttons.
Richcontrols
ASP.net
Calendar TreeViewMenu
Datacontrols
GridView.
Validationcontrols

JavaScript .
LoginControls
.

601

ASP.net

Webpartcontrols

.
HTMLControls .

GridView +ASP.net .

MasterPages .5

.
100

100 .
include ASP Include
ASP.net MasterPages
.
NewItemMasterPage :

602

ASP.net

.8 .22 MasterPage.
:

ASP.NET
>"<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server
></asp:ContentPlaceHolder

MasterPage
.


:
9

603

ASP.net

.MasterPage .9 .22
:
ASP.NET

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs"


Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form2" runat="server">
<div>
<center>
<table border="1" width=80%>
<tr>
<td>hiiii, i am here</td>
<td><img src="http://vb4arab.com/vb/attachments/logo.jpg" /></td>
<td>any thing</td>
</tr>
<tr>
<td>hii again</td>
<td>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</td>
<td><input type="button" /></td>
</tr>
<tr>
<td colspan=2>large TD :)</td>
<td>bye</td>
</tr>
</table>
</center>
</div>
</form>
</body>
</html>

604

ASP.net

Designer
MasterPage :

.10 .22 .MasterPage




Page:

ASP.NET
"<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1
>Runat="Server"></asp:Content

head. html

605

ASP.net

.6 Sitemap
SiteMap


sitemap :

.11 .22 .SiteMap


:

XML
>? "<?xml version="1.0" encoding="utf-8
> "<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0
>""=<siteMapNode url="" title="" description
><siteMapNode url="" title="" description="" /
><siteMapNode url="" title="" description="" /
></siteMapNode
></siteMap

:
Nodes

606

ASP.net

XML
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="Default1.aspx" title=" " description="">
<siteMapNode url="Default2.aspx" title=""!
description="" />
<siteMapNode url="Default3.aspx" title=""
description="" />
</siteMapNode>
</siteMap>

MasterPage
: sitemap DataSource Menu

. .12 .22
Sitemap DataSource

607

ASP.net

.13 .22 SiteMap .


:

SiteMapPath
:

masterpage

.7 ValidationControls
Client Side
:

608

ASP.net

CompareValidator


RangeValidator
RequiredFieldValidator .
RegularExpressionValidator
Reqular Expression
Reqular
Expressions - : -

http://www.arabteam2000-forum.com/index.php?showtopic=77787

RegularExpression :

http://regexlib.com/DisplayPatterns.aspx
http://www.regular-expressions.info/

CustomValidator .
ValidationSummary -

609

ASP.net

.
:
: ControlToValidate .
: Display .
: ErrorMessage .
: ForeColor .

.
RequiredFieldValidator:
CompareValidator:
RegularExpressionValidator:
10 RangeValidator:50
...
:

610

ASP.net

.14 .22 .
:

611

ASP.net
ASP.NET

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs"


Inherits="Default4" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div> Name:<br />
&nbsp;<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="you must eneter
Name"></asp:RequiredFieldValidator><br /><br />
Age:<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="TextBox2" ErrorMessage="Age must be between 10
and 50"
MaximumValue="50" MinimumValue="10"></asp:RangeValidator>
<br /><br />
Password:<br />
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<br /><br />
Retype Password:<br />
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToCompare="TextBox3" ControlToValidate="TextBox4"
ErrorMessage="The passwords must be the
same"></asp:CompareValidator><br /><br />
E-mail:<br />
&nbsp;<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server"
ControlToValidate="TextBox5" ErrorMessage="invalid email address"
ValidationExpression="^((?&gt;[a-zA-Z\d!#$%&amp;'*+\/=?^_`{|}~]+\x20*|&quot;((?=[\x01-\x7f])[^&quot;\\]|\\[\x01\x7f])*&quot;\x20*)*(?&lt;angle&gt;&lt;))?((?!\.)(?&gt;\.?[a-zAZ\d!#$%&amp;'*+\-/=?^_`{|}~]+)+|&quot;((?=[\x01-\x7f])[^&quot;\\]|\\[\x01\x7f])*&quot;)@(((?!-)[a-zA-Z\d\-]+(?&lt;!-)\.)+[a-zAZ]{2,}|\[(((?(?&lt;!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zAZ\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01\x7f])+)\])(?(angle)&gt;)$"></asp:RegularExpressionValidator>
<br /><br />
<asp:Button ID="Button1" runat="server" Text="Go On" /><br /><br />
<Summery:r />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
</div>
</form>
</body>
</html>

612

ASP.net

ErrorMessage ControlToValidate
.
RegularExpression :
"^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01\\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA"Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$

ControlToValidate

ControlToCompare

Range

MinimumValue

.MaximumValue
:

613

ASP.net

.15 .22 . Summery


WebParts :
http://msdn.microsoft.com/en-us/library/e0s9t4ck.aspx

CSS :

http://www.w3.org/Style/CSS/learning

614

ASP.net

ASP.net Themes

http://msdn.microsoft.com/en-us/library/ykzx33wh.aspx

StateManagement .8
DesktopApplication
Scope
ASP.net

.
:
. Viewstate . Controlstate . ApplicationLevelVariable . Cache . Session. Cookies -

ControlState .1.8

EnableViewState

.

615

ASP.net

View State HTML


.ViewState

ASP.NET

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"


value="/wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFBWFobWVkZGRkCq8FGqyXB
P0pBDpvdnycvM5zSQE=" />


Form_Load
:

C#
ListBox1.Items.Add("Ahmed");
ListBox1.Items.Add("Mohammed");
ListBox1.Items.Add("Ali");

VB.NET
ListBox1.Items.Add("Ahmed")
ListBox1.Items.Add("Mohammed")
ListBox1.Items.Add("Ali")

!!!
EnableViewState
: IsPostBack
C#

if (!IsPostBack)
{
ListBox1.Items.Add("Ahmed");
ListBox1.Items.Add("Mohammed");
ListBox1.Items.Add("Ali");
}

VB.NET
If Not IsPostBack Then
ListBox1.Items.Add("Ahmed")
ListBox1.Items.Add("Mohammed")
ListBox1.Items.Add("Ali")
End If

616

ASP.net

ViewState .2.8

C#
ViewState["CustomViewStateItem"] = "Ahmed";

VB.NET
ViewState("CustomViewStateItem") = "Ahmed"

C#
Label1.Text = (string)ViewState["CustomViewStateItem"];

VB.NET
Label1.Text = DirectCast(ViewState("CustomViewStateItem"), String)

Session .3.8

ViewState
:

C#
Session["mySession"] = "Ahmed";

VB.NET

Session("mySession") = "Ahmed"

:
C#
string name = (string)Session["mySession"];

617

ASP.net

VB.NET
)Dim name As String = DirectCast(Session("mySession"), String

Remove Session :

C#
;]"Session.Remove["mySession

VB.NET
)"Session.Remove("mySession

Timeout Session
20:

C#
;Session.Timeout = 5

VB.NET
Session.Timeout = 5

Cookies .4.8


) (

System.Web.HttpCookie
-

-

.

:

618

ASP.net

. .16 .22
:

ASP.NET
<asp:Panel ID="Panel1" runat="server" Height="134px" Width="446px"
BackColor="Yellow">
:<br />
<br />
<asp:RadioButton ID="RadioButton1" runat="server" Text=""
GroupName="colors" />
<br />
<asp:RadioButton ID="RadioButton2" runat="server"
oncheckedchanged="RadioButton2_CheckedChanged" Text=""
GroupName="colors"/>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text=""
onclick="Button1_Click1" />
</asp:Panel>


: ( )

619

ASP.net

C#

string color;
if (RadioButton1.Checked)
{
color = "Green";
Panel1.BackColor = System.Drawing.Color.Green;
}
else if (RadioButton2.Checked)
{
color = "Red";
Panel1.BackColor = System.Drawing.Color.Red;
}
else
color = "";
HttpCookie Cookie = new HttpCookie("myColor", color);
Cookie.Expires = DateTime.Parse("01/01/2009");
Response.Cookies.Add(Cookie);

VB.NET

Dim color As String


If RadioButton1.Checked Then
color = "Green"
Panel1.BackColor = System.Drawing.Color.Green
ElseIf RadioButton2.Checked Then
color = "Red"
Panel1.BackColor = System.Drawing.Color.Red
Else
color = ""
End If
Dim Cookie As New HttpCookie("myColor", color)
Cookie.Expires = DateTime.Parse("01/01/2009")
Response.Cookies.Add(Cookie)

myColor Form_Load
:
C#
if (Request.Cookies["myColor"] != null)
{
string color = Request.Cookies["myColor"].Value;
if (color == "Green")
Panel1.BackColor = System.Drawing.Color.Green;
else if (color == "Red")
Panel1.BackColor = System.Drawing.Color.Red;
}

620

ASP.net

VB.NET
If Request.Cookies("myColor") IsNot Nothing Then
Dim color As String = Request.Cookies("myColor").Value
If color = "Green" Then
Panel1.BackColor = System.Drawing.Color.Green
ElseIf color = "Red" Then
Panel1.BackColor = System.Drawing.Color.Red
End If
End If

Application .5.8
HttpApplicationState

.
:

)( Add
AllKeys
Count

)( Lock(), Unlock
)( RemoveAt
)( Remove(),RemoveAll
.6 .22 HttpApplicationState
Application :

C#

;Application["Visitors"] = 1

621

ASP.net

VB.NET
Application("Visitors") = 1

C#
labelVistor.Text = (string)Application["Visitors"];

VB.NET
labelVistor.Text = DirectCast(Application("Visitors"), String)

C#
Application["Visitor"] = ((int)Application["Visitor"]) + 1;

VB.NET
Application("Visitor") = CInt(Application("Visitor")) + 1

Application

Cache .6.8

:

C#

Context.Cache["myCache"] = "hii, my first cache";

VB.NET

Context.Cache("myCache") = "hii, my first cache"

622

ASP.net

C#
;]"string myCache = (string)Context.Cache["myCache

VB.NET
)Dim myCache As String = DirectCast(Context.Cache("myCache"), String

Global.asax .7.8
Global.asax
Global
:

623

ASP.net

.Global.asax .17 .22


:

C#
using System;
namespace myWebSite
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
}
}

624

ASP.net

VB.NET

<%@ Application Language="VB" %>


<script runat="server">
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application startup
End Sub
Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application shutdown
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a new session is started
End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a session ends.
' Note: The Session_End event is raised only when the sessionstate mode
' is set to InProc in the Web.config file. If session mode is set to
StateServer
' or SQLServer, the event is not raised.
End Sub
</script>


Application_Error State Management

. StateManagement

ASP.net .9
ASP.net
. ADO.net


:

625

ASP.net

C#

SqlConnection cn = new SqlConnection(@"Data Source=AHMED-PC\SQLEXPRESS;Initial


Catalog=Items;Integrated Security=True;Pooling=False");
cn.Open();
SqlCommand cmd = new SqlCommand("select * from Items", cn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Response.Write("<b><font color=blue> Item Number: </font></b>" +
dr.GetInt64(0).ToString() + "<br/>");
Response.Write("<b><font color=blue> Item Name: </font></b>" +
dr.GetString(1) + "<br/>");
Response.Write("<b><font color=blue>Item Price: </font></b>" +
dr.GetInt64(2).ToString() + "<hr/>");
}

VB.NET
Dim cn As New SqlConnection("Data Source=AHMED-PC\SQLEXPRESS;Initial
Catalog=Items;Integrated Security=True;Pooling=False")
cn.Open()
Dim cmd As New SqlCommand("select * from Items", cn)
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Response.Write("<b><font color=blue> Item Number: </font></b>" +
dr.GetInt64(0).ToString() + "<br/>")
Response.Write("<b><font color=blue> Item Name: </font></b>" +
dr.GetString(1) + "<br/>")
Response.Write("<b><font color=blue>Item Price: </font></b>" +
dr.GetInt64(2).ToString() + "<hr/>")
End While

. .18 .22


images
-
:

626

ASP.net
C#

SqlConnection cn = new SqlConnection(@"Data Source=AHMED-PC\SQLEXPRESS;Initial


Catalog=Items;Integrated Security=True;Pooling=False");
cn.Open();
SqlCommand cmd = new SqlCommand("select * from Items", cn);
SqlDataReader dr = cmd.ExecuteReader();
Response.Write("<center><table border=1><tr valign=center align=center
bgcolor=#AAAAAA><td><b>Item No.</b></td><td><b>Item Name</b></td><td><b>Item
Price</b></td><td><b>Sample</b></td></tr>");
while (dr.Read())
{
Response.Write("<tr><td><b>" + dr.GetInt64(0).ToString() + "</b></td>");
Response.Write("<td>" + dr.GetString(1) + "</td>");
Response.Write("<td>" + dr.GetInt64(2).ToString() + "</td>");
Response.Write(@"<td><img src='images/" + dr.GetString(3) +
"'></td></tr>");
}
Response.Write("</table></center>");

VB.NET

Dim cn As New SqlConnection("Data Source=AHMED-PC\SQLEXPRESS;Initial


Catalog=Items;Integrated Security=True;Pooling=False")
cn.Open()
Dim cmd As New SqlCommand("select * from Items", cn)
Dim dr As SqlDataReader = cmd.ExecuteReader()
Response.Write("<center><table border=1><tr valign=center align=center
bgcolor=#AAAAAA><td><b>Item No.</b></td><td><b>Item Name</b></td><td><b>Item
Price</b></td><td><b>Sample</b></td></tr>")
While dr.Read()
Response.Write("<tr><td><b>" + dr.GetInt64(0).ToString() + "</b></td>")
Response.Write("<td>" + dr.GetString(1) + "</td>")
Response.Write("<td>" + dr.GetInt64(2).ToString() + "</td>")
Response.Write("<td><img src='images/" + dr.GetString(3) + "'></td></tr>")
End While
Response.Write("</table></center>")

627

ASP.net

.19 .22 .
*** ASP Classic
... .net

DataGrid .1.9
ASP.net ...
DataGrid
SqlDataSource :

628

ASP.net

.20 .22 .
ConnectionString .Next
:

629

ASP.net

.21 .22 .

Control :

630

ASP.net

.22 .22 .
Query .
DataGrid DataSource

SqlDataSource
:
.23 .22
.Data Grid

631

ASP.net

Enter :

.24 .22 .Data Grid


.
CSS :

.25 .22 Data Grid .Css


GridView
:

632

ASP.net

.26 .22
DataGrid
.GridView
:

C#
;)(string something = GridView1.SelectedRow.Cells[0].ToString

VB.NET
Dim something As String
)(something=GridView1.SelectedRow.Cells(0).ToString

633

ASP.net

.27
.22

... AutoGenerateEditButton
FormView DetailsView .
:

.28 .22 .
ASP.net
... ADO.net

634

ASP.net

WAP .10
Protocol WirelessApplication
WAP
.net

.1.10 WAP
MobileApplication



.

WAP WEB
.

WAP
WAP Wireless Application Protocol
WAP Standard
Mobiles
.

.

WAP
WAP WEB

635

ASP.net


.
WAP
.
WAP URL
HTML WML HTML
WAP .
HTML ...

WML .2.10
HTML XML
HTML :
><html
Tag > <wml Cards > <card >.<card/
- : -
WML

WML
>?"<?xml version="1.0
"<!DOCTYPE wml PUBLIC "-//PHONE.COM//DTD WML 1.1//EN
> ""http://www.phone.com/dtd/wml11.dtd
><wml
>"<card id="main" title="First Card
><p mode="wrap">This is a sample WML page.</p
></card
></wml

:
:

636

ASP.net

WML
<setvar name="First_Name" value="Ahmed"/>
<setvar name="Age" value="21"/>

WML
<p>First Name: $(First_Name)</p>

Select
...

: -

WML
<card id="card1" title="Tutorial">
<do type="accept" label="Answer">
<go href="#card2"/>
</do>
<p>
<select name="name">
<option value="HTML">HTML Tutorial</option>
<option value="XML">XML Tutorial</option>
<option value="WAP">WAP Tutorial</option>
</select>
</p>
</card>
<card id="card2" title="Answer">
<p>
You selected: $(name)
</p>
</card>
</wml>

WAP+ASP.net .3.10

- -
:
WML
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//PHONE.COM//DTD WML 1.1//EN"
"http://www.phone.com/dtd/wml11.dtd" >
<wml>
<card id="main" title="First Card">
<p mode="wrap">This is a sample WML page.</p>
</card>
</wml>

637

ASP.net

.net :

ASP.NET
><%@ Page Inherits="System.Mobile.UI.MobilePage" Language="C#" %
><%@ Register TagPrefix="mobile" Namespace="System.Mobile.UI" %
>"<mobile:Form runat="server
>"<mobile:Label runat="server
This is a sample WML page.
></mobile:Label
></Mobile:Form

VB.net :

ASP.NET
><%@ Page Inherits="System.Mobile.UI.MobilePage" Language="C#" %

WML

HTML
.
WAB NET.

.

Ajax .11
ASP.net
AJAX .net

.1.11 Ajax
Asynchronous JavaScript and XML


.

638

A
ASP.net


Gmail

AJA
AX


Yahoo.Hotmail
:

_http://en..wikipedia.orrg/wiki/Ajax
_%28progra
amming%29
9

.n
net







AJAX
A


. AJJAX


Atlas
A

Asp.net Ajax
A
ToolKiit

http://aja
ax.asp.net/ajjaxtoolkit/

http://aja
ax.asp.net/

Asp.net

http://ww
ww.asp.net/learn/defaultt.aspx?tabid=63

639

ASP.net

http://download.microsoft.com/download/0/f/6/0f651a0f-6f2b-4497-b061e1b2825e22e0/MSAJAX-ToDoList-Video.zip

.Atlas
AjaxToolKit :

http://www.asp.net/learn/videos/view.aspx?tabid=63&id=75
http://www.asp.net/learn/videos/view.aspx?tabid=63&id=76

...

C#
;)(TextBox1.Text = DateTime.Now.ToString

VB.NET
)(TextBox1.Text = DateTime.Now.ToString



ScriptManager :

640

ASP.net

. .28 .22
UpdatePanel
:

ASP.NET
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default6.aspx.cs"
Inherits="Default6" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form2" runat="server">
<div>
<img src="images/food.jpg" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server"><ContentTemplate>
<br />
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="ShowTime" />
</ContentTemplate></asp:UpdatePanel>
</div>
</form>
</body>
</html>

641

ASP.net


. updatepanel
: updatepanel updatePanel

ASP.NET
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>

:

ASP.NET

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default6.aspx.cs"


Inherits="Default6" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form2" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<img src="images/food.jpg" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server"><ContentTemplate>
<br />
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="ShowTime" />
</div>
</form>
</body>
</html>

642

ASP.net



.Enter

GridView .
updatepanel GridView
Triggers :

643

ASP.net
ASP.NET

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs"


Inherits="Default5" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server"><title>Untitled Page</title></head><body>
<form id="form2" runat="server"><center><div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ItemsConnectionString %>"
SelectCommand="SELECT * FROM [Items] WHERE ([ItemPrice] &lt; @ItemPrice)">
<SelectParameters>
<asp:ControlParameter ControlID="TextBox1" DefaultValue="0"
Name="ItemPrice" PropertyName="Text" Type="Int64" />
</SelectParameters>
</asp:SqlDataSource><br /><br />
<asp:Button ID="Button1" runat="server" Text="Button" />
&nbsp;<asp:TextBox ID="TextBox1" runat="server">1000</asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="
<>"/asp:Label><br />
<asp:ScriptManager ID="ScriptManager1" runat="server"
EnablePartialRendering="true">
</asp:ScriptManager><br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1"
AllowPaging="True" AllowSorting="True" AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True" AutoGenerateSelectButton="True" BackColor="White"
BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3"
GridLines="Horizontal" onselectedindexchanged="GridView1_SelectedIndexChanged">
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="ItemName" HeaderText="ItemName"
SortExpression="ItemName" />
<asp:BoundField DataField="ItemPrice" HeaderText="ItemPrice"
SortExpression="ItemPrice" />
<asp:BoundField DataField="ItemPicture" HeaderText="ItemPicture"
SortExpression="ItemPicture" />
</Columns>
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<AlternatingRowStyle BackColor="#F7F7F7" />
</asp:GridView>ContentTemplate>
<Triggers><asp:AsyncPostBackTrigger EventName="Click"
ControlID="Button1" /> </Triggers>
</asp:UpdatePanel><br /><br /><br /></div><center></form></body>
</html>

644

ASP.net

AJAX Toolkit
AJAX
:

http://www.asp.net/ajax/ajaxcontroltoolkit/samples/

http://www.asp.net/ajax/ajaxcontroltoolkit/

645

646


.net 2008

.net2
2008
.

http://ww
ww.AhmedGa
amal-Techniical.blogspott.com



.
.

647


Pro
oC#2008 2
and the .NET 3.5 Platfo
orm, Explo
oring the .NET univverse usingg curly
Pro C# 2008
brackets..
Aouther:AndrewTTroelsen.
Edition:FFourthEdittion
M
MSDN
MSDNM
MicrosftD
DeveloperN
Network,

http://mssdn2.microso
oft.com/en-u
us/default.asspx

http://ww
ww.vb4arab.com

http://ww
ww.arabteam
m2000-forum
m.com/

648

649

You might also like