CSLesson9 - una.co.uk

grapedraughtΛογισμικό & κατασκευή λογ/κού

2 Δεκ 2013 (πριν από 3 χρόνια και 6 μήνες)

206 εμφανίσεις

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

1

Lesson 09:
Windows

Forms
,

Exception Handling
, WPF
, File Handling
.


Windows Forms



Windows Forms have been deprecated ie they are no longer recommended for use. They have
been replaced by Windows Presentation Foundation (WPF)
-

see later.


However since
you may still encounter them as legacy code
, for
reference

we will consider them
here.


Day 16 & 17 C#21 days or


















A form is an interface for our programs. See below:


The .Net framework contains code to make a form for us. It consists of
classes that we can use to
make Form objects (and Button objects etc).











Here are two ways that we will go about it.


1. Write the code from scratch and set a reference to the System.Windows.Forms library of
classes or


2. Specifically choose to
make a Windows Forms application from the IDE (rather than Console
Application.



We will try approach 1. first.

http://www.programmersheaven.com/2/CSharpBook


Download
csharp_ebook.pdf
.


This reference will be referred to as PH.


Pages 190


㈲㤠is⁥ c敬le湴nr敦敲敮e攮et潲瑨⁦潬lowin朠
in⁤ t慩l.


T漠o潰y⁩n⁴ e⁣潤e yo甠睩ll 敤⁴漠o潮v敲琠e桩s 灤f⁴ ⁡ tor搠d潣畭敮琮


䡥e攠es⁡⁦r敥 lin攠e潮v敲瑥爺

桴h瀺pL睷眮灤w瑯睯w搮d潭L


El渠n慧e‱ ㄠ1潴o⁴ a琠t琠is c敳s慲y⁴ ⁳e琠t⁲敦敲e湣攠e漠opy
st敭.ti湤潷s⹆潲ms⸩


Adv慮t慧攠ef tmc

潶敲⁆orms
W

ㄮ1uAM䰠⡳敥 l慴arF⁰ 潶i摥s⁡ m潲攠數灥摩e湴nway 潦⁰牯摵ci湧 愠a潲m⸠

㈮2T桥慮y⁳kills散敳s慲y⁴ 灲潤畣e⁲ich

f潲os⁥ ⁇䑉Ⱐ䑩r散琠tⰠ䵥di愠
mlay敲e慲攠a湮散敳s慲y wit栠tmc⸠T桥s攠er攠e慫敮⁣慲攠潦⁷ 瑨ttmc⁷it桯u琠
r敱畩ri湧 瑨ts攠數瑲愠aro杲慭mi湧⁳kills.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

2

1.

Writing Code To Produce
a

Form


o

Follow pages 540


(Chapter 16) of C# 21 Days.


o

Make a Console Application called test.


o

Paste this code over

the code in the code window.


using

System.
Windows
.Forms;


public

class

FirstFrm

: Form

{


public

static

void

Main()


{


FirstFrm

frmHello =
new

FirstFrm
();


Application
.Run(frmHello);


}

}


This line means that

the class
Firs
tFrm

derives from
System.
Windows
.Forms.Form
.


To

set a reference:
































(Before we set a
reference, some
lines show an error.)

o

Right
-
click on
References and then
choose Add Reference.

o

Navigate to
System.Windows.Forms
and click OK.

o

Choose the Net tab.

Application
.Run

registers
your form so that it may
receive event mes
sages from
the Windows OS.

The
System.
Win
dows.Forms
namespaces contain the base
classes for windows controls
eg Form Label and Button.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

3


o

Run the program. We obtain our basic Form along with the Console Window.


To Ensure That The Console

Window Does Not Appear As Well

































o

Run the program. Now only our form appears as required.


















o

Choose
Project,


…. Properties.

o

Choose Window Application.

o

Choose Application.

o

See page 546 C# in
21 Days for the code to
control the appearance of the form eg to turn
on/off the close button etc. FormApp.cs in the
downloaded code.


// Caption bar properties


frmHello.MinimizeBox =
true
;


frmHello.MaximizeBox =
false
;


frmHello.HelpButton =
true
;


frmHello.ControlBox =
true
;


frmHello.Text =
@"My Form's Caption"
;


You could read up to page 556

and try the code
which controls the appearance of the
form
.


C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

4

To Produce
a

Form
w
ith
a

Button
b
y Writing
t
he Code


o

R
e
place your code with this:






















































using

System;

using

System.ComponentModel;

using

System.Drawing;

using

System.Windows
.Forms;


namespace

exp

{


public

class

Form1

: Form


{


public

Button button1;


public

Form1()


{


button1 =
new

Button();


button1.Size =
new

Size(40, 40);


button1.Location =
new

Point(30, 30);


button1.Text =
"Click me"
;


this
.Controls.Add(button1);


button1.Click +=
new

EventHandler
(button1_Click);


}


private

void

button1_Click(
object

sender,
EventArgs

e)


{


MessageBox.Show(
"Hel
lo World"
);


}


[
STAThread
]


static

void

Main()


{


Application.EnableVisualStyles();


Application.Run(
new

Form1
());


}


}

}

o

Set a reference to
System.Drawing.

The System.Drawing
namespace is necessary
as it contains the
classes related to the
drawing of controls.

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

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

5


o

Run the progra
m. Our form appears with a command button.














o

Read the rest of the chapter 16 but remember that there are easier ways of adding these
controls.


C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

6



2.

Making a Windows Forms Project


See:


Making a Program Using a Form



1.

On the File menu,
click New Project.

2.

Ensure the Windows
Forms
Application template is selected, and in the Name field, type
"MyProject". Click OK to create the project.

You will see a Windows Form in the Windows Forms Designer. This is the user interface
of your applicati
on.

3.

Open the View menu,

Other Windows,

and click Toolbox to make the list of controls
v
isible.









4.

Click Label, and then drag the label control to the middle of your form.

5.

From the Toolbox, drag a button onto the form, near the label.

6.

Double
-
cl
ick your button to open the Code Editor. Visual C# Express Edition has inserted
a method called
button1_Click
that
will be

executed when the button is clicked.

7.

Change the method so it reads

private void
button1_Click(object sender, EventArgs e)

{


la
bel1.Text = "Hello, World!";

}

8.

Press F5 to compile and run your application.

o

Choose the
All Windows Forms

tag.

Make sure
that your label on the
form is indeed named
lable
l
1
.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

7

9.

When you click the button, a text message is displayed.







To access the code:

o

Open solution explorer.



o

Then double
-
click on the form designer.



private

void

bu
tton1_Click(
object

sender,
EventArgs

e)


{




label1.Text =
"Hello, World!"
;


}

etc.

o

Double
-
click.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

8

Note that we have three program files in our project: Form1.cs,

Form1.Designer.cs

&
Program.cs
:






































using

System;

using

System.Drawing;

using

System.Text;

using

System.Windows.Forms;


namespace

MyProject

{


public

partial

class

Form1

:
Form


{


public

Form1()


{



InitializeComponent();


}


private

void

button1_Click(
object

sender,
EventArgs

e)


{


label1.Text =
"Hello"
;


}


}

}

Form1.cs


using

System;

using

System.Windows.Forms;

namespace

MyProject

{


static

class

Program


{


///

The main entry poi
nt for the application.


[
STAThread
]


static

void

Main()


{


Application
.EnableVisualStyles();


Application
.SetCompatibleTextRenderingDefault(
false
);


Application
.Run(
new

Form1
());


}


}

}

Pr
ogram.cs
:

These 2 partial classes could be placed in one
file/class but the Form1.Desi
gner code does not
need to be altered by us so it is separated. and

we do most of our coding in the one above
.

Form1.Designer.cs

If we change the name of the form,
then this permeates thru the whole of
the code ie
Form1
, is replaced
automatically by the new name.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

9

More C
ontrols


We wish to add a List Box and populate it at run time.






































o

Change its name by right
-
clicking on the List Box and choosing Properties.













o

Drag a ListBox control
onto our design
-
time form.

o

If the Toolbox is not
visible, choose View, Other
Windows, Toolbox.


o

Change the Name to
lbxBooks
.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

10

We wish the list box to be populated when the form appea
rs.


We need the Form’s
Shown

event.


This fires when the form
appears

on our screen


o

Go to the properties of the Form. (Make sure that the Form is selected when you right
-
click
and choose Properties.)



















private

void

Form1_Show
n(
object

sender,
EventArgs

e)


{


lbxBooks.Items.AddRange(
new

String
[] {
"Beginning C# by Wrox"
,


"Professional C# by Wrox"
,
"Programming C# by O' Reilly"
,


"Professional ASP.Net"
,
"Beginning Java 2 by Wrox"
,



"C++
-

The complete Reference"
,
"Java Servlets Programming"
,


"Java Server Pages
-

JSP)"
});


}


o

Run it.



















Exercise
: Write code that will MessageBox out the item that we click upon.


o

Double
-
click.

o

When the event stub appears type
in this code or copy from here.

This code is an example of the
code that should be trialled from
PH. It can be found on page 212.

The form appears
with the list box

loaded up.













C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

11

Storing Values in a Windows Fo
rm




page 509 C#2008


We can store our strings in a central "depository".






















































o

Right
-
click our project name..

o

..and choose Properties.

o

Choose
Settings

o

EdsStored is the “label” we
杩v攠e漠o畲⁳瑯t敤⁳瑲i湧⸠

v潵ay敥d⁴
p桯眠wl
l⁆il敳.

E䑯畢le
-
clicki湧⁴桩s畳琠
杩v敳⁴ 攠eb潶攠ea扬攠e条in⸩

o

To view the code that has been written
for us to accommodate our string, d
ouble
-
click


Settings.Designer
.cs

.



o

Give a value
to the string.

(The name of this project is AppSettings.)

o

Expand
Properties.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

12


Here it is:


namespace

AppSettings.Properties {

……




public

static

Settings

Default {



get

{


return

defaultInstance;


}


}

………



public

string

EdsStored

{


get

{


return

((
string
)(
this
[
"EdsStored"
]));


}


set

{


this
[
"EdsStored"
] =
va
lue
;


}


}


}

}


o

Write this code in our Form1.cs code:


private

void

button1_Click(
object

sender,
EventArgs

e)


{


string

s;


s = Properties.
Settings
.Default.EdsStored;


MessageBox
.Show(s);



}


o

Press F5 to build and run our program.

















o

Click our
button.

Our message
box appears.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

13

Events


We have seen how events are generated by clicking a button on a form.


button1.Click +=
new

System.
EventHandler
(button1_Click);











We could even write our
own

event han
dler




private

void

myEvent(
object

sender,
EventArgs

e)


{


MessageBox
.Show(
"Hello Again"
);


}


In which case we would need to add another method to the delegate:



button1.Click +=
new

System.
EventHandler
(myEvent);






private

void

myEvent(
object

sender,
EventArgs

e)

{

MessageBox
.Show(
"Hello Again"
);

}






I
n

which case when the prog
r
am is run this event will fire as well.





EventHandler

is a “built
-
in” delegate which delegates the event
myEvent

to
occur whenever the
Click

* event occurs for the
button1
.

The signature for the event is always the same ie
(
object

sender,
EventArgs

e)

In Form1.D
esigner.
cs

Besides
Click

we could have
DoubleClick
,
MouseDown

etc.








Events are usually
fired off by some
physical activity eg
clicking the buttons
of the mouse,
pressing a key,
ch
anging some text
in a text box.

In Form1.
cs

In Form1.Designer.
cs

This is the concept of a (multicast) delegate. The same delegate can call
many methods. Also these methods can be added (or
removed) at runtime.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

14


Exception Handling



PH page 155


Chapter
9

C#21 days


An Exception is a run
-
time error.
ie an error which occurs when the program is running. It is not
necessarily detected at compile
-
time.


o

Try this


it has no errors.


using

System;


class

TryIt2

{


public

static

void

Main()


{


string

s =
"ed"
;


Console
.WriteLine(s.ToUpper(
));


Console
.ReadLine();


}

}





o

Build it. It builds just fine!


o

Run it.


Its only when we run it that we see the problem
:
ToUpper()

will not operate on a
null

string.


























This
is not what the user of our program would want

to see. We must
trap

potential errors.


o

Press Shift Alt F10 if this
dialog box is not open.

This program simply
converts a string t
o
upper case.

o

Change this to
string

s =
null
;

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

15

t
ry
c
atch

finally






using

System;


class

TryIt

{


public

static

void

Main()


{


string

s =
null
;



try


{



Console
.WriteLine(s.ToUpper());


}




catch



{


Console
.WriteLine(
"null string"
);


}



finally


{


Console
.WriteLine(
"finally"
);


}



Console
.ReadLine();


}

}

o

Change
string

s =
null
;

back

to
string

s =
"ed"
;


o

We find th
at the

finally

is always executed


error or not
.

o

ie the purpose of a finally block is to ensure that a set of statements will always be executed
-

exception or not.
The last line is also always
executed
-

error or not.

Catch

will catch all errors from the
try
.

o

Replace

catch

with

catch
(
NullReferenceException
)
.

This will now catch
only this particular error
. (null
string.) Take care


if⁡ y o瑨
敲⁴y灥 潦⁥牲潲oc畲u
瑨t⁵ u慬⁲un
-
瑩m攠err潲⁷oll c畲⁡湤⁴桥 灲潧p慭
睩ll⁴ rmi湡瑥t睩t桯畴⁣潮瑲潬⁡ 扥f潲攮⁥朠gf w攠eri敤
瑯tc潭灡r攠e⁳瑲i湧⁴ 慮 in瑥t敲㨠es
=
"ed"
;
)

int

j = s.CompareTo(
'a'
);
woul
d

go untrapped.


Firstly:
The code that
could possibly

throw an exception

is put in the
try

block.



The code to
handle

the thrown exception is placed in
the
catch

block just after the

try

block. This is called catching the exception

If

an exception is raised during the execution of the code inside the
try

block, the
remaining code in the try block is neglected

(If there is any.)

Try it.

The code that must always be executed after the
try
or
try
.. .
catch
block is placed in the
finally

block, placed just after the
try

or
try
...
catch

blocks. This code is guaranteed
to
always be executed

whether the excepti
on occurs or not.

See bottom of this page.

o

Add:
Console
.WriteLine(
"No Error"
);

in the
try

block. This will be output only if there is
no

error.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

16


o

Change th
is

catch:



string

s =
null
;



try


{


Console
.Wri
teLine(s.ToUpper());


}



catch

(
Exception

e
)


{


Console
.WriteLine(
e
);


}


The above message is in two parts:



Console
.WriteLine(e.
StackTrace
);


which ind
icates where the error occurred






and

Console
.WriteLin
e(e
.Message
);


which indicates the actual error.









Tip:
To view a list of exceptions


o

Type:
catch
(
N



we will get the itellisense drop down:














We could equally write:

catch

(System.
Exception

e
)

Also a lis
t of methods which
can be thrown is shown by
hovering the mouse over a
system method:



C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

17

Exercise:


o

This code causes

an error

which is unhandled: Try it.


Provide a catch which

will handle this particular error.



Hint: look at the exception type reported
when it is run.


using

System;

public

class

MyClass

{ }

public

class

ArgExceptionExample

{


public

static

void

Main()


{


string

s =
null
;


try


{



string

st =
String
.Format(s);


}


catch

()


{


Console
.WriteLine(
"Error:"
);


}


Console
.ReadLine();


}

}



Out Of Bounds Error


using
System;


class
TryIt

{


public static void
Main()


{


int
[]

arr =
new int
[3];



try


{


Console
.WriteLine(arr[3]);


}



catch
(
Exception

e)


{


Console
.WriteLine(e.Message);


}



Console
.ReadLine();


}

}






arr[3];

does not exist.

o

Ch
ange this to:

catch

(
IndexOutOfRangeException

e)

Now only this spe
cific error will be
trapped.

Any other error will cause a runtime
exception.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

18

Divide By Zero Error




try


{


Console
.WriteL
ine(
3/arr[2]
);


}



catch
(
DivideByZeroException

e)


{


Console
.WriteLine(e.Message);


}







Finally


For a more practical example of using finally see page 306 C# 21 Days. ie ALWAYS close the file
-

error or not

Do this after

File Handling)
.

This shows the use of Close in the finally block ie the file must be closed whatever happens.


C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

19



Multiple Catch

with a Single Try


o

Place
both

of these catch statements in your code.


using
System;


class
TryIt

{


public static void
Main(
)


{


int
[] arr =
new int
[3];



try


{


C
onsole
.WriteLine(3/arr[
2
]);


}



catch
(
DivideByZeroException

e)


{



Console
.WriteLine(e.Message);


}




catch
(
IndexOutOfRangeException

e)



{



Console
.WriteLine(e.Message);



}




catch
(
Exception

e)


{



Console.WriteLine(e.Message);



}




Console
.ReadLine();


}

}











If we have multiple errors Only ONE will respond:


o

Try

C
onsole
.WriteLine(3/arr[
3
]);



For a list of common Exceptions see page 311
C# in 21 Days.



This will catch any
OTHER exception
which may occu
r

T
his
“general”
c慴ah

扬潣k mus琠tom攠ecTb删瑨o⁳灥cific⁣慴a栠hl潣ks.

䥦 yo甠uo
n’t need to access its properties
you⁣慮畳琠t慶攺

catch
(
DivideByZeroException
)

Generally the more specific error
catch
es are placed first.


arr[
2])

is zero.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

20

t
hrow


throw your own!


using
System;


class
TryIt

{


public static void
Main()


{


try


{


throw
(
new
DivideByZeroException
());


}




catch
(
DivideByZeroException

e)


{


Con
sole
.WriteLine(e.Message);


}




Console
.ReadLine();


}

}

This can be useful for debugging.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

21


Custom Exception Classes


using

System;

class

Program



{


class

Part


{


private

int

i;



public

Part(
int

j)


{ i= j ; }




pub
lic

void

ask()


{


if

(i > 10)


{


PartException

ex =
new

PartException
(
"too big"
);


throw

ex;


}


}


}


public

class

PartException

:
ApplicationException


{


public

Part
Exception()


{


}



public

PartException(
string

s)


{


}


}


static

void

Main()


{


Part

p =
new

Part
(20);


try



{




p.ask();


}




catch

(
PartException
)



{


Console
.WriteLine(
"Greater than 10"
);


}


Console
.ReadLine();


}

}


For a slightly more practical example see page 315 C# 21 Days

where throw is used to
throw
your
custom

exceptions
.

throw

can be more useful when used to
re
thro
w eg to throw a more specific exception.

See page 140 c# 4.0 in a Nutshell.

These allow you to modify the behavior of the standard
Exception

class by providing your own
overrides.

For example you may wish to provide an alternative to the
Message

provided
by the standard
Exception

class.

after page 274 Troelsen


C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

22

Wind
ows Presentation Foundation (WPF
)




Ref:
Page 1117 Troelsen
.

Very comprehensive
-

more from an XAML point of view
-

perhaps a
bit too detailed.


o

File, New Project.










o

Place a Button and a Text Box on the
form.

(First c
hoose the MainWindow.xaml tab.
)




You can see that the Name of the button is
button1

and the Name of the Text Box is
textBox1
.


You can change a Name of the button or the text
-
box by right
-
clicking on the control in the design

view

of the form and choosing Properties
-

or you can change it here!

o

Choose WPF Application.
C
all it MyWPF and click OK.

o

Run it now to show
that it i
s working so far.

Make sure that the
toolbox is visible
(View Toolbox)

You should see the XAML

(see later)

produced dynamically!

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

23

XAML (Extensible
Application

Markup Language) is a variant of XML (Extensible Application
Markup Language).


XML
(and XAML)
is text
.

It uses lots of
<

and
>

's to arrange the text in a hierarchical way,

It is an afterthought of HTML which

also used lots of
<

and
>

's in a hierarchical to describe
the layout of an HTML document.


XAML as it name suggest is used for "marking up"
(designing)
applications

such as our C#
WPF project.


It is a way of providing information to the compiler which u
ses it to produce buttons etc.


For further discussion of XML see

XML.doc

xlVBAXMLexercise.doc

x
lVBADiffValidWellFormedXML.doc

on una.co.uk

We will have more to say on XML next chapter as well.



Take a look at the files produced so far:








A
Window

can only have one item of content ie only a Button for example and not a Text box as
we
ll
. We therefore must have at leas
t one container eg a Grid. Our Grid has been placed on our
Window by default.
Clcick back on our form and see that a Grid has been placed by default in our
window.


.

App.xml and App.xaml.cs are the XAML and coding
files respectively
.

These

produce a Window
program
framework

which gets the application up and running
.
We will not be much concerned with them but
double
-
click

on each
to take a look.

MainWindow.xaml as you have seen contains the markup which describes our controls etc.


MainWindow.xaml.cs
provides an alternative
way of producing our form with buttons etc
. It
also contains the functionali
ty eg events for button clicking etc.

Window.

Grid

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

24

Add An Event Handler

for the button as follows:


o

D
ouble
-
click

on the button and type into

the
button1_Click

event:

.















private

void

button1_Click(
object

sender,
RoutedEventArgs

e)


{


textBox1.Text =
"Hello"
;


}


o

Build and Run.


















o

Remove the button and textbox from the form
above.


o

Take a look at our XAML
produced
so far. It has an opening and closing
Grid

elements>



<

Grid



</
Grid
>



A WPF windows
must

have some sort of container.

We can have a
Gr
id (as above)
, StackPanel,
Canv
as etc.


They have different behaviours

when the Window is resized
etc.


We will
first
consider the
Grid
.

A

grid was placed by default when we drew the button etc. A grid
consists of

cells.

o

Note that as we type we are given
the

name of the
Text Box
.
Double
-
click

on it
(or
just type the full stop)
to accept it
and continue to type the code in yellow below.

o

Click the button.

o

Hello appears.

You could check that the name of the text
box is
textBox1

by inspecting its proper
ties
(or take a look at the XAM
).


For the
differences

and
properties of the various
containers see Troe
lsen
page 1185

We could also create an event handler stub by
going to Properties of the Button , selecting Events
and then double
-
clicking on the Click event.


Also create a new event my going to the XAML and
typing in the
Button

XAML
Click
=
whereupon we
are prompted for a <New Event Handl
er>
etc.



C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

25




















o

In any case,

right
-
click on the form and choose Properties.

































A
s

we will see it is proba
bly actually easier to directly
edit the XAML to achieve the same result.

We might well hav
e drawn one u
sing the
Toolbox.
If you

don’t have a grid draw it now.


o

Choose RowDefinitions and click this
ellipses button.


S
ince we can specify many row widths
we

are
using
a

Collection
.

o

Click Add.

o

Type 45 and click OK .

Our grid now has a
n

extra
row
whose

height

is
45.

o

Click

and drag the
grid's handles if you
wish to resize it.

A 1x1 grid is created by default.


o

Take a look at the XAML
produced:

<
RowDefinition

Height
="45" />


C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

26

Visit
http://www.c
-
sharpcorner.com/beginners/

















After

reading the intro etc…












o

Cut and paste! the code above into our XML so that you should have:








<
Window

x
:
Class
="
MyWPF
.
MainWindow
"



xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"



xmlns
:

="http://schemas.microsof
t.com/winfx/2006/xaml"



Title
="Window1"

Height
="300"

Width
="450"

WindowStyle
="ThreeDBorderWindow">


<
Grid

Name
="MCGrid"

Width
="400"

Background
="LightSteelBlue"

ShowGridLines
="True">

<
Grid.ColumnDefinitions
>


<
ColumnDefinition

/>



<
ColumnDefinition

/>


<
ColumnDefinition

/>


</
Grid.ColumnDefinitions
>


<
Grid.RowDefinitions
>


<
RowDefinition

Height
="45" />


<
RowDefinition

Height
="45" />


<
RowDefinition

Height
="45" />


</
Grid.RowDefinitions
>


</
Grid
>

</
Window
>


T
he

XAML in the
<
Grid

may not be the same
-

so long as it has the closing
>
.
o

Choose Grid in WPF.

o

Make

sure that the
class name is the
same as your project
..

..and the name of your window

matches
the
name of your


Ma
inWindow
.xaml.cs code file.

public

partial

class

MainWi
ndow

:
Window


I
f there is such
inconsistencies when
copying and pasting code
we will get
an error message:

"
The name 'InitializeComp
onent'
does not exist in the current context
".


..and the name of your
namespace
matches in MainWindow.xaml.cs.

namespace

MyWPF


For XAML below:

Use
x

to prefix elements
from that namespace.

xmlns

is the default W
PF
namespace so if an
element has no prefix it is
assumed to be of this
namespace.

We can add our own
namespaces.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

27

1.

Button Control in WPF

2.

Border in WPF

3.

Canvas in WPF

4.

CheckBox in WPF

5.

ComboBox in W
PF

6.

DockPanel in WPF

7.

Drawing Brush in WPF

8.

Ellipse in W
PF

9.

Grid in WPF

10.

Image Viewer in WPF

11.

Label in WPF

12.

Line in WPF

13.

ListB
ox in WPF

14.

ListBox in WPF and XAML

15.

Menus in WPF

16.

MessageBox in WPF

17.

OpenFileDialog in WPF

18.

Path in WPF

19.

Pens in WPF

20.

Polygon in WPF

21.

RadioButton in WPF

22.

Rectangle in WPF

23.

ScrollBar in WPF

24.

Slider Control in WPF

25.

StackPanel in WPF

26.

Tab Control in WPF

27.

TextBox in WPF

28.

Timer in WPF

29.

WrapPanel in WPF

When you run it you should have:





















o

Try
this
Line
i
n WPF

(
hyperlink
)
.
W
e

see here
how as well as directly editing the XAML we can
achieve the same thing pro
grammatically.


o

Slider Control in WPF

-

a good example of handling events.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

28

Following the
previously mentioned
web page, insert the line as shown in y
ellow below.


<
Window

x
:
Class
="MyWPF.MainWindow"



xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"



xmlns
:
x
="http://schemas.microsoft.com/winfx/2006/xaml"



Title
="Window1"

Height
="218"

Width
="282"

WindowStyle
="ThreeDBorderWindow">


<
Grid

Height
="134"

Width
="174"

Name
="Grid1">


<
Button

Content
="Button"

Height
="28"

HorizontalAlignment
="Left"

Margin
="32,68,0,0"



Name
="button1"

VerticalAlignment
="Top"

Width
="98" />


<
TextBox

Height
="23"

HorizontalAlignment
="Lef
t"

Margin
="32,25,0,0"




Name
="textBox1"

VerticalAlignment
="Top"

Width
="97" />


<
Line


X1
="50"

Y1
="50"


X2
="200"

Y2
="200"

Stroke
="Red"

StrokeThickness
="4" />


</
Grid
>


</
Window
>


o

When run we get:



W
e

will now show that we can do exactly the
same thing
a
s

above but
using code.


o

Delete the line of XAML (in yellow) above.


o

As per the web page, copy in this code to MainWindow.xaml.cs.



private

void

button1_Click(
object

sender,
RoutedEventArgs

e)


{


CreateALine();



}



public

void

CreateALine()


{


// Create a Line


Line

redLine =
new

Line
();


redLine.X1 = 50;


redLine.Y1 = 50;


redLine.X2 = 200;


redLine.Y2 = 200;



// Cre
ate a red Brush


SolidColorBrush

redBrush =
new

SolidColorBrush
();


redBrush.Color =
Colors
.Red;


// Set Line's width and color


redLine.StrokeThickness = 4
;


redLine.Stroke = redBrush;


//
Add line to the Grid.


LayoutRoot.Children.Add(redLine);


}



(It would have been a good
idea to delete the text
-
box
-

but only
move

the button
-

we
will now need it in a moment.)

o

Add this call to the sub.

o

Note that
LayoutRoot

is the name the author has given to the grid
. We will do
likewise as follows.
.

If you get a bit
lost, copy and past
in the above
XAML!

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

29

o

Right
-
click on the grid and choose Properties. (Make sure it is not the grid that is highlighted
and not a button etc
-

otherwise you will find yourself looking at the proper
ties of the button etc
instead of the grid.)




















o

As before when we run it we will get:











I
f

we wished the line to be drawn automatically upon start

up we could for example
place it:


public

partial

class

MainWindow

:
Window



{


public

MainWindow()


{


InitializeComponent();


CreateALine();


}



public

void

CreateALine()


{

o

Give the Grid control this name.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

30


1.

Exercise
. Follow
ScrollBar in WPF
.

o

Write some event code which will show the value of the scroll bar in
a label

as the scroll bar
button is moved.


You will need to ascertain the Name of the scroll bar and use its
Value

property as an indication
of the sc
roll button's position horizontally.

and create a
Scroll

event stub:


Change t
he
Content
property of the label to change its "caption".





C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

31


For
More Elaborate Editing
we could download and use Expression Build.

See page 1027 Troelsen.


o

Download Expressi
on Studio. (60 day trial)


http://www.microsoft.com/en
-
us/download/confirmation.aspx?id=5915




o

Run Expression Blend




o

Open MyWPF.sln. (You may need to ascertain where i
t has been saved from Visual Studio)


























You find this event stub



private

void

_myCode(
object

sender, System.EventArgs e)


{



CreateALine();


}




o

1, Select our grid.

o

2. Chose Events
and type a name for
our event handler
_myCode in the
Initialized

event.

o

3. Double
-
click on
our MainWindow code.

o

Add this line which will call our code which we wrote to draw a line.

For example if we wanted to draw a polyline
Expression Blend would allow us to just d
raw it
rather than tediously calculating the
coordinates of the individual line segments. (Or
do we need Expression Design?

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

32














T
he line should be drawn automatically

at start up.













C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

33

XAML

tutorial


page 1154 Troelsen.


Attribute Syntax:


W
h
en writing XAML

use an opening and closing angle bracket.


eg



<
Grid

Height
="200"

/>








The Property
-
Value
S
yntax


(Property.Value syntax)


Equivalently we could wr
ite:



<
Grid
>


<
Grid.Height
>


200


</
Grid.Height
>



</
Grid
>






Result:


Or even:


<
Grid

Height
="200">


</
Grid
>


o

Try each of these:


eg


<
Window

x
:
Class
="WpfApplication3.MainWindow"





xmlns
=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation"



xmlns
:
x
="http://schemas.microsoft.com/winfx/2006/xaml"




Height
="350"

Width
="525">




<
Grid

Height
="200"

Width
="300" />


</
Window
>




The first syntax is the easiest and shoul
d be used where possible

Attribute

Element

Value

Values are always written

with quotes

when using this syntax
.

Now the value need not be a string.

Closing tag.

These are namespaces. They are not web
locations but URI's

ie unique names only.
Much like the
using
.. in C#.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

34

The Property
-
Value
S
yntax

i
s the only alternative when we have more complex ("nested")
properties.


eg



<
Grid
>


<
Grid.RowDefinitions
>


<
RowDefinition

Height
="100*" />


<
RowDefinition

Height
="100
" />


</
Grid.RowDefinitions
>


</
Grid
>



Attached

Property



When the property of an element is in the child element:



<
Grid

Height
="237"

Width
="468">


<
Grid.RowDefinitions
>


<
RowDefinition

Height
="100*" />


<
RowD
efinition

Height
="100" />


</
Grid.RowDefinitions
>


<
Button

Margin
="78,14,325,44"

Grid.Row
="1"

/>


</
Grid
>









RowDefinitions

contains a
collection

of
RowDefinition

properties.

Row

is an attached property since it belongs to the parent class
of Button which is
Grid
. The
Button

is designated as being in
the second row. (Recall that numbering starts at 0.)

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

35

The Content property


Content

replaces

the

Caption

property of Forms.



<
Grid
>


<
Button

Content
="Press"


M
argin
="78,19,290,146" />


</
Grid
>

Bu
t
Content

is more.


eg
it

could be an image or even a
StackPanel
.



<
Grid
>


<!
--

Setting the Content property using property element syntax
--
>


<
Button

Height
="80"

Width
="100">


<
Button.C
ontent
>


<
StackPanel
>


<
Ellipse

Fill
="Red"

Width
="25"

Height
="25"/>


<
Label

Content

="OK!"/>


</
StackPanel
>


</
Button.Content
>


</
Button
>


</
Grid
>









o

Remove the
<
Button.Content
>

and
</
Button.Content
>

tags. The is what is implicitly
between element ta
gs
-

in this case

Button
.

Anything that is contained between the
Button

tags
iscontent. (This is true for any controls that have a
Content

property.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

36

Mar
kup Extensions

Markup extensions are dynamic placeholders for attribute values in XAML.
They resolve the value of a property at
runtime
. Markup extensions are surrounded by curly braces (Example:
Background="{StaticResource
NormalBackgroundBrush}"
). WPF ha
s some built
-
in markup extensions, but you can write your own, by
deriving from
MarkupExtension
. These are the built
-
in markup extensions:



Binding

To bind the values of two properties together.



StaticResource

One time lookup of a resource entry


etc


The
first identifier within a pair of curly braces is the name of the extension. All preceding
identifiers are named parameters in the form of Property=Value. The following example shows a
label whose
Content

is bound to the
Text

of the textbox. When you type
a text into the text box,
the text property changes and the binding markup extension automatically updates the content of
the label.



<
TextBox

Name
="textBox1"

Margin
="65,0,65,100" />


<
Label

Content
="{
Binding

Text
,

ElementName
=textBox1}"

Margin
="6
5,88,65,27" />





An example :


Styles


<
Window

x
:
Class
="WpfApplication3.MainWindow"



xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"



xmlns
:
x
="http://schemas.microsoft.com/winfx/2006/xaml"



Height
="350"

Width
="52
5">




<
Window.Resources
>


<
Style

TargetType
= "Button"

x
:
Key

= "
myButtonStyle
">


<
Setter

Property

= "FontSize"

Value

= "16"/>


<
Setter

Property

= "Foreground"

Value

= "Red"/>


<
/
Style
>



</
Window.Resou
rces
>




<
Grid
>




<
Button

Margin
="168,119,250,152"

Style
= "{
StaticResource

myButtonStyle
}"


>


Help


</
Button
>




</
Grid
>

</
Window
>


Every button created
will have this style

Curly braces
means referencing
another element.

StaticResource

means we are referencing a reource and
myButtonStyle

is a key for that resource.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

37

Comment
s
:


<!
--

--
>


can block out whole elements
-

not just one p
roperty.


We need:


<
Window

x
:
Class
="WpfApplication3.MainWindow"



xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"



xmlns
:
x
="http://schemas.microsoft.com/winfx/2006/xaml"




Title
="MainWindow"

Height
="350"

Width
="525">




<
Grid



<!
--

<TextBlock Name="textBlock1" Margin="0,185,140,46" FontSize="20">


The <Bold> cat</Bold> sat on the mat


</TextBlock>
--
>


</
Grid
>

</
Window
>


otherwise:



For just one property:



<
Window

x
:
Class
="WpfAppli
cation3.MainWindow"



xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"



xmlns
:
x
="http://schemas.microsoft.com/winfx/2006/xaml"



xmlns
:
mc
="http://schemas.openxmlformats.org/markup
-
compatibility/2006"





xml
ns
:
ignore
="http://www.kensingtoncollege.co.uk/ignore"





Title
="MainWindow"

Height
="350"

Width
="525">




<
Grid

mc
:
Ignorable
="ignore">



<
TextBlock


Name
="textBlock1"

TextWrapping
="Wrap"

Margin
="0,185,140,46"


ignore
:
FontSize
="20"
>


The
<
ignore
:
Bold
>

cat
</
ignore
:
Bold
>

sat on the mat


</
TextBlock
>



</
Grid
>

</
Window
>





C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

38

Code can be included in the Markup


<
DockPanel
>


<
Button

Name=
"
btn1
"

Height
=
"
50
"

Width
=
"
200
"

Background
=
"
Red
"

Foreground
=
"
White
"




FontFamily
=
"
Times New Roman
"

FontSize
=
"
14
"

Content
=
"
Red
Button
"

Click
=
"
ButtonClickMethod
"
/>



<
x:Code
>


<![CDATA[




void ButtonClickMethod(object sender, EventArgs e)


{


btn1.Backg
round = Brushes.Green;


MessageBox.Show("Red Button clicked");


}


]]>


</
x:Code
>


</
DockPanel
>


How does X
AML

Work?


The Xaml is parsed to form corresponding classes and properties etc.


For details see:Troelsen page
1148.








<
Window

x
:
Class
="WpfApplication2.MainWindow"


x
:
Class

attribute references the code
-
behind for this particular element.

The
x

means it comes from the XAML namespace.

x
:
Class
…….:

MainWindo
w

tells us that class will be found in this window
MainWindow
.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

39

Bezier


<
Window

x
:
Class
="WpfApplication2.MainWindow"



xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"



xmlns
:
x
="http://schemas.microsoft.com/winfx/2006/xaml"



Title
="Window1"

Height
="300"

Width
="300">


<
Grid

Background
="Azure">


<
Path

Stroke
="Blue"

StrokeThickness
="2" >


<
Path.Data
>


<
PathGeometry
>


<
PathGeometry.Figures
>


<
PathFigureC
ollection
>


<
PathFigure

StartPoint
="
10,100
">


<
PathFigure.Segments
>


<
PathSegmentCollection
>


<
BezierSegment

Point1
="
100,0
"




Point2
="
200,200
"




Point3
="
300,100
"




/>


</
PathSegmentCollection
>



</
PathFigure.Segments
>


</
PathFigure
>


</
PathFigureCollection
>


</
PathGeometry.Figures
>


</
PathGeometry
>


</
Path.Data
>


</
Path
>

<
Path

F
ill
="Gold"

Stroke
="Black"

StrokeThickness
="1">


<
Path.Data
>


<
EllipseGeometry

Center
="10,100"

RadiusX
="5"

RadiusY
="5" />


</
Path.Data
>


</
Path
>



<
Path

Fill
="Gold"

Stroke
="Black"

StrokeThickness
="1">



<
Path.Data
>


<
EllipseGeometry

Center
="100,0"

RadiusX
="5"

RadiusY
="5" />


</
Path.Data
>


</
Path
>


<
Path

Fill
="Gold"

Stroke
="Black"

StrokeThickness
="1">


<
Path.Data
>


<
EllipseGeometry

Ce
nter
="200,200"

RadiusX
="5"

RadiusY
="5" />


</
Path.Data
>


</
Path
>




<
Path

Fill
="Gold"

Stroke
="Black"

StrokeThickness
="1">


<
Path.Data
>


<
EllipseGeometry

Center
="300,100"

RadiusX
="5"

RadiusY
="
5" />


</
Path.Data
>


</
Path
>


</
Grid
>

</
Window


Graphics


see
http://msdn.microsoft.com/en
-
gb/library/ms747393.aspx

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

40

File Handling



page 526 C# 21 Days


Sometimes

we need to save our data onto disk. For example we might save some lines of text or
perhaps a set of numbers or even a picture (bitmap).



Text Files


Writing
:


using

System;

using

System.IO;

public

class

Writing

{


public

static

void

Main()


{


StreamWriter

myFile =
File
.CreateText(
"C:
\
\
text.txt"
);


myFile.WriteLine(
"about time"
);


myFile.Close();


}

}

Write and read

using

System;

using

System.IO;


class

Test

{


public

static

void

Main()


{


string

path =
@"c:
\
Text.txt"
;


try


{


if

(
File
.Exists(path))


{


File
.Delete(path);


}


using

(
StreamWriter

sw =
new

StreamWriter
(path))


{


sw.WriteLine(
"about time"
);





}


using

(
StreamReader

sr =
new

StreamReader
(path))


{


while

(sr.Peek() >= 0)


{


Console
.WriteLine(sr.ReadLine());


}


}


}



catch

(
Exception

e)



{


Console
.WriteLine(
"The process failed: {0}"
, e.ToString());


}


finally








{


Console
.ReadLine();


}



}

}








File

is a class
located w
ithin
the
System.IO

namespace.


CreateText

is a
static method of
the
File

class. It
creates a text file.

StreamWriter

and
StreamReader

classes are used
to create stream objects wh
ich are
then
used to transfer data to and
from the opened file.


Peek

is a method
which

returns the next
character to be read in
the form of an integer.
If there are no more
characters then
-
1 is
returned.

Writes to the file.


using

is just
a
method of making sure
that an object automatically goes out of
scope when the
using

block finishes.


C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

41

To View Our File


In windows 7 onwards debug is no longer available from the c
om
mand prompt.


Try this text editor found at :

http://sourceforge.net/projects/hexbox/?source=dlp

The executable is
Be.HexEditor
.exe.

(This was built using C#. You may wish inspect these fi
les as an exercise.)






















When we open a file for output, it will write over any data that was there before
.



o

Confirm this


save the same file but with different data.






These bytes are the ascii equivalents of the string.


o

The
two bytes
0
d
,
O
a

indicate th
e end of a text file.

o

Double
-
click and then
open the file text.txt on c:

To view the ascii list visit:
http://www.ascii.cl/


C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

42

Binary Files


We saw for text files that letters eg a
and b are written as their ascii equivalent


and so are the
numbers eg 1 is written as 49 (or hex 31). But for a binary file 1 is written as 1.


Writing


o

Run this:


using

System;

using

System.IO;


class

MyStream

{


public

static

void

Main()


{





FileStream

myFile =
new

FileStream
(
"C:
\
\
binFile"
,
FileMode
.CreateNew);


BinaryWriter

bwFile =
new

BinaryWriter
(myFile);



// Write data




for

(
int

i = 0; i < 10; i++)




{




bwFile.Write(i);




}


bwFile.Close();


myFi
le.Close();


}


}
















To avoid an error if the file exists we could use:



string

path =
@"c:
\
binFile"
;



if

(
File
.Exists(path))


{


File
.Delete(path);


}

Each number eg 2 is written as a four byte integer.

After page 532 C# 21 days.

To run the next program from the command line:

Locate the exe file eg mypr
oject.exe.

Open the Visual Studio command prompt. Change to the above located directory.

Type myproject c:
\
binFile as shown.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

43

Reading




See

page 53
3

C# 21 days.


This
program relies on entering “command line arguments”


eg at the command prompt typing












An easier option is to run our
Console Application

as usual but set the command line arguments
like so:







// Exception handling left out to keep
listing short.

using
System;

using
System.IO;


class
BinReader

{


public static void
Main(
String
[] args)


{


if
(args.Length < 1)


{


Console
.WriteLine(
"Must
include
file name."
);


}


else


{



FileStream

myFile =
new
FileStream
(args[0],
FileMode
.Open);


BinaryReader

brFile =
new
BinaryReader
(myFile);



// Read data


Console
.WriteLine(
"Reading file...."
);


while
(brFile.PeekChar() !=
-
1)


{


Console
.Write(
"{0}

"
, brFile.ReadInt32());


}


Console
.WriteLine(
"....Done Reading."
);




Console
.ReadLine();



brFile.Close();


myFile.Close();


}


}

}


args[0]
is
the name of
our program.

arg
s[
1
]
is 2
nd

argument which in this
case is the name
(an
d
location)
of our file.

If

running the program from c:
you will need to find and
transfer your executable
myproject
.exe in this case to c:

From the menu
:

Project,
myproject

options and then Debug and the
command line argument here.

The na
me of the project in this
case is
myproject
.

Make sure your binary editor is not
using the file else you will get an error.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

44

X
ML

Files


Serialization: Page 36
5


375 C# 2008 book. Page 309 PH is an excellent reference.


http://msdn.microsoft.com/en
-
us/library/system.xml.serialization.xmlserializer.aspx


Serializ
ing Objects


This program will write some data to an XML file.































using

System;

using

System.IO;

using

System.Xml.Serialization;


// This is the class that wi
ll be serialized.

public

class

Table1

{


public

string

Name;


public

decimal

Balance;

}

public

class

Test

{


public

static

void

Main()


{


Stream

writer =
new

FileStream
(
"c:
\
\
test.xml"
,
FileMode
.
Create
);


XmlSerializer

serializer

=
new

XmlSerializer
(
typeof
(
Table1
));



Table1

t1 =
new

Table1
();


t1.Name =
"ed"
;


t1.Balance = 10;



serializer.
Serialize
(writer, t1);


writer.Close();


}

}

This indi
cates th
at

xml “format” that
睩ll⁢攠es敤⁴ wri瑥t瑨t⁦il攠瑯tdisc.

T桩s 敮s⁴ 攠eile
f潲⁷riti湧 ⁴ 摩sc.

乯w writ攠eh攠e扪散琠
t1

to the file.

To
serialize

means
to send any
object

to
a file. To
deserialize

means to retrieve it.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

45


o

First Locate our file
test.xml


o

Double
-
click on the file when you locate it. It should open in Windows Explorer or whatever is
the default program for op
ening XML files..
















T
he xml file is of course stored as sequential bytes

ie
serialized
.


If we
use our hex editor to view our

test.xml

stored as ascci
:












<?
xml

version
=
"
1.0
"
?>

<
Table1

xmlns:xsi
=
"
http://www.w3.org/2001/XMLSchema
-
instance
"

xmlns:xsd
=
"
http://www.w3.org/2001/XMLSchema
"
>


<
Name
>
ed
</
Name
>


<
Balance
>
10
</
Balance
>

</
Table1
>

If
Internet explorer by default displays your xml file don’t think that it is HTML. It is
湯琠
-

i琠ts⁘䵌⁢ t⁉ is⁡扬e⁴
format

XML so as well as colour coding your XML
you may see + expanders etc.

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

46

Des
erializing Objects









Exercise Combin
in
g an XML Reader and WPF:


MyXamlPad

project Troelsen page1168






using

System;

using

System.IO;

using

S
ystem.Xml.Serialization;


// This is the class that will be serialized.

public

class

Table1

{


public

string

Name;


public

decimal

Balance;

}

public

class

Test

{


public

static

void

Main()


{


Stream

reader =
new

FileStream
(
"c:
\
\
test.xm
l"
,
FileMode
.
Open
);


XmlSerializer

serializer =
new

XmlSerializer
(
typeof
(
Table1
));



Table1

t1 =
new

Table1
();


t1 = (
Table1
) serializer.
Deserialize
(reader);


Console
.WriteLine(t1.Name +
"
\
t "

+ t1.Balance);


Console
.ReadL
ine() ;


}

}

C:
\
Program Files
\
neevia.com
\
docConverterPro
\
temp
\
NVDC
\
173D6901
-
446B
-
40A0
-
BFA7
-
757F8B3170D1
\
grapedraught_aec8a32a
-
3fbb
-
4c59
-
9101
-
0681b8a65e26.doc

47

To Download
a
n XML Document
f
rom
t
he
Interne
t


using

System;

using

System.IO;

using

System.Xml.Linq;


// This is the class that will be serialized.



public

class

Test

{


public

static

void

Main()


{

XDocu
ment

rss =
XDocument
.Load(
@"http://www.wrox.com/WileyCDA/feed/RSS_WROX_ALLNEW.xml"
)
;


Console
.WriteLine(rss.ToString());


Console
.ReadLine() ;


}

}





.

.

.

.

.













Page 454 C# 2008