Professional Documents
Culture Documents
Dotnet 2008 PDF
Dotnet 2008 PDF
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
)
(
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
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
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
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
08
OOP
13
09
10
14
207 .......................................................................................... .6
Collections
11
12
15
13
16
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
15
18
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
19
17
20
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
21
21
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
22
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
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
net 2008. C#
netFramework.
http://go.microsoft.com/?linkid=7653518
.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
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 :
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
.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#
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
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
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
.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
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#
VB.NET
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#
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
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"
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#
VB.NET
...
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#
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#
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#
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#
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
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#
VB.NET
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
.10
= ==
C# :
C#
)if (x == y
{
}
VB.NET
if x = y Then
End if
True False
5=5 : 7=7 " "Ahmed"="Ahmed
.
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
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
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
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#
VB.NET
:
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#
VB.NET
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#
VB.NET
static counter
: Class
C#
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#
VB.NET
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
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#
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
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
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
.
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#
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
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
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#
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
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
move() implementation
:BMW
C#
public class BMW : ITruck, ICar
{
void move()
{
// do something.
}
}
VB.NET
185
Interfaces
C#
VB.NET
BMW object
:
C#
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#
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
188
Interfaces
VB.NET
.IEnumerable loop
:IEnumerable interface
C#
public interface IEnumerable
{
IEnumerator GetEnumerator();
}
VB.NET
IEnumerator interface
C#
public interface IEnumerator
{
bool MoveNext();
object Current { get; }
void Reset();
}
VB.NET
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
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#
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#
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#
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
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#
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#
VB.NET
IComparable reference T
.Constructor
:
C#
public class Example<K, T> where K : class, new()
where T : IComparable<T>
VB.NET
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#
VB.NET
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
: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
.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
: 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; }
}
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#
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
254
.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
:
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
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
. ***
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
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
var DimDataType
NullableTypes .
Lambda .
PreprocessorDirectives .15
:
263
.net
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
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
.elif else
. .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>
.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
:
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
.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
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#
VB.NET
))Dim t As New Thread(New ParameterizedThreadStar(functionname
)t.Start(parms
ThreadStart
)( BeginInvoke )(EndInvoke
Foregroundandbackground .6.18
:threads
:ForegroundThread
: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
289
.net
C#
VB.NET
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#
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")
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#
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
:
Or
C#
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
)( 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#
VB.NET
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
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
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:
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
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#
VB.NET
Private Sub MyNotificationHandler(ByVal source As Object, ByVal e As
RenamedEventArgs)
End Sub
315
.net
q
WindowsForms
: c:\
C#
watcher.EnableRaisingEvents = true;
Console.WriteLine("Press 'q' to quit app.");
while (Console.Read() != 'q') ;
VB.NET
watcher.EnableRaisingEvents = True
Console.WriteLine("Press 'q' to quit app.")
While Console.Read() <> "q"c
End While
316
.net
OnChanged
OnChanged
: -
C#
VB.NET
...
)
: (
. .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#
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
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#
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
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
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#
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
333
2008 .net
334
2008 .net
.5 .14 .
F5.
....
.
VisualStudio
.
ToolBox
View
.ToolBox
335
2008 .net
.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
.14 .14 .
.10.6
TreeView
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
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#
VB.NET
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
:
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
:
361
2008 .net
http://msdn.microsoft.com/en-us/library/ms646375.aspx
FontDialog .4.7
362
2008 .net
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
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
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
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
http://msdn.microsoft.com/en-us/library/system.windows.forms.printdialog.aspx
.8
MouseDown
Properties
367
2008 .net
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
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
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#
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
:
C#
379
GDI+
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
.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
. .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
-
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
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
DataBinding .7
Slider
WPF
: TextBox
XAML
DataContext = "{Binding ElementName=slider1}" Content = "{Binding Path=Value}"
XAML
: XAML
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
401
WPF
402
WPF
.2.8 Pen
XAML
.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>
404
WPF
http://msdn.microsoft.com/en-us/library/aa970904.aspx
Transformations .4.8
.
:
XAML
.15 .16
.Transformation
WPF
:
405
WPF
http://www.codeproject.com/KB/WPF/TransformationsIntro.aspx
.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
VB.NET
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#
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
. .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
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
. .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
:
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#
VB.NET
419
WPF
C#
VB.NET
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
424
WPF
HTML styles
Asp.net
.php
:
http://www.microsoft.com/expression/features/default.aspx?key=web
MicrosoftExpressionDesign .2.15
425
WPF
http://www.microsoft.com/expression/features/default.aspx?key=design
MicrosoftExpressionMedia .3.15
426
WPF
http://www.microsoft.com/expression/features/default.aspx?key=media
MicrosoftExpressionEncoder .4.15
Silver
Light Flash Macromedia
Adobe.
427
WPF
http://www.microsoft.com/expression/features/default.aspx?key=encoder
MicrosoftExpressionBlend .5.15
...
428
WPF
Expression Blend
New Project ) WPF Application (*.exe
:
429
WPF
430
WPF
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
. .34 .16
: XAML
433
WPF
XAML
Top Left
:
. .35 .16
434
WPF
:XAML
XAML
<Canvas>
<Canvas x:Name="MainImageCanvas" Canvas.Left="40" Canvas.Top="120">
MediaElement
...
.
435
WPF
XAML
MicrosoftExpression
.
:
http://expression.microsoft.com/en-us/cc136522.aspx
436
437
17
ADO.net
438
439
ADO.net
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
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
: IDbDataParameter
:
C#
public interface IDbDataParameter : IDataParameter
{
byte Precision { get; set; }
byte Scale { get; set; }
int Size { get; set; }
}
444
ADO.net
VB.NET
: IDataParameter
:
C#
VB.NET
: 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
: 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)
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=192622&SiteID=1
450
ADO.net
.3 .17 .
Stored Procedure
:
.4 .17 .
451
ADO.net
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
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
:
: . .
: 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
468
ADO.net
. StoredProcedure :
469
ADO.net
TSQL
ALTER PROCEDURE dbo.GetAge
@condition int,
@firstname char(10) output
AS
]SELECT @firstname =[First Name
FROM Employee_info
WHERE age > @condition
SQLServer
.
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
:
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#
VB.NET
:
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#
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
@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
478
ADO.net
true Read
...
myDataReader["Age"]
.
myDataReader[2]
FieldCount
:
C#
VB.NET
: 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
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
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
C#
myDataLayer example=new myDataLayer();
example.OpenConnection(myconnectionstring);
example.DeleteEmployee(10);
example.DeleteEmployee("Ahmed");
VB.NET
!!!
. 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()
C#
string strSQL = "WaitFor Delay '00:00:05';Select * From Employee_info";
SqlCommand myCommand = new SqlCommand(strSQL, cn);
VB.NET
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#
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
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#
VB.NET
)"Dim empDataSet as DataSet = New DataSet("My Employee
.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#
VB.NET
DataRow .5.9
:
498
ADO.net
)( BeginEdit
)( EndEdit
)( CancelEdit
)( Delete )(AcceptChanges
)( IsNull null
RowState enum
DataRowState
.5 .17 .DataRow
- DataRowState :
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
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
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#
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
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#
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
LastOrDefault
:
>= Employee firstone = employees.LastOrDefault(emp
;)emp.ismarried == 1
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#
VB.NET
Dim purchaseOrder As XElement = XElement.Load("Items.xml",
LoadOptions.SetBaseUri Or LoadOptions.SetLineInfo)
C#
var newSearch
520
LINQ
VB.NET
Dim newSearch = From item In Items.<Item>() _
Select item.@Number
100
C#
var newSearch
VB.NET
Dim newSearch = From item In Items.<Item>() _
Where (item.<Price>.Value > 100) _
Select item.@Number
LINQToSQL .5
SQL Server LINQ
.
: 30
C#
VB.NET
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#
VB.NET
: 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
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#
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#
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
. .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
535
WWF
536
WWF
.2 WWF
.
Sequential Workflow Console Application
:
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#
VB.NET
Activity
: Activity ThisPasswordisWrong
C#
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 :
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
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
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#
for (int i = 2; i <= 10; i += 2)
{
System.Console.WriteLine(i);
System.Console.WriteLine(i*10);
}
:
C#
:
VB.net
VB.NET
For c = 2 To 10 Step 2
System.Console.WriteLine(c)
Next
566
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
- 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
.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
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"();">
<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
... . 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
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
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
604
ASP.net
Designer
MasterPage :
ASP.NET
"<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1
>Runat="Server"></asp:Content
head. html
605
ASP.net
.6 Sitemap
SiteMap
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
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
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
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
ASP.NET
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
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#
VB.NET
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
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_Error State Management
. StateManagement
ASP.net .9
ASP.net
. ADO.net
:
625
ASP.net
C#
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#
VB.NET
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 :
.
CSS :
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
642
ASP.net
.Enter
GridView .
updatepanel GridView
Triggers :
643
ASP.net
ASP.NET
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