Indrumator II
Indrumator II
Industrial Informatics
Author:
Author:
Asist.dr.eng. Emilia-Daniela
Bordencea
Prof.dr.eng. Honoriu
Valean
2012
Contents
Contents
iii
List of Figures
vii
1 Console Applications
1.1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2
C# syntax
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2.1
Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2.2
Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2.3
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2.4
Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2.5
Data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2.6
Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2.7
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2.8
Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3
My first C# application . . . . . . . . . . . . . . . . . . . . . . . . . .
10
1.4
Exercises
15
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
17
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
17
2.1.1
Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
19
2.2
26
2.3
Exercises
27
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
iii
CONTENTS
3 Threads
3.1
3.2
3.3
29
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
30
3.1.1
Creating threads . . . . . . . . . . . . . . . . . . . . . . . . . .
30
3.1.2
Naming Threads . . . . . . . . . . . . . . . . . . . . . . . . . .
31
3.1.3
31
Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
33
3.2.1
Locking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
33
3.2.2
Monitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
34
3.2.3
Mutex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
35
3.2.4
Semaphore . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
35
Exercises
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4 Database
4.1
4.2
4.3
37
39
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
39
4.1.1
Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
40
4.1.2
Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
41
4.1.3
DataReader . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
42
4.1.4
42
4.1.5
DataTable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
42
4.1.6
DataRelation . . . . . . . . . . . . . . . . . . . . . . . . . . . .
42
My first database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
43
4.2.1
45
Exercises
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5 Web Services
48
49
5.1
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
50
5.2
53
5.3
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
55
57
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
58
6.1.1
Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
59
6.1.2
Layouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
62
iv
CONTENTS
6.2
62
6.2.1
62
6.2.2
Styles in WPF . . . . . . . . . . . . . . . . . . . . . . . . . . .
63
6.2.3
Data Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . .
65
6.3
Animations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
66
6.4
Exercises
68
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Bibliography
69
CONTENTS
vi
List of Figures
1.1
10
1.2
Solution Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10
1.3
IntelliSense feature . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12
1.4
Hello C# Application . . . . . . . . . . . . . . . . . . . . . . . . . . .
13
1.5
13
2.1
17
2.2
Form Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
18
2.3
My First Button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
20
2.4
. . . . . . . . . . . . . . . . . . . . . . .
23
2.5
24
2.6
String concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . .
25
3.1
Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
29
3.2
32
4.1
39
4.2
Creating a database in C# . . . . . . . . . . . . . . . . . . . . . . . .
40
4.3
Creating a database in c# . . . . . . . . . . . . . . . . . . . . . . . . .
43
4.4
46
5.1
49
5.2
50
5.3
Solution Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
51
vii
LIST OF FIGURES
5.4
Web Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
52
5.5
53
5.6
53
5.7
54
6.1
58
6.2
WPF button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
59
viii
Chapter 1
Console Applications
This chapter presents the basic programming concepts in C# by introducing some
console applications.
1.1
Introduction
1. Console Applications
1.2
C# syntax
This language inherits the C++ syntax and programming principles. Furthermore,
some new data types and methods were added, modified or dumped.
1.2.1
Identifiers
The identifiers are used to indicate variables, data types, symbolic constants or methods. The first character of an identifier must be a letter or underline, and its maximum
length cannot exceed 31 characters.
1.2.2
Keywords
The keywords are predefined identifiers with special meaning for the compiler. The
C# keywords are presented below:
abstract
as
base
bool
break
byte
case
catch
char
checked
class
const
continue
decimal
default
delegate
do
double
else
enum
event
explicit
extern
false
finally
fixed
float
for
foreach
goto
if
implicit
in
int
interface
internal
is
lock
long
namespace
new
null
object
operator
out
override
params
private
protected
public
readonly
ref
return
sbyte
sealed
short
sizeof
stackalloc
static
string
struct
switch
this
throw
true
try
typeof
uint
ulong
unchecked
unsafe
ushort
using
virtual
void
volatile
while
Generally, the keywords cannot have a different meaning in our programs. However,
in order for them to have another meaning, they must contain the symbol @ as a prefix.
2
C# syntax
1.2.3
Variables
// D e c l a r e
int a ;
// I n i t i a l i z e
a =1;
// D e c l a r e and i n i t i a l i z e
i n t c =1;
// M u l t i p l e v a r i a b l e can be d e c l a r e d i n one s t a t e m e n t i f
they have t h e same type
i n t first , second ;
// D e c l a r e and i n i t i a l i z e
i n t bfirst =1 , bsecond =2;
8
9
10
1.2.4
Constants
The constants are values which cannot change. They can be declared by using the
const or the readonly modifier.When local variables or fields are declared using the
const modifier, they must be initialized. The constants are implicitly static.
1 c o n s t i n t ct = 3 ;
On the other hand, the readonly fields can be initialized within a constructor.
1 // I n i t i a l i z e a r e a d o n l y f i e l d
2 p u b l i c r e a d o n l y i n t ct = 3 ;
3 p u b l i c r e a d o n l y i n t cnt ;
4
5 p u b l i c myC ( )
6
// I n i t i a l i z e a r e a d o n l y i n s t a n c e f i e l d
cnt = 4 ;
1. Console Applications
1.2.5
Data types
Reference types
Examples: class, interface, delegate, string, object and array.
Note: You might observe that C# contains two types of strings, string and String,
and you also might wonder what is the difference. Technically, excepting a few small
differences, there are the same (string is an alias for System.String). Then, maybe you
are wondering when it is recommended to use one or the other. Generally, you can
use string when you refer to an object (string mystr="hi";) and you can use String
when you refer to the class (string reply = String.Format("0", mystr);). Among the
differences, we have:
String is a class name while string is a restricted keyword,
String belongs to the .NET platform (is accessible in all languages), while string
is language specific (C#).
4
C# syntax
The arrays are zero indexed in C# and they work almost the same as in other
languages.
The declaration is:
1 i n t [ ] array ; // not i n t a r r a y [ ] ;
Note: It is not legal to place the brackets after the identifier in C#.
C# supports:
single-dimensional arrays,
multidimensional arrays (rectangular arrays),
array-of-arrays (jagged arrays).
1. single-dimensional arrays
The declaration is:
1 i n t [ ] myArray ;
The array is declared but not created. For creating the arrays, it must be
instantiated.
1 i n t [ ] myArray = new i n t [ 1 0 ] ;
byt e [ ] [ ] scores ;
scores = new byte [ 5 ] [ ] ;
f o r ( i n t x = 0 ; x < scores . Length ; x++)
{
scores [ x ] = new byte [ 4 ] ;
}
You can have three-dimensional rectangular arrays or mix rectangular and jagged
arrays.
5
1. Console Applications
1 i n t [ , , ] buttons = new i n t [ 4 , 5 , 3 ] ; // t h r e e d i m e n s i o n a l r e c t a n g u l a r
array
2 i n t [ ] [ , , ] [ , ] numbers ; // s i n g l e d i m e n s i o n a l a r r a y o f t h r e e
d i m e n s i o n a l a r r a y s o f twod i m e n s i o n a l a r r a y s o f type i n t
1.2.6
Operators
The operators are used for specifying which operations should be performed in an
expression.
Assignment and Equality Operators
=
Assigns a value
==
Increment variable v by 1
v += n
v *= n
Multiply variable v by n
v -= n
Addition
Subtraction
Multiplication
Division
Modulus
&
Logical AND
Logical XOR
Logical OR
6
C# syntax
The arithmetic expression evaluation is performed from the left side to the right
side, taking into account the order of regular assessment.
Logical Condition Operators
&&
Conditional AND
||
Conditional OR
Conditional NOT
The && operator has higher priority than the || operator and smaller priority than
the comparison operators. In && and || operations, the terms used represent bool
values.
Note: The rule from C, in which a numerical value different than 0 is true and a
value equal to 0 is false, is not valid in C#.
Relational operators
==
!=
>
Greater than
<
Less than
>=
<=
Conversions
Data type conversion can be performed by using cast.
1
2
3
4
5
int a = 5;
float b = 0;
b = a ; // An i m p l i c i t c o n v e r s i o n . The data w i l l not be l o s t .
b = 0.9 F ;
a = ( i n t ) b ; // An e x p l i c i t c o n v e r s i o n . The data w i l l be l o s t .
An expression can be converted from one type to another by using Convert class
methods. For instance:
i n t m = Convert . ToInt32 ( 1 2 4 . 4 5 6 ) ;
1. Console Applications
In order to convert strings to some other types, .Parse can be used. There are, for
example, strings which contain digits. In order to use the numerical value, the string
should be converted to an integer.
1
2
1.2.7
Comments
In the case of all the programming languages, for explaining the meaning of different
methods or variables, the programs can contain text under the form of comments. The
following types of comments [3] can be used in C#:
Single line comments // one line comment;
Multiple line comments, used especially for debugging / multi line comments/;
XML tag comments /// XML tag comments.
Single line comments are used in the majority of cases.
Shortcuts: Ctrl+K and then Ctrl+C to comment selected lines of text and
Ctrl+K and then Ctrl+U to uncomment.
1.2.8
Files
sw . Close ( ) ;
C# syntax
Reading from a file:
s t r i n g line = sr . ReadLine ( ) ;
sr . Close ( ) ;
c h a r [ ] separator = { } ;
Note: When you want to clear the buffer and leave the stream open, you can use
StreamWriter.Flush(). This method writes the current contents of the buffer to the
file. In order to close the stream, you can use StreamWriter.Close(). This method
internally calls flush() method and before closing the stream it flushes the Steeam for
the last time. Invoking the flush method makes sure that the memory contents are
persisted to disk; thus, the buffer data is not lost in case the process or machine fails.
1. Console Applications
1.3
My first C# application
The way to create a console application is fairly simple: select File New Project
Visual C# Console Application (Figure 1.1). The project can be renamed and
the location of the project can be changed.
My first C# application
In Listing 1.1, the structure of a C# program is presented.
using
using
using
using
System ;
System . Collections . Generic ;
System . Linq ;
System . Text ;
namespace myFirstApp
{
c l a s s Program
{
s t a t i c v o i d Main ( s t r i n g [ ] args )
{
}
}
}
This is the code that is executed when the application is running. The first line
(using System) is a directive which specifies that some of the System namespace classes
will be used. MyFirstApp is the applications name. There also exists a class Program
which contains the Main method.
Therefore, a C# application consists of one or more classes, grouped in namespaces.
Lets take a look at the code. Only one of the classes must contain an entry point (the
Main method).
Convention: The following writing convention is also adopted in C#: if names
consisting of several words are used, each word is capitalized: HelloWorld, WriteLine.
The convention is called the Pascal Convention. The Camel Case Convention is similar,
except that the first character of the first word is lowercase.
Lets make a simple console application. Write a simple program as in Figure 1.4.
You can observe that you are assisted by the IntelliSense (Figure 1.3), the feature
which helps you to automatically generate the code in the Code Editor.
11
1. Console Applications
To compile the program, select Build Build Solution from the main menu or
press F6. If errors exist, they will be displayed in the Error List window.
There are many ways to run the program:
Step Into (F11) and Step Over (F10) (running step by step)
Toggle Breakpoint (F9) and then Start Debugging (runs fast until the breakpoint
line marked).
Stop Debugging (Shift+F5) exits from the debugging mode and returns to the
normal one. All these options are available in the Debug menu of the programming
environment.
The application code and its result are shown in Figure 1.4.
12
My first C# application
As it can be seen, the last line of the code contains Console.ReadKey(). This line
is used for keeping the console open until a key is pressed. If this line is not present,
the program will be executed and then the console will close.
You can also run the program only using the .exe file from /bin/debug. The result
can be seen in Figure 1.5.
1. Console Applications
The Console class methods from the System namespace are used in Console Applications. Among the most widely used we have:
Write - writes a message to the console;
WriteLine - writes a message to the console and moves to a new line;
ReadLine - reads a line of text from the keyboard and moves to a new line.
There are two ways of using the Write and WriteLine methods:
1. Console.WriteLine(value), where value can be of any type (int, string, char,
double, and so on) allows direct display. An example is presented below:
1
2
3
4
5
6
s t a t i c v o i d Main ( s t r i n g [ ] args )
{
int b = 34;
char c = a ;
Console . WriteLine ( " {0} i s {1} " , c , b ) ;
Console . ReadKey ( ) ;
}
It means that the first parameter (here c) is the second parameter (here b).
All the data read from the keyboard are strings. Other types of data are read by
converting the strings into the desired types.
1
14
Exercises
1.4
Exercises
15
1. Console Applications
16
Chapter 2
Getting started
Microsoft Visual C# contains specialized tools, which offer the possibility to create
applications in an interactive, quick and easy way. In order to create Form Applications
click File New Project Visual C# and then select Windows Form Application.
18
Getting started
Listing 2.1: The Program class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using
using
using
using
System ;
System . Collections . Generic ;
System . Linq ;
System . Windows . Forms ;
namespace MyFirstForm
{
s t a t i c c l a s s Program
{
// / <summary>
// / The main e n t r y p o i n t f o r t h e a p p l i c a t i o n .
// / </summary>
[ STAThread ]
s t a t i c v o i d Main ( )
{
Application . EnableVisualStyles ( ) ;
Application . SetCompatibleTextRenderingDefault ( f a l s e ) ;
Application . Run ( new Form1 ( ) ) ;
}
}
}
The application is executed in the same way as a Console Applications (see chapter
Console Applications).
All the windows contain in the right side a drawing pin, which, if opened, sets
the window upright. Otherwise, the window closes, retreating to the programming
environments right or left side.
2.1.1
Controls
19
Description
used for executing a sequence of instructions when their are activated by the user
displays a calendar of the current month
yes/no option
used for printing text label
displays a list of articles from where the user can choose
used for adding images
used for selecting, moving or scaling a control
gives the possibility of choosing one element from a cluster of
selections
displays the text generated by an application or gives the possibility to introduce a text
Buttons
First, lets create a Form Application, as in Figure 2.3, which contains a button.
For doing this, go to Toolbox and expand Common Controls. Select the Button
element and move the cursor somewhere on the surface of your form.
All the controls have properties. Select the Text property and modify the text that
20
Getting started
will appear on your button in My Button. The form has also a lot of properties. Click
the form and change the text to My First Form. Then change the form size. After
you solve these three requirements, the Form should look like in Figure 2.3.
Further, lets add a function to our button. Thus, when the button is clicked, a message box should be displayed. How do we do this? First, double-click on the button.
This will automatically generate in the Form code a method called button1_Click.
Button1 is the default button name (because we did not changed the property name
of the button) and _Click is an event. Some other events examples are MouseDown,
LocationChanged, TextChanged, and so on. Object sender, EventArgs e are known as
arguments. One argument is called sender and the other is called e.
As it was said in the beginning, we want to display a message box containing some
text. This is quite simple to be done in C# as it can be seen in the source code,
presented in Listing 2.2.
Listing 2.2: Display a MessageBox which contains some text
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using
using
using
using
using
using
using
using
System ;
System . Collections . Generic ;
System . ComponentModel ;
System . Data ;
System . Drawing ;
System . Linq ;
System . Text ;
System . Windows . Forms ;
namespace MyFirstForm
{
p u b l i c partial c l a s s Form1 : Form
{
p u b l i c Form1 ( )
{
InitializeComponent ( ) ;
}
p r i v a t e v o i d button1_Click ( o b j e c t sender , EventArgs e )
{
MessageBox . Show ( " Message " , "My F i r s t Msg " ) ; // d i s p l a y s
a window with t h e name "My F i r s t Msg " and a
message " Message " . I f "My F i r s t Msg " i s omitted ,
t h e window w i l l not have any name .
21
}
22
}
23 }
21
Text boxes
Herein, the text and numerical variables will be introduced. What is a variable? It is
a storage area for things that you will need later on. They can be seen as boxes, which
are empty until something is put inside. They can be labeled for not being confused.
To understand what is going on, a small program will be written. It takes the text
from a text box, retains it in a variable and then displays it through a message.
Thus, create a new Windows Form Application project and rename it as you wish.
Add a button having the following properties:
Name: myBtn
Location: 80,160
Then add four more controls: two Labels and two TextBoxes. The Form should
look as the Form from Figure 2.4. Note the fact that the second TextBox is ReadOnly.
22
Getting started
In order to see the way the result looks like, save the project files (File Save
All) and then run it. In this moment, even if you will press the button, nothing will
happen.
So, lets add an event for the button. Therefore, when the button is pressed, the
text from the first text box is taken and displayed in the second one. The code is
listed below.
1
2
3
4
5
6
Run the project and type a text in your first text box. Press the button and you
will obtain a form as in Figure 2.5.
23
24
Getting started
3
4
5
6
7
Numerical variables
Suppose that a variable contains a numerical value. Display the value in a message
box.
1
2
3
4
5
When you try to display the number by using the above code, you can observe
that it generates errors. Why is that? The MessageBox displays only text and your
variable is integer. C# does not convert a number in string without this action being
specified. In order to correct the problem, the number should be converted to string
25
2.2
Generally, the applications contain more than one form. There exists a main form
from where you can start to navigate through the secondary ones. Thus, create a new
Windows Form Application which contains a form consisting of a button. When the
button is pressed another form should be opened. How can we do this?
In order to add a new form to the project, select Project Add Windows Form.
Now, you have a project containing two forms. But how will you connect them?
Add a button with any properties to your first form. The forms are represented by
classes. Thus, the object of the first form is automatically created when the program
is started. For the second one, it should be manually created, as follows:
1
2
3
4
5
By using the above code, the second form will appear each time you will click the
button. To make the form appear only once, move the code which creates the form
outside of the method.
26
Exercises
2.3
Exercises
1. Create a login window (the user and password are read from a file) which opens
a new form. The second form will contain the "Hello username!" label and the
Exit button.
2. Populate a list object with the words found on the individual lines of a file and
create a selecting and copying mechanism in another list.
3. Create a form which contains two listBoxes and two buttons. When you press
the first button, the selected item/items from the first listBox will be added to
the second one. When the second button will be clicked, all the item from the
second listBox will be deleted.
4. Create a calculator which contains three textBoxes (two of them are used for
introducing the numbers and the third one is for the result) and in a menu, the
binary operators. (Indication: use MenuStrip).
5. Create a forms which contains a TabControl with two pages. The first page has
a listBox which contains different items (for instance: car names, cities names
and so on). When an item is selected, an image will appear on the form. The
second page has two radioButton groups. Select one radioButton from the first
group and one from the second one and print the result in a MessageBox.
27
28
Chapter 3
Threads
The task execution time depends on the task complexity, thus complex tasks require
longer execution time. Therefore, in order to eliminate the process waiting time, the
concurrent task execution is required. The complex applications can split their jobs in
chunks, which can run independently and simultaneously. The chunks, called threads,
can run by themselves. A thread is defined as a sequential set of instructions designated
to execute tasks in a process. It can be compared to a sequential process. These
threads are often named light processes. However a thread can operate only as part
of a process. Thus, a process can define multiple threads allowing the simultaneous
execution of various operations.
3. Threads
3.1
Getting started
3.1.1
Creating threads
All programs contain a main thread which represents the Main method. There are
many ways of creating threads, but the simplest one is represented by the use of a
Thread object and of a ThreadStart delegate, where Thread is used for creating and
managing threads while ThreadStart contains the code executed when the thread is
alive. In order to use threads, the System.Threading directive must be imported.
Listing 3.1 creates a thread which prints "Hello! I am a thread." in console.
Listing 3.1: Creating a thread
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using
using
using
using
using
System ;
System . Collections . Generic ;
System . Linq ;
System . Text ;
System . Threading ;
namespace Threads
{
c l a s s Program
{
s t a t i c v o i d CreatingThread ( )
{
Console . WriteLine ( " H e l l o ! I am a t h r e a d . " ) ;
}
s t a t i c v o i d Main ( s t r i n g [ ] args )
{
ThreadStart ts = new ThreadStart ( CreatingThread ) ;
Thread myFirstThread = new Thread ( ts ) ;
myFirstThread . Start ( ) ;
}
}
}
30
Getting started
3.1.2
Naming Threads
A thread can be identified by using the Thread.Name property. The name of a thread
can be set only once. A later attempt to change the name will throw an exception.
The static Thread.CurrentThread property returns the currently executing thread.
Listing 3.2 contains a program which creates two threads: main and worker. When
a thread starts, it has its IsAlive property true till the end. If a thread is stopped, it
cannot be restarted.
Listing 3.2: Creating two threads
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using
using
using
using
using
System ;
System . Collections . Generic ;
System . Linq ;
System . Text ;
System . Threading ;
namespace Threads
{
c l a s s Program
{
s t a t i c v o i d Main ( )
{
Thread . CurrentThread . Name = " main t h r e a d " ;
Thread worker = new Thread ( Hi ) ;
worker . Name = " worker t h r e a d " ;
worker . Start ( ) ;
Hi ( ) ;
Console . ReadKey ( ) ;
}
24
25
26 }
s t a t i c v o i d Hi ( )
{
Console . WriteLine ( " Hi from " + Thread . CurrentThread .
Name ) ;
}
}
3.1.3
There are cases where a thread should wait for another thread to finish its task. This
can be done by using the Join method. The thread which calls Join() will be in
the waiting state until the other threads finish. In order to understand the Join()
31
3. Threads
statement, the example from listing 3.3 will be considered.
Listing 3.3: Join method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using
using
using
using
using
System ;
System . Collections . Generic ;
System . Linq ;
System . Text ;
System . Threading ;
namespace Threads
{
c l a s s Program
{
s t a t i c v o i d Main ( )
{
Thread . CurrentThread . Name = " main t h r e a d " ;
Thread worker = new Thread ( Hi ) ;
worker . Name = " worker t h r e a d " ;
worker . Start ( ) ;
worker . Join ( ) ;
Hi ( ) ;
}
26
27
28
29 }
s t a t i c v o i d Hi ( )
{
f o r ( i n t i = 1 ; i <= 5 ; i++)
{
Console . WriteLine ( " Hi from " + Thread . CurrentThread
. Name ) ;
}
}
}
Synchronization
In some other cases maybe, a thread should wait a period of time. This can
be achieved by calling the Sleep method which will pause the thread for a specified
amount of time.
1 Thread . Sleep ( 1 0 0 0 ) ; // p a u s e s t h e t h r e a d f o r 1000 m i l l i s e c o n d s
2 Thread . Sleep ( TimeSpan . FromHours ( 2 ) ) ; // p a u s e s t h e t h r e a d f o r 2
hours
When the Sleep and Join methods are called, the corresponding threads do not
consume CPU resources.
3.2
Synchronization
The synchronization enables the programmer to control the access to shared resources.
The best way is to try to avoid synchronization, but this is not possible all the time.
There are applications where two or more threads should access the same data or
execute the same piece of code. Thus, in these kind of applications, synchronization
is necessary. This is because only one thread can access or change the data at a time.
3.2.1
Locking
In threading programs, the use of locking is necessary. Executing the same code by
different threads at a time can make the program unreliable. Locking is used to ensure
that a shared resource is not accessed by more than one thread at a time. When a
thread wants to enter a portion of locked code, it is blocked until the resource is
released.
Thus, the use of lock statement ensures that a thread not access a block while
another thread is already in that section, called critical section. When a thread wants
to access a locked block, it will wait till the block will be released. By calling Enter,
the block will be locked and the lock will be released by calling, at the end of the
block, Exit.
The lock syntax is the following:
l o c k ( expression )
33
3. Threads
3
instructions ;
When we are talking about blocking threads, we are thinking of threads whose
execution is paused due to some reasons (for instance, Sleep() call or waiting a thread
to end). ThreadState checks the state of the thread (if it is blocked or not).
3.2.2
Monitor
A Monitor is an advanced version of Lock. It performs the same action as Lock, but
the shared data is synchronized at run time. The mutual exclusion is automatically
provided by Monitor, while Lock just focuses on it. Moreover, the Monitor has the
Wait and Pulse command which prevent spinning. Thus, Wait is used to block the
thread until it receives a notification from another thread while Pulse provides the
notification.
1
2
3
4
5
6
7
8
9
The Monitors are used to ensure that when a thread performs a read/write/increment
operation, no one of the other threads does the same. A Monitor is actually a lock
attached to a resource in order to prevent the parallel use of the resource. When a
thread holds a Monitor, no other thread can hold it. All the other threads that want
34
Synchronization
to use the lock are blocked and they have to wait till the thread releases the lock.
The Monitor class contains methods for controlling the threads synchronization.
They may allow the declaration of critical areas, where, at a time, only one thread can
operate. When you want to start synchronization, call the Enter method, specifying
the object which will be blocked. If the Monitor is not available, it means that another
thread is currently in the critical region of the respective object. The critical area can
be closed by using Exit(). The compiler places the Exit() method in the final section
of a try block, so the monitor is released if an exception is thrown.
3.2.3
Mutex
A Mutex is different than a C# lock because it can be used for synchronizing between
multiple processes. A Mutex, with a name assigned to it, is known by the operating
system and is shared between different processes. Thus, a Mutex can be defined in
different processes.
It is used to ensure that, at some time, only a certain piece of code is executed. In
order to obtain the lock, the WaitOne method is used and in order to release it, the
ReleaseMutex is used.
Create a form application which contains a button. When the button is clicked, a
new mutex instance will be created. If two instances with the same name exist, the
application exits. The code is presented in the following:
1
2
3
4
5
6
7
8
b o o l _new ;
Mutex mutex = new Mutex ( f a l s e , " s t r i n g name " , out _new ) ;
i f ( ! _new )
{
MessageBox . Show ( " Only one i n s t a n c e can be s t a r t e d ! " ) ;
Application . Exit ( ) ;
return ;
}
3.2.4
Semaphore
The Semaphore class is very similar to Mutex, only that, the number of threads which
have access to a shared resource can be set. The semaphore has two arguments: the
number of slots that are initially available and the maximum number of slots.
35
3. Threads
When the capacity is one, the semaphore is similar to Mutex. However, a semaphore
can be released by any thread, while a Mutex or a Lock can be released only by the
thread which holds it.
The semaphores can be used to limit the competition. This means that, a particular
piece of code cannot be used by too many threads simultaneously.
Note: In .NET 4.0, the Semaphore and SemaphoreSlim classes are available.
The following code creates a semaphore with a maximum of four slots. The initial
count is 0, which means that the main thread holds the semaphore.
The methods for locking and releasing are the same as for Mutex, namely the
Wait() and the Release() methods.
Example:
Listing 3.4: Synchronization using semaphore
1
2
3
4
5
6
7
8
c l a s s Program
{
s t a t i c i n t threadNr = 1 0 ;
s t a t i c i n t semCount = 5 ;
s t a t i c v o i d Main ( s t r i n g [ ] args )
{
f o r ( i n t i = 1 ; i <= threadNr ; i++) new Thread ( Enter ) .
Start ( i ) ;
}
9
10
11
12
13
14
15
16
17
18
19
20
21
s t a t i c v o i d Enter ( o b j e c t id )
{
Console . WriteLine ( id + " s a y s h i ! " ) ;
semaphore . Wait ( ) ;
Console . WriteLine ( id + " s a y s bye ! " ) ;
Thread . Sleep ( 1 0 0 ( i n t ) id ) ; Console . WriteLine ( id + "
i s going o f f l i n e " ) ;
semaphore . Release ( ) ;
}
}
36
Exercises
3.3
Exercises
1. Create another thread besides the main thread. Both of them will display the
numbers from 1 to 10 in the same time.
2. Modify the first exercise so that the main thread waits for the other one to finish
before starting his job.
3. Modify the first exercise so that the main method will display a new number at
every 3 seconds and the other thread at every 1 second.
4. Modify the third exercise so that when the created thread finishes, the main
thread will stop.
5. Create another two threads besides the main thread. Then increment on each
thread a value and on each increment make a sleep.
37
3. Threads
38
Chapter 4
Database
4.1
Getting started
ADO.NET (Active Data Objects for .NET) is a .NET Framework component which
allows the connection to various data sources, data retrieval and manipulation. Usually, the data source can be a database, but it can also be a text file, Excel, XML or
Access. In the traditional databases, the connection is maintained during the entire
process. Using ADO, working with databases can be performed while connected or
disconnected. Disconnected means that the applications can connect to the database
only for retrieving or updating data. In this case, the number of simultaneous open
connections can be reduced.
39
4. Database
4.1.1
Connection
It represents the creation of a connection to the database. The connection types are:
the SqlConnection object, designed for SQL Server 7.0 or later,
the OleDbConnection object, designed for Microsoft Access and Oracle.
All the information required for establishing a connection with the database are
provided by the Connection object.
Opening database connection:
1 u s i n g System . Data . SqlClient ;
2 . . .
3 SqlConnection myCon=new SqlConnection ( " Data S o u r c e=s e r v e r D b ;
Database=dbName ; User ID=u s e r I d ; Password=p a s s " ) ;
4 myCon . Open ( ) ;
5 . . .
Where:
serverDb is the MSSQL server host;
dbName is the name of the database;
40
Getting started
userId is the user name;
pass is the user password.
Methods
1. Open(): opens the database connection;
2. Close(), Dispose(): close the database connection;
3. BeginTransaction(): used for executing a transaction. At the end call the Commit or Rollback methods;
4. ChangeDatabase(): changes the database with a new one from the same server;
5. CreateCommand(): creates a valid command.
4.1.2
Commands
The command objects are used for executing commands on the database. They can
execute SQL commands, such as: SELECT, INSERT, UPDATE or DELETE. It is
mandatory that the connection to the database to be open.
1 SqlCommand cmd = new SqlCommand ( "SELECT FROM dbName " , myCon ) ;
Methods
1. Constructors: a command object can be created through a constructor call;
2. Cancel(): stops a command;
3. Dispose(): kills the command object;
4. ExecuteNonQuery(): executes a command which does not return a set from the
database;
5. ExecuteReader(): executes the command from the CommandText property and
returns a DataReader object;
6. ExecuteScalar(): returns a single value from the database query.
41
4. Database
4.1.3
DataReader
The data from a database can be read by using DataReader. It is a read-only command
and in order to modify data in a table DataSet+DataAdapter should be used.
4.1.4
After setting up the connection to the database, the records from the database should
be retrieved. The data retrieved from the database is held in a DataSet, which is filled
with records by using DataAdapter. The DataAdapter command is used because the
DataSet and the Connection cannot see each other.
Two objects should be created:
4.1.5
DataTable
DataTable is used for storing tables, which can differ from a database table. Therefore,
if a line is modified, added or deleted, the data table within the database is not
modified. The line will just be marked as being modified, added or deleted. In order
to accept the modifications, the DataTable.AcceptChanges() method can be used.
4.1.6
DataRelation
DataRelation is used for creating parent-child relations between two tables. For instance:
1 myDS . Relations . Add ( myDS . Tables [ " Table1 " ] . Columns [ " i d " ] , myDS . Tables
[ " Table2 " ] . Columns [ " i d " ] ) ;
42
My first database
4.2
My first database
Next, you will learn how to create a relational database by using Visual Studio. The
database will contain two tables: Universities and Faculties.
Before creating the project, launch SQL Server Configuration Management from
Start Programs Microsoft SQL Server 2008 Configuration Tools and check if
the SQL Server is running. This action must be performed because of the fact that
the database is hosted by SQL Server.
Then, create a Windows Form Application called myDatabase and right click on
Solution Explorer. Next, select Add New Item Service-Based Database, as in
Figure 4.3. Now, you have created a database. In order to configure your database
expand the Server Explorer menu (as mentioned in Chapter 1, the menu can be made
visible by clicking on View Solution Explorer). In the database, right click on
Tables and then select Add New Table. Then, create two tables with the structure
43
4. Database
Table 4.1: Universities
Column name
Id
NameUniv
City
Code
Data type
int
text
text
int
Allow Nulls
No
No
No
No
Data type
int
text
Allow Nulls
No
No
44
My first database
4.2.1
After you set up the Connection object, the ConnectionString property can be
accessed. Thus, select Data Show Data Source and then Add New Data Source
Database Dataset. You are new able to Choose your Data Connection.
You will see the window illustrated in Figure 4.4.
If you do not find any connection or you want to use a new one, click the New
Connection button and then select Microsoft SQL Server Database File, Continue and
then browse to the database location.
You will find the seeking string (example: "Data Source=.
SQLEXPRESS;AttachDbFilename=kDataDirectoryk
Database1.mdf;Integrated Security=True;User Instance=True") by expanding Connection String.
After your SqlConnection line, add the following code:
When you add this code in C# you will notice that errors are signaled. This
45
4. Database
Next, you can open a connection to the database by using myCon.Open() and you
can close the connection by using myCon.Close().
Now, lets see a simple example. Considering the relational database already created, display in a ListBox all the Universities, in a TextBox the university code and
in another the corresponding faculty.
46
My first database
Listing 4.2: Example
1 p r i v a t e v o i d Form1_Load ( o b j e c t sender , EventArgs e )
2
{
3
myCon . Open ( ) ;
4
dsUniv = new DataSet ( ) ;
5
dsFac = new DataSet ( ) ;
6
7
dsUniv = new SqlDataAdapter ( "SELECT from U n i v e r s i t i e s " ,
myCon ) ;
8
daUniv . Fill ( dsUniv , " U n i v e r s i t i e s " ) ;
9
10
daFac = new SqlDataAdapter ( "SELECT from F a c u l t i e s " , myCon )
;
11
daFac . Fill ( dsFac , " F a c u l t i e s " ) ;
12
13
f o r e a c h ( DataRow dr i n dsUniv . Tables [ " U n i v e r s i t i e s " ] . Rows )
14
{
15
String name = dr . ItemArray . GetValue ( 1 ) . ToString ( ) ;
16
listBox1 . Items . Add ( name ) ;
17
}
18
}
19
20 p r i v a t e v o i d listBox1_SelectedIndexChanged ( o b j e c t sender , EventArgs
e)
21
{
22
String UnivSelected = listBox1 . SelectedItem . ToString ( ) ;
23
24
f o r e a c h ( DataRow dr i n dsUniv . Tables [ " U n i v e r s i t i e s " ] . Rows )
25
{
26
i f ( UnivSelected == dr . ItemArray . GetValue ( 1 ) . ToString ( ) )
27
{
28
textBox1 . Text = dr . ItemArray . GetValue ( 2 ) . ToString ( ) ;
29
code = Convert . ToInt16 ( dr . ItemArray . GetValue ( 2 ) ) ;
30
}
31
}
32
33
f o r e a c h ( DataRow dr i n dsFunctii . Tables [ " f u n c t i i " ] . Rows )
34
{
35
i f ( code == Convert . ToInt16 ( dr . ItemArray . GetValue ( 0 ) ) )
36
{
37
textBox2 . Text = dr . ItemArray . GetValue ( 1 ) . ToString ( ) ;
38
}
39
}
40
myCon . Close ( ) ;
41 }
47
4. Database
4.3
Exercises
1. Using the database already created, insert and delete a new record to/from the
database. Next, modify and search an existing record.
2. Create a relational database named myDatabase with two tables. Then insert by
code at least 6 lines for each table. The values will be read from the keyboard.
Implement a WindowsApplication which allows the user to insert and delete a
record.
48
Chapter 5
Web Services
A web service is a collection of protocols and standards used for communicating between two devices via Internet. It is based on the client-server model thus: the server
exposes some methods and the client connects to the server in order to use the methods. The idea is to create components such as black boxes that can interact, without
taking into account the operating system or programming language. More precisely,
the web service is a component or a module of executable code with a special interface
that makes the methods to be available for other programs using a HTTP request.
The request is made by using HTTP GET, HTTP POST and Simple Object Access
Protocol (SOAP).
5. Web Services
Therefore, the methods or the messages can be published in order to be used
from everywhere. For coding the data, web service uses Extensible Markup Language
(XML) and for transporting it, an XML-based protocol called SOAP [4]. SOAP is
used in applications which need to exchange information over HTTP. A web service
can be located by using Web Service Definition Language (WSDL).
5.1
Getting started
Note: All the examples are done by using Visual Studio 2010 Ultimate. Starting
with .Net Framework 4.0, ASP.NET Web Service Application template is not available
anymore. However, you can create a web service targeting the .NET Framework 3.5
as in figure 5.2. Then, you can reuse .NET Framework 4.0 by re-targeting to .NET
Framework 4.0 from the project properties.
Getting started
Explorer (see Figure 5.3).
Notice that the wizard has created a project which contains the Service1 class with
the following implementation.
Listing 5.1: Hello World Web Service
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using
using
using
using
using
System ;
System . Collections . Generic ;
System . Linq ;
System . Web ;
System . Web . Services ;
namespace WebService1
{
// / <summary>
// / Summary d e s c r i p t i o n f o r S e r v i c e 1
// / </summary>
[ WebService ( Namespace = " h t t p : / / tempuri . o r g / " ) ]
[ WebServiceBinding ( ConformsTo = WsiProfiles . BasicProfile1_1 ) ]
[ System . ComponentModel . ToolboxItem ( f a l s e ) ]
// To a l l o w t h i s Web S e r v i c e t o be c a l l e d from s c r i p t , u s i n g
ASP .NET AJAX, uncomment t h e f o l l o w i n g l i n e .
// [ System . Web . S c r i p t . S e r v i c e s . S c r i p t S e r v i c e ]
p u b l i c c l a s s Service1 : System . Web . Services . WebService
{
[ WebMethod ]
p u b l i c s t r i n g HelloWorld ( )
{
r e t u r n " H e l l o World " ;
}
}
}
51
5. Web Services
The class contains one method named HelloWorld(). For the method to be sent
by the web service to the client, it should be declared as web method through the
[WebMethod] directive.
1
2
3
4
5
[ WebMethod ]
p u b l i c s t r i n g HelloWorld ( )
{
r e t u r n " H e l l o World " ;
}
Lets add another method. For instance, we want to compute the sum of two
numbers. For doing so, we implement a method as follows:
1
2
3
4
5
[ WebMethod ]
p u b l i c i n t Add ( i n t a , i n t b )
{
r e t u r n a+b ;
}
By building and running the project, we will have our first web service like in the
Figure 5.4.
5.2
In order to create a client, fire up Visual Studio and create a new Console Application
project. Name the project myFirstClient. Then, add a web service reference to the
client, as shown in the Figures 5.5 and 5.6.
5. Web Services
Paste the URL into the text box URL (here http://localhost:5005/Service1.asmx).
After you press go, if the service is found you will see a window as in Figure 5.7 and
then you should add the reference.
s t a t i c v o i d Main ( s t r i n g [ ] args )
{
myFirstClient . localhost . Service1 service = new
myFirstClient . localhost . Service1 ( ) ;
i n t sum= service . Add ( 2 , 3 ) ;
Console . WriteLine ( " The sum i s "+sum . ToString ( ) ) ;
Console . ReadKey ( ) ;
}
54
Exercise
5.3
Exercise
1. Create a web service which converts the temperature from Fahrenheit to Celsius,
and vice versa. Then create two clients (one Console Application and one Form
Application) for making use of your service.
2. Create a web service which provides the exact date and time of the service.
3. Create a Web Service that gives access to a database which stores information
about Romania. Then, create a client which uses the service. It will provide
methods for adding new cities and for modifying them, based on a given name.
4. Make a presentation about Windows Communication Foundation.
55
5. Web Services
56
Chapter 6
Windows Presentation
Foundation
The Windows Presentation Foundation (WPF), designed by Microsoft, is a framework
for creating user-friendly interfaces. Initially, it was part of .NET Framework 3.0, being
known as "Avalon". WPF uses Extensible Application Markup Language (XAML),
an Extensible Markup Language (XML) derivative for initializing structure values
and objects. It provides the possibility of building UIs, 2D graphics, 3D graphics,
documents and multimedia applications. Standalone and also XAML Browser WPF
applications can be developed by using a similar programming model.
WPF makes much more than what Windows Form can do because it is an unified
solution which contains different technologies. For example, if you want to develop a
Windows Form Application which displays video or audio, you should use also Windows Media Player. Or, if you want to display documents on an interface, you can use
Windows Forms, but for fixed-format document you must use Adobes PDF. WPF
has support for all these and even more.
The WPF goal is not to replace Windows Forms. Windows Forms will have also
valuable usability even in WPF world and many applications will continue to use them
while some others will connect Windows Forms with WPFs.
WPF can create modern interfaces in a fairly straightforward manner. Compared
57
6.1
Getting started
A WPF application can be implemented using Visual Studio, 2008 version or later.
The Visual Studio 2005 users can also develop WPF applications by installing an
add-on.
A simple WPF application can be created by selecting File New Project
Visual C# WPF Application. A window as in Figure 6.1 will appear. The project
can be renamed and also its location can be changed.
The project along with the MainWindow.xaml and App.xaml files are created by
Visual Studio. It has almost the same structure as Windows Form, excepting that the
Window1.designer.cs file is now declared in XAML as MainWindow.xaml.
58
Getting started
6.1.1
Controls
The Toolbox (Ctrl+W,X) contains a rich set of built-in controls. They can be drag and
dropped from the toolbox or they can be implemented by using XAML code. Listing
6.1 shows the XAML code automatically generated when the project is created. It
provides the ability to create, configure, show, and manage the lifetime of windows
and dialog boxes.
Listing 6.1: The structure of a WPF program
1 <Window x : C l a s s=" MyFirstWPF . MainWindow "
2
xmlns=" h t t p : / / schemas . m i c r o s o f t . com/ w i n f x /2006/ xaml /
presentation "
3
xmlns : x=" h t t p : / / schemas . m i c r o s o f t . com/ w i n f x /2006/ xaml "
4
T i t l e=" MainWindow " Hei ght=" 231 " Width=" 414 ">
5
<Grid H e ight=" 187 " Width=" 365 ">
6
<Grid . R o w D e f i n i t i o n s>
7
<R o w D e f i n i t i o n H eig ht=" 184 " />
8
<R o w D e f i n i t i o n H eig ht=" 3 " />
9
</ Grid . R o w D e f i n i t i o n s>
10
</ Grid>
11 </Window>
Buttons
using
using
using
using
using
using
using
using
using
using
using
using
using
System ;
System . C o l l e c t i o n s . G e n e r i c ;
System . Linq ;
System . Text ;
System . Windows ;
System . Windows . C o n t r o l s ;
System . Windows . Data ;
System . Windows . Documents ;
System . Windows . Input ;
System . Windows . Media ;
System . Windows . Media . Imaging ;
System . Windows . N a v i g a t i o n ;
System . Windows . Shapes ;
namespace MyFirstWPF
{
p u b l i c p a r t i a l c l a s s MainWindow : Window
{
p u b l i c MainWindow ( )
{
InitializeComponent () ;
}
p r i v a t e v o i d button1_Click ( o b j e c t s e n d e r , RoutedEventArgs e )
{
MessageBox . Show ( " Hi ! " ) ;
}
}
}
60
Getting started
The XML button code is listed in the following.
Listing 6.3: XML button code
1 <Window x : C l a s s=" MyFirstWPF . MainWindow "
2
xmlns=" h t t p : / / schemas . m i c r o s o f t . com/ w i n f x /2006/ xaml /
presentation "
3
xmlns : x=" h t t p : / / schemas . m i c r o s o f t . com/ w i n f x /2006/ xaml "
4
T i t l e=" MainWindow " Hei ght=" 231 " Width=" 414 ">
5
<Grid H e ight=" 187 " Width=" 365 ">
6
<Grid . R o w D e f i n i t i o n s>
7
<R o w D e f i n i t i o n H eig ht=" 184 " />
8
<R o w D e f i n i t i o n H eig ht=" 3 " />
9
</ Grid . R o w D e f i n i t i o n s>
10
<Button Content=" MyButton " Hei ght=" 23 " H o r i z o n t a l A l i g n m e n t=
" L e f t " Margin=" 1 3 8 , 8 1 , 0 , 0 " Name=" button1 "
V e r t i c a l A l i g n m e n t=" Top " Width=" 75 " C l i c k=" button1_Click
" />
11
</ Grid>
12 </Window>
displays text
ListBox
CheckBox
ComboBox
RadioButton
TabControl
Image
displays an image
61
6.1.2
Layouts
In WPF, the layouts are used for arranging controls in complex environments. The
Table 6.2 presents the most popular build-in layout panels.
Dock Panel
Wrap Panel
as StackPanel, except that, when the line finishes, the child elements can be wrapped to new lines
Grid Panel
Canvas Panel
6.2
6.2.1
The main difference between Windows Forms and WPF applications is the way User
Interface (UI) elements are displayed and populated. WPF introduces the idea of
element styling and data binding in order to simplify the production process.
Lets consider the following problem: a main window with about 10 Slider items.
All sliders should be in the range 128 to 200 and be 250px in width and 30px in height.
Also, a numerical display, in the form of a TextBox control, should be added to show
the current selected value and modify the slider value. All the data from the sliders
should be saved as an object properties.
In order to solve the problem in Windows Forms, the designer would have to
manually set the Minimum, Maximum, Width and Height properties on each slider in
order to set the appearance, making further modifications very hard. On a functional
62
6.2.2
Styles
The concept of styles let you remove all properties values from the individual user
interface elements and combine them into a style. A style consists of a list of setters.
If you apply this style to an element, it sets all properties with the specified values.
The idea is quite similar to Cascading Styles Sheets (CSS) that we know from web
development.
To make the style accessible to your controls you need to add it to the resources.
Any control in WPF has a list of resources that is inherited to all controls beneath the
visual tree. That is the reason why we need to specify a x:Key="myStyle" property
that defines a unique resource identifier.
In this way, the modifications to all the controls can be made in a single place. For
example, setting the properties to the slider controls can be done as following.
At the beginning of the <Window> tag, the style definition must be added.
1
2
3
4
5
6
7
8
<Window . Resources>
<Style x : Key=" S l i d e r S t y l e 1 " TargetType=" {x : Type S l i d e r } ">
<Setter Property=" Width " Value=" 150 " />
<Setter Property=" He ight " Value=" 30 " />
<Setter Property=" Minimum " Value=" 128 " />
<Setter Property="Maximum" Value=" 200 " />
</ Style>
</ Window . Resources>
This defines the SliderStyle1 style which can then be applied to controls of type
Slider. Assigning a style to a control is done by adding the Style property to the
control definition:
1 <Slider Name=" s l i d e r 1 " Style=" { S t a t i c R e s o u r c e S l i d e r S t y l e 1 } " />
Multiple sliders can have the same style assigned. This solves the problem of
modifying a property in several controls.
63
64
36
37
38
39
40
6.2.3
Data Binding
WPF provides a simple and powerful way to auto-update data between the business
model and the user interface. This mechanism is called DataBinding. Every time
when the data of your business model changes, it automatically reflects the updates
to the user interface and vice versa. This is the preferred method in WPF for bringing
data to the user interface.
DataBinding can be unidirectional (source target or target source) or bidirectional (source target).
Data Binding between UI Elements
The issue of displaying the slider value in a TextBox and be able to modify data in
both directions is much simpler to be solved in WPF. To bind a TextBox control to a
Slider, the TextBox.Text property must be binded to the Slider.Value property.
1 <TextBox H e i ght=" 23 " Text=" { Binding ElementName=s l i d e r 1 , Path=Value
, U p d a t e S o u r c e T r i g g e r=PropertyChanged , Mode=TwoWay} " Name="
t e x t b o x 1 " />
6.3
Animations
66
Animations
Listing 6.6: C# code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using
using
using
using
using
using
using
using
using
using
using
using
using
System ;
System . C o l l e c t i o n s . G e n e r i c ;
System . Linq ;
System . Text ;
System . Windows ;
System . Windows . C o n t r o l s ;
System . Windows . Data ;
System . Windows . Documents ;
System . Windows . Input ;
System . Windows . Media ;
System . Windows . Media . Imaging ;
System . Windows . N a v i g a t i o n ;
System . Windows . Shapes ;
namespace Animation
{
/// <summary>
/// I n t e r a c t i o n l o g i c f o r MainWindow . xaml
/// </summary>
p u b l i c p a r t i a l c l a s s MainWindow : Window
{
p u b l i c MainWindow ( )
{
InitializeComponent () ;
CompositionTarget . Rendering += Move ;
}
Int32 counter = 0;
v o i d Move ( o b j e c t s e n d e r , EventArgs e )
{
counter = counter + 2;
Canvas . S e t L e f t ( b a l l , c o u n t e r ) ;
}
}
}
67
6.4
Exercises
1. Create a login window which opens another form (the user and password are
read from a file). The second form will contain a "Hello username!" label and
the Exit button.
2. Make an application that changes an object color depending on some parameters
RGB.
68
Bibliography
[1] MSDN, http://msdn.microsoft.com/en-us/library/67ef8sbd.aspx. vii, 39
[2] W. S. T. Architecture, http://www.flickr.com/photos/dullhunk/415645479/. vii,
49
[3] C. in C#, http://www.c-sharpcorner.com/. 8
[4] W. Services, http://www.w3schools.com/webservices/ws_why.asp. 50
[5] http://www.wpftutorial.net/.
[6] Wikipedia, http://en.wikipedia.org/wiki/main_page.
69