You are on page 1of 77

Technical University of Cluj-Napoca

Faculty of Automation and Computer Science

Industrial Informatics

Author: Author:
Asist.dr.eng. Emilia-Daniela Prof.dr.eng. Honoriu
Bordencea Valean

2012
Contents

Contents iii

List of Figures vii

1 Console Applications 1
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 C# syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.1 Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.2 Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.3 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.4 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.5 Data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.6 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2.7 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.2.8 Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.3 My first C# application . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

2 Windows Form Applications 17


2.1 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.1.1 Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.2 Multiple forms applications . . . . . . . . . . . . . . . . . . . . . . . . 26
2.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

iii
CONTENTS

3 Threads 29
3.1 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.1.1 Creating threads . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.1.2 Naming Threads . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.1.3 Join and Sleep methods . . . . . . . . . . . . . . . . . . . . . . 31
3.2 Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.2.1 Locking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.2.2 Monitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.2.3 Mutex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.2.4 Semaphore . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

4 Database 39
4.1 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.1.1 Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4.1.2 Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.1.3 DataReader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.1.4 DataSet and DataAdapter . . . . . . . . . . . . . . . . . . . . . 42
4.1.5 DataTable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.1.6 DataRelation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.2 My first database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.2.1 Connect to the MS SQL Server Express Database . . . . . . . 45
4.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

5 Web Services 49
5.1 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.2 Create a Web Service client . . . . . . . . . . . . . . . . . . . . . . . . 53
5.3 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

6 Windows Presentation Foundation 57


6.1 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
6.1.1 Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
6.1.2 Layouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

iv
CONTENTS

6.2 Styling and Data Binding . . . . . . . . . . . . . . . . . . . . . . . . . 62


6.2.1 WPF vs Windows Forms . . . . . . . . . . . . . . . . . . . . . 62
6.2.2 Styles in WPF . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
6.2.3 Data Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
6.3 Animations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
6.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

Bibliography 69

v
CONTENTS

vi
List of Figures

1.1 Creating a Console Application . . . . . . . . . . . . . . . . . . . . . . 10


1.2 Solution Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3 IntelliSense feature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.4 Hello C# Application . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.5 How to run an application in command line . . . . . . . . . . . . . . . 13

2.1 Creating a Form Application . . . . . . . . . . . . . . . . . . . . . . . 17


2.2 Form Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.3 My First Button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.4 Get text from a TextBox (1) . . . . . . . . . . . . . . . . . . . . . . . 23
2.5 Get Text from a TextBox (2) . . . . . . . . . . . . . . . . . . . . . . . 24
2.6 String concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

3.1 Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.2 Join method output . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

4.1 ADO architecture. Source: [1] . . . . . . . . . . . . . . . . . . . . . . . 39


4.2 Creating a database in C# . . . . . . . . . . . . . . . . . . . . . . . . 40
4.3 Creating a database in c# . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.4 Choose your Data Connection . . . . . . . . . . . . . . . . . . . . . . . 46

5.1 Web Services Triangle Architecture. Source: [2] . . . . . . . . . . . . . 49


5.2 Creating a Web Service . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.3 Solution Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

vii
LIST OF FIGURES

5.4 Web Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52


5.5 Add service reference (1) . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.6 Add service reference (2) . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.7 Add service reference (3) . . . . . . . . . . . . . . . . . . . . . . . . . . 54

6.1 Creating a WPF Application . . . . . . . . . . . . . . . . . . . . . . . 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

C# was developed by a small team of engineers at Microsoft. Anders Hejlsberg (the


Turbo Pascal language author and member of the team which designed the Borland
Delphi) is one of the creators. C# is an object-oriented imperative programming
language. It is very similar to Java and C++, and this is why the learning curve runs
very smoothly.

C# uses Microsoft .NET Framework, a collection of classes which can be down-


loaded through the Internet and which is constantly maintained and improved by
Microsoft.

The .NET applications are run in a program compilation called CLR (Common
Language Runtime). The initial compilation of the program generates a code written
in an intermediate language (CIL - Common Intermediate Language). In this form,
the code is then sent to the virtual processor (CLR) that performs the translation to
machine code and that runs the application.

1
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 meth-
ods. 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

A variable can contain either a value of an elementary type or a reference to an


object. In C#, a variable is declared by writing its type and name. They are optionally
initialized through the assignment of a value.

1 // D e c l a r e
2 int a ;
3 // I n i t i a l i z e
4 a =1;
5 // D e c l a r e and i n i t i a l i z e
6 i n t c =1;
7 // 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
8 i n t first , second ;
9 // D e c l a r e and i n i t i a l i z e
10 i n t bfirst =1 , bsecond =2;

Note: C# is "case sensitive", it distinguishes between uppercase and lowercase


letters.

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 {
7 // 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
8 cnt = 4 ;
9 }

3
1. Console Applications

1.2.5 Data types

Two categories of data types exist in C#:

• value types;

• reference types.

Value types

Examples:

• byte, short, int, float, double, long, char, bool, DateTime;

• primitive data types except string, object;

• struct;

• enum.
Date time:

1 DateTime currenttime = DateTime . Now ; // i t d i s p l a y s t h e c u r r e n t d a t e


time
2 i n t days = DateTime . DaysInMonth ( 2 0 1 1 , 7 ) ; // i t d i s p l a y s " 3 1 "

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 ] ;

2. multidimensional arrays (rectangular arrays)

1 s t r i n g [ , ] myArray ;
2 myArray = new s t r i n g [ 7 , 6 ] ;

3. array-of-arrays (jagged arrays)

1 byt e [ ] [ ] scores ;
2 scores = new byte [ 5 ] [ ] ;
3 f o r ( i n t x = 0 ; x < scores . Length ; x++)
4 {
5 scores [ x ] = new byte [ 4 ] ;
6 }

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 two−d 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
== Tests for equality

Increment and Decrement operators

v++ Increment variable v by 1


v += n Increment variable v by n ⇔ v=v+n;
v *= n Multiply variable v by n
v -= n Subtract n from variable v

Example of pre and post-increment operators:


Example:

1 x = n++; // s e t s x=n , and then s e t n=n+1


2 x = ++n ; // s e t s n=n+1 , and then s e t x = t h e new v a l u e o f n

Mathematical and Logical Operators

+ 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

== Checks for equality


!= Checks for inequality
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Conversions

Data type conversion can be performed by using cast.

1 int a = 5;
2 float b = 0;
3 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 .
4 b = 0.9 F ;
5 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:

1 i n t m = Convert . ToInt32 ( 1 2 4 . 4 5 6 ) ;

7
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 s t r i n g myText = " 20 " ;


2 i n t myNum = i n t . Parse ( myText ) ; // I t c o n v e r t s s t r i n g t o
integer .

Another C# method for parsing integers is int.TryParse. The difference between


int.TryParse and int.Parse is represented by the fact that, the first one can be used
when the data is corrupt. For example, when the data does contain non-numeric or
invalid characters, int.TryParse should be used. If the data is valid and consists only
of numbers, int.Parse is a good solution.

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

In order to work with files in C#, System.IO directive is used.


Writing in a file is done by using StreamWriter:

1 StreamWriter sw = new StreamWriter ( " myFile . t x t " , t r u e ) ;


2 sw . WriteLine ( " I am a f i l e ! " ) ;
3 sw . Close ( ) ;

8
C# syntax

Reading from a file:

1 StreamReader sr = new StreamReader ( " myFile . t x t " ) ;


2 s t r i n g line = sr . ReadLine ( ) ;
3 sr . Close ( ) ;

Split the line into words:

1 c h a r [ ] separator = { ’ ’ } ;
2 s t r i n g [ ] words = line . Split ( separator , StringSplitOptions .
RemoveEmptyEntries ) ;

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.

9
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.

Figure 1.1: Creating a Console Application

When a console application is created, a .cs file is generated. The .cs extension
comes from C Sharp.
All the project files can be found in Solution Explorer (Figure 1.2). If the Solution
Explorer cannot be seen, it can be made visible from the View menu or by using the
shortcut Ctrl+W, S.

Figure 1.2: Solution Explorer

10
My first C# application

In Listing 1.1, the structure of a C# program is presented.

Listing 1.1: The structure of a C# program


1 using System ;
2 using System . Collections . Generic ;
3 using System . Linq ;
4 using System . Text ;
5
6 namespace myFirstApp
7 {
8 c l a s s Program
9 {
10 s t a t i c v o i d Main ( s t r i n g [ ] args )
11 {
12
13 }
14 }
15 }

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 application’s 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.


Let’s 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.

Let’s 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

Figure 1.3: IntelliSense feature

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:

• Start Without Debugging (shortcut Ctrl+F5)

• Start Debugging (shortcut F5)

• 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

Figure 1.4: Hello 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.

Figure 1.5: How to run an application in command line

13
1. Console Applications

The Console class methods from the System namespace are used in Console Ap-
plications. 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 string a = "a string " ;


2 Console . WriteLine ( a ) ;
3 int b = 34;
4 Console . WriteLine ( b ) ;
5 char c = ’ a ’ ;
6 Console . WriteLine ( c ) ;

2. Console.WriteLine(format, parameters) → behaves as the printf function in C.

1 s t a t i c v o i d Main ( s t r i n g [ ] args )
2 {
3 int b = 34;
4 char c = ’ a ’ ;
5 Console . WriteLine ( " {0} i s {1} " , c , b ) ;
6 Console . ReadKey ( ) ;
7 }

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 i n t myInteger= i n t . Parse ( Console . ReadLine ( ) ) ;

14
Exercises

1.4 Exercises
1. Determine the first n terms of the Fibonacci sequence.

2. Read two real numbers from the keyboard and then, by using the binary opera-
tors +, -, *, /, make some computations.

3. Compute the ideal weight (kg) according to the height (cm), age (years) and
sex. The parameters are read from the keyboard.

Man_idWeight = [height (cm) -100 - ( (-150 ) /4 )] + ( (age-20) /4)

Woman_idWeight = [height (cm) -100 - ( (height-150 ) /2,5)] + ( (age-20) /6)

4. Create a stack. Add to the class Stack the public method ElementsNr() which
returns the elements number inserted in the stack. Do the same thing for a
queue.

5. Create a class named Car with the attributes: name, engine power and price.
Create a static method for comparing two cars. Let’s say that power is more
important than the price so, the power will be the first criterion and the price
will be the second one. Create an application which asks for n car models and
sorts them in ascending order.

15
1. Console Applications

16
Chapter 2

Windows Form Applications

2.1 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.

Figure 2.1: Creating a Form Application

17
2. Windows Form Applications

A window like the one in Figure 2.2 will appear. The window’s default name is
Form1. Controls, such as buttons, text boxes, menus, check boxes, radio buttons and
so on can be added to the forms.

Figure 2.2: Form Application

The Windows Form Applications can be formed of at least one Form. The visual
components of the application can be processed in the Designer mode (Shift + F7):
placing new objects, determining their properties and so on. The code "behind" a
visual component is accessible in Code mode (F7).
The code of Form1.cs file can be seen by right clicking and selecting the View Code
option in Solution Explorer. The properties window (Ctrl+W, P) is used for changing
objects properties.
The Toolbox (Ctrl+W,X) contains all the controls and all the components that
can be used. The controls can be dragged-and-dropped and they are clustered in
categories.
When a visual application is created, C# generates a namespace which contains
the starting point of the application (the Program class, listing 2.1).

18
Getting started

Listing 2.1: The Program class


1 using System ;
2 using System . Collections . Generic ;
3 using System . Linq ;
4 using System . Windows . Forms ;
5
6 namespace MyFirstForm
7 {
8 s t a t i c c l a s s Program
9 {
10 // / <summary>
11 // / 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 .
12 // / </summary>
13 [ STAThread ]
14 s t a t i c v o i d Main ( )
15 {
16 Application . EnableVisualStyles ( ) ;
17 Application . SetCompatibleTextRenderingDefault ( f a l s e ) ;
18 Application . Run ( new Form1 ( ) ) ;
19 }
20 }
21 }

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
environment’s right or left side.

2.1.1 Controls

A control is the main unit of a Windows interface. It can be hosted by a container


(for instance, a form or another control).

A control is an instance of a class derived from System.Windows.Forms, being


responsible for drawing a part of a container.

The Table 2.1 contains a list of the most frequently used controls together with
their descriptions.

19
2. Windows Form Applications

Table 2.1: Controls

Control name Description


Button used for executing a sequence of instructions when their are ac-
tivated by the user
MonthCalendar displays a calendar of the current month
CheckBox yes/no option
Label used for printing text label
ListBox displays a list of articles from where the user can choose
PictureBox used for adding images
Pointer used for selecting, moving or scaling a control
RadioButton gives the possibility of choosing one element from a cluster of
selections
TextBox displays the text generated by an application or gives the possi-
bility to introduce a text

Buttons

First, let’s create a Form Application, as in Figure 2.3, which contains a button.

Figure 2.3: My First 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, let’s add a function to our button. Thus, when the button is clicked, a mes-
sage 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 using System ;
2 using System . Collections . Generic ;
3 using System . ComponentModel ;
4 using System . Data ;
5 using System . Drawing ;
6 using System . Linq ;
7 using System . Text ;
8 using System . Windows . Forms ;
9
10 namespace MyFirstForm
11 {
12 p u b l i c partial c l a s s Form1 : Form
13 {
14 p u b l i c Form1 ( )
15 {
16 InitializeComponent ( ) ;
17 }
18 p r i v a t e v o i d button1_Click ( o b j e c t sender , EventArgs e )
19 {
20 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
2. Windows Form Applications

Exercise 1: Create an application that contains a button and displays the number
of clicks.

Show() method is used when you want to have access to the main menu form
controls, even if a second menu is active. If you want to have the permission of using
the main menu only when the second menu is closed, you should use ShowDialog()
method. In this case, we can talk about modal forms. DialogResult is a property used
with these methods for identifying which button is clicked by the user.

Exercise 2: Create a form which contains two buttons OK and CANCEL and
displays which button was clicked.

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

• Text: Get Text.

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

Figure 2.4: Get text from a TextBox (1)

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, let’s 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 p r i v a t e v o i d button1_Click ( o b j e c t sender , EventArgs e )


2 {
3 s t r i n g myStr ; // c r e a t e s a s t r i n g v a r i a b l e named " myStr "
4 myStr = textBox1 . Text ; // r e t a i n s t h e t e x t from t h e t e x t box
i n t h e " myStr " v a r i a b l e
5 textBox2 . Text = myStr ; // put t h e t e x t from t h e " myStr "
v a r i a b l e i n our s e c o n d t e x t box
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
2. Windows Form Applications

Figure 2.5: Get Text from a TextBox (2)

Exercise 3: Create a form which contains two labels, one for the price and one
for VAT. When the Compute button is clicked, the amount of VAT will be calculated
and displayed in another textBox.

Custom controls

.NET framework has the capability of creating custom controls. Therefore, the pro-
gramming model becomes easier.
You can create custom controls in the same way as you create ordinary classes.
The control class can be implemented in an already created project and it can be used
later. A custom control can inherit another control which is modified by adding some
other specific features.

String concatenation

Using the same form as before and the code listed below, let’s make a simple example
which takes the text "The result is " and the text from the text boxes and it displays
the result in a message box, as in Figure 2.6.
Although it is possible to concatenate strings using "+", the best way to do that
is by String.Format(), especially when there are more than 2 strings.

1 p r i v a t e v o i d button1_Click ( o b j e c t sender , EventArgs e )


2 {

24
Getting started

3 s t r i n g firstText = " The r e s u l t i s " ;


4 s t r i n g textTb1 , textTb2 ;
5 textTb1 = textBox1 . Text ;
6 textTb2 = textBox2 . Text ;
7 MessageBox . Show ( String . Format ( " {0} {1} {2} " , firstText ,
textTb1 , textTb2 ) ) ; // t h e same a s \ t e x t s l { f i r s t T e x t +
textTb1 +" "+ textTb2 }
8 }

Figure 2.6: String concatenation

Numerical variables

Suppose that a variable contains a numerical value. Display the value in a message
box.

1 p r i v a t e v o i d button1_Click ( o b j e c t sender , EventArgs e )


2 {
3 i n t myNumber = 2 5 ;
4 MessageBox . Show ( "My number i s " + myNumber ) ;
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. Windows Form Applications

as follows.

1 p r i v a t e v o i d button1_Click ( o b j e c t sender , EventArgs e )


2 {
3 i n t myNumber = 2 5 ;
4 MessageBox . Show ( "My number i s "+myNumber . ToString ( ) ) ;
5 }

2.2 Multiple forms applications


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 p r i v a t e v o i d button1_Click ( o b j e c t sender , EventArgs e )


2 {
3 Form2 secondForm = new Form2 ( ) ; // c r e a t e s t h e form
4 secondForm . Show ( ) ; // makes t h e form t o show up
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
2. Windows Form Applications

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.

Figure 3.1: Threads

29
3. Threads

3.1 Getting started


C# is a programming language where parallel execution is allowed. The threads
are independent processes which can run in parallel. They are managed by a thread
scheduler which allocates almost the same execution time to each thread. The thread
scheduler makes sure that the CPU time is not consumed by the waiting or blocking
threads. A thread can be in one of the following states: Unstarted (created), Started,
Running, Suspended, Blocked, WaitSleepJoin or Stopped.

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 using System ;
2 using System . Collections . Generic ;
3 using System . Linq ;
4 using System . Text ;
5 using System . Threading ;
6
7 namespace Threads
8 {
9 c l a s s Program
10 {
11 s t a t i c v o i d CreatingThread ( )
12 {
13 Console . WriteLine ( " H e l l o ! I am a t h r e a d . " ) ;
14 }
15 s t a t i c v o i d Main ( s t r i n g [ ] args )
16 {
17 ThreadStart ts = new ThreadStart ( CreatingThread ) ;
18 Thread myFirstThread = new Thread ( ts ) ;
19 myFirstThread . Start ( ) ;
20 }
21 }
22 }

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 using System ;
2 using System . Collections . Generic ;
3 using System . Linq ;
4 using System . Text ;
5 using System . Threading ;
6
7 namespace Threads
8 {
9 c l a s s Program
10 {
11 s t a t i c v o i d Main ( )
12 {
13 Thread . CurrentThread . Name = " main t h r e a d " ;
14 Thread worker = new Thread ( Hi ) ;
15 worker . Name = " worker t h r e a d " ;
16 worker . Start ( ) ;
17 Hi ( ) ;
18 Console . ReadKey ( ) ;
19 }
20
21 s t a t i c v o i d Hi ( )
22 {
23 Console . WriteLine ( " Hi from " + Thread . CurrentThread .
Name ) ;
24 }
25 }
26 }

3.1.3 Join and Sleep methods

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 using System ;
2 using System . Collections . Generic ;
3 using System . Linq ;
4 using System . Text ;
5 using System . Threading ;
6
7 namespace Threads
8 {
9 c l a s s Program
10 {
11 s t a t i c v o i d Main ( )
12 {
13 Thread . CurrentThread . Name = " main t h r e a d " ;
14 Thread worker = new Thread ( Hi ) ;
15 worker . Name = " worker t h r e a d " ;
16 worker . Start ( ) ;
17 worker . Join ( ) ;
18 Hi ( ) ;
19 }
20
21 s t a t i c v o i d Hi ( )
22 {
23 f o r ( i n t i = 1 ; i <= 5 ; i++)
24 {
25 Console . WriteLine ( " Hi from " + Thread . CurrentThread
. Name ) ;
26 }
27 }
28 }
29 }

The output of this example is presented in Figure 3.2.

Figure 3.2: Join method output

32
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:

1 l o c k ( expression )
2 {

33
3. Threads

3 instructions ;
4 }

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).

1 b o o l isblocked = ( myThread . ThreadState & ThreadState . WaitSleepJoin )


!= 0 ;

Thread unblocking can be performed by calling Thread.Interrupt or Thread.Abort.


Another way is represented by the specification of a timeout. If a thread execution
is paused by using the (deprecated) Suspend method, it is not considered as being
blocked anymore.

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 Monitor . Enter ( mon ) ;


2 try
3 {
4 // s y n c h r o n i z e d r e g i o n f o r o b j
5 }
6 finally
7 {
8 Monitor . Exit ( mon ) ;
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 b o o l _new ;
2 Mutex mutex = new Mutex ( f a l s e , " s t r i n g name " , out _new ) ;
3 i f ( ! _new )
4 {
5 MessageBox . Show ( " Only one i n s t a n c e can be s t a r t e d ! " ) ;
6 Application . Exit ( ) ;
7 return ;
8 }

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.

1 s t a t i c Semaphore mySem = new Semaphore ( 0 , 4 ) ;

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 c l a s s Program
2 {
3 s t a t i c i n t threadNr = 1 0 ;
4 s t a t i c i n t semCount = 5 ;
5
6 s t a t i c v o i d Main ( s t r i n g [ ] args )
7 {
8 f o r ( i n t i = 1 ; i <= threadNr ; i++) new Thread ( Enter ) .
Start ( i ) ;
9 }
10
11 s t a t i c SemaphoreSlim semaphore = new SemaphoreSlim ( semCount
);
12
13 s t a t i c v o i d Enter ( o b j e c t id )
14 {
15 Console . WriteLine ( id + " s a y s h i ! " ) ;
16 semaphore . Wait ( ) ;
17 Console . WriteLine ( id + " s a y s bye ! " ) ;
18 Thread . Sleep ( 1 0 0 ∗ ( i n t ) id ) ; Console . WriteLine ( id + "
i s going o f f l i n e " ) ;
19 semaphore . Release ( ) ;
20 }
21 }

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. Usu-
ally, 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.

Figure 4.1: ADO architecture. Source: [1]

39
4. Database

Figure 4.2: Creating a database in C#

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 Com-
mit 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 DataSet and DataAdapter

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:

1 DataSet ds = new DataSet ( ) ;


2 SqlDataAdapter da = new SqlDataAdapter ( "SELECT ∗ from myTable " ,
myCon )

* symbol means "all the records".


Further, the DataSet is filled by using da.Fill(ds, "MyTable").

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 in-
stance:

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.

Figure 4.3: Creating a database in c#

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 Data type Allow Nulls


Id int No
NameUniv text No
City text No
Code int No

Table 4.2: Faculties

Column name Data type Allow Nulls


Code int No
NameFac text No

presented in the tables 4.1 and 4.2:


A unique Primary Key, identifying a particular row, can be set by right clicking
on the desired row.
Save the tables and name them as Universities and Faculties. Now, let’s add some
data in our tables. Right click on your Table, then select Show Table Data and fill in
the columns. For filling the cells click inside them. Warning symbols can be observed.
They appear only when the data has changed. Save your tables by clicking Execute
SQL (marked by a red exclamation mark !). Now you have created your first database.

44
My first database

4.2.1 Connect to the MS SQL Server Express Database

Listing 4.1: Connect to the SQL Server Express Database


1 u s i n g System . Data . SqlClient ;
2
3 namespace myDatabase
4 {
5 p u b l i c partial c l a s s Form1 : Form
6 {
7 p u b l i c Form1 ( )
8 {
9 InitializeComponent ( ) ;
10 }
11
12 p r i v a t e v o i d Form1_Load ( o b j e c t sender , EventArgs e )
13 {
14 SqlConnection myCon=new SqlConnection ( ) ; // s e t up a SQL
Connection o b j e c t
15 }
16 }
17 }

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 Connec-
tion String.
After your SqlConnection line, add the following code:

1 myCon . ConnectionString=" Data S o u r c e =.\SQLEXPRESS ; AttachDbFilename =|


D a t a D i r e c t o r y | \ Database1 . mdf ; I n t e g r a t e d S e c u r i t y=True ; User
I n s t a n c e=True " ;

When you add this code in C# you will notice that errors are signaled. This

45
4. Database

Figure 4.4: Choose your Data Connection

happens because the backslash is considered to be a special character in C# and it


should be marked. This can be done as in one of the following cases:

1 myCon . ConnectionString=" Data S o u r c e =.\\SQLEXPRESS ; AttachDbFilename


=| D a t a D i r e c t o r y | \ \ Database1 . mdf ; I n t e g r a t e d S e c u r i t y=True ; User
I n s t a n c e=True " ;

1 myCon . ConnectionString=@ " Data S o u r c e =.\SQLEXPRESS ; AttachDbFilename


=| D a t a D i r e c t o r y | \ Database1 . mdf ; I n t e g r a t e d S e c u r i t y=True ; User
I n s t a n c e=True " ;

Next, you can open a connection to the database by using myCon.Open() and you
can close the connection by using myCon.Close().
Now, let’s see a simple example. Considering the relational database already cre-
ated, 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 be-
tween 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 meth-
ods. 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).

Figure 5.1: Web Services Triangle Architecture. Source: [2]

49
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.

Figure 5.2: Creating a Web Service

In order to create a new web service, fire up Visual Studio. Then, there are two
possibilities: either select the New Project button or create the project from the menu
bar as follows File → New Project → Visual C# Web → ASP.NET Web Service
Application. After creating the project, all the project files can be found in Solution

50
Getting started

Explorer (see Figure 5.3).

Figure 5.3: Solution Explorer

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 using System ;
2 using System . Collections . Generic ;
3 using System . Linq ;
4 using System . Web ;
5 using System . Web . Services ;
6
7 namespace WebService1
8 {
9 // / <summary>
10 // / Summary d e s c r i p t i o n f o r S e r v i c e 1
11 // / </summary>
12 [ WebService ( Namespace = " h t t p : / / tempuri . o r g / " ) ]
13 [ WebServiceBinding ( ConformsTo = WsiProfiles . BasicProfile1_1 ) ]
14 [ System . ComponentModel . ToolboxItem ( f a l s e ) ]
15 // 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 .
16 // [ 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 ]
17 p u b l i c c l a s s Service1 : System . Web . Services . WebService
18 {
19 [ WebMethod ]
20 p u b l i c s t r i n g HelloWorld ( )
21 {
22 r e t u r n " H e l l o World " ;
23 }
24 }
25 }

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 [ WebMethod ]
2 p u b l i c s t r i n g HelloWorld ( )
3 {
4 r e t u r n " H e l l o World " ;
5 }

Let’s add another method. For instance, we want to compute the sum of two
numbers. For doing so, we implement a method as follows:

1 [ WebMethod ]
2 p u b l i c i n t Add ( i n t a , i n t b )
3 {
4 r e t u r n a+b ;
5 }

By building and running the project, we will have our first web service like in the
Figure 5.4.

Figure 5.4: Web Service

Note: Each method has to be marked with the [WebMethod] directive. Without
this directive, the method cannot be called.

52
Create a Web Service client

5.2 Create a Web Service client


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.

Figure 5.5: Add service reference (1)

Figure 5.6: Add service reference (2)

53
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.

Figure 5.7: Add service reference (3)

Now, the client is connected to the service and it can use the methods exposed by
the service. Further, the client can be implemented as below:

Listing 5.2: The Client code


1 s t a t i c v o i d Main ( s t r i n g [ ] args )
2 {
3 myFirstClient . localhost . Service1 service = new
myFirstClient . localhost . Service1 ( ) ;
4 i n t sum= service . Add ( 2 , 3 ) ;
5 Console . WriteLine ( " The sum i s "+sum . ToString ( ) ) ;
6 Console . ReadKey ( ) ;
7 }

Exercise: Create another client for making use of your service.

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 Win-
dows 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 Adobe’s 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. Windows Presentation Foundation

to Windows Form applications, the WPFs are divided in two parts:

• the appearance of an user interface, specified in XAML,

• the behavior, implemented using C# or Visual Basic.

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.

Figure 6.1: Creating a WPF Application

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

Figure 6.2: WPF button

59
6. Windows Presentation Foundation

First control presented is the well known button (see Figure 6.2). It has two main
properties: IsDefault and IsCancel.
Exercise 1: Using the application already created, add a button, named MyBut-
ton, to the window. Then, in the properties window, after switching to the event view,
double-click on the "Click" event.
In this way, the method button1_Click, which will be executed when the button
is pressed, is automatically created. This can be done only if the Service Pack 1 for
Visual Studio is installed. The same result will be achieved if the button will be
double-clicked. The method created in the code-behind file is the same as in Windows
Form.
Add inside the method the code: MessageBox.Show("Hi!"). Then, test the appli-
cation which is also presented in Listing 6.2.

Listing 6.2: Button event


1 using System ;
2 using System . C o l l e c t i o n s . G e n e r i c ;
3 using System . Linq ;
4 using System . Text ;
5 using System . Windows ;
6 using System . Windows . C o n t r o l s ;
7 using System . Windows . Data ;
8 using System . Windows . Documents ;
9 using System . Windows . Input ;
10 using System . Windows . Media ;
11 using System . Windows . Media . Imaging ;
12 using System . Windows . N a v i g a t i o n ;
13 using System . Windows . Shapes ;
14
15 namespace MyFirstWPF
16 {
17 p u b l i c p a r t i a l c l a s s MainWindow : Window
18 {
19 p u b l i c MainWindow ( )
20 {
21 InitializeComponent () ;
22 }
23
24 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 )
25 {
26 MessageBox . Show ( " Hi ! " ) ;
27 }
28 }
29 }

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>

TextBoxes and RichTextBoxes

A TextBox can be used for displaying unformatted text or for giving the possibility of
entering some text. It brings the opportunity of words auto-correcting by using the
spell checking functionality. The available languages are English, French, German and
Spanish. The code for enabling the spell checking functionality is presented below.
This can be done by setting the SpellCheck.IsEnabled property to true.

1 <TextBox SpellCheck . IsEnabled=" True " Language=" en−US" />

The table 6.1 presents other WPF controls.

Table 6.1: Other controls

Label displays text


ListBox displays a list of items
CheckBox displays item that can be selected or cleared
ComboBox items control where only one item can be visible at a time
RadioButton displays items that can be selected but not cleared
TabControl displays multiple items that share the same space in a form
Image displays an image

61
6. Windows Presentation Foundation

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.

Table 6.2: Layouts

Stack Panel places the controls beside each other or below


Dock Panel arranges the elements in the right, left, bottom, top or center of
the panel
Wrap Panel as StackPanel, except that, when the line finishes, the child ele-
ments can be wrapped to new lines
Grid Panel organizes the child in a tabular structure
Canvas Panel the child’s coordinates are explicitly given

6.2 Styling and Data Binding

6.2.1 WPF vs Windows Forms

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.
Let’s 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
Styling and Data Binding

level, one must add event handlers to the sliders in which the TextBox.Text property
would be updated and also, assign each sliders value to the respective object property.
WPF brings two new concepts in order to solve these problems: Styling and Data
Binding.

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 <Window . Resources>
2 <Style x : Key=" S l i d e r S t y l e 1 " TargetType=" {x : Type S l i d e r } ">
3 <Setter Property=" Width " Value=" 150 " />
4 <Setter Property=" He ight " Value=" 30 " />
5 <Setter Property=" Minimum " Value=" 128 " />
6 <Setter Property="Maximum" Value=" 200 " />
7 </ Style>
8 </ 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
6. Windows Presentation Foundation

Listing 6.4: Example with multiple sliders


1 <Window x : C l a s s="LabWPF2 . 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 " He ight=" 195 " Width=" 347 ">
5 <Window . R e s o u r c e s>
6 <S t y l e x : Key=" S l i d e r S t y l e 1 " TargetType=" {x : Type S l i d e r } ">
7 <S e t t e r P r o p e r t y=" H o r i z o n t a l A l i g n m e n t " Value=" L e f t " />
8 <S e t t e r P r o p e r t y=" Minimum " Value=" 128 " />
9 <S e t t e r P r o p e r t y="Maximum" Value=" 200 " />
10 <S e t t e r P r o p e r t y=" Width " Value=" 150 " />
11 <S e t t e r P r o p e r t y=" He ight " Value=" 30 " />
12 </ S t y l e>
13 <S t y l e x : Key=" TextBoxStyle1 " TargetType=" {x : Type TextBox } ">
14 <S e t t e r P r o p e r t y=" H o r i z o n t a l A l i g n m e n t " Value=" L e f t " />
15 <S e t t e r P r o p e r t y=" Width " Value=" 50 " />
16 <S e t t e r P r o p e r t y=" He ight " Value=" 30 " />
17 </ S t y l e>
18 </Window . R e s o u r c e s>
19
20 <Grid>
21 <Grid . C o l u m n D e f i n i t i o n s>
22 <C o l u m n D e f i n i t i o n Width=" ∗ " />
23 <C o l u m n D e f i n i t i o n Width=" ∗ " />
24 </ Grid . C o l u m n D e f i n i t i o n s>
25 <S t a c k P a n e l Grid . Column=" 0 ">
26 <S l i d e r Name=" s l i d e r 1 " S t y l e=" { 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 } " />
27 <S l i d e r Name=" s l i d e r 2 " S t y l e=" { 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 } " />
28 <S l i d e r Name=" s l i d e r 3 " S t y l e=" { 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 } " />
29 <S l i d e r Name=" s l i d e r 4 " S t y l e=" { 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 } " />
30 <S l i d e r Name=" s l i d e r 5 " S t y l e=" { 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 } " />
31 </ S t a c k P a n e l>
32 <S t a c k P a n e l Grid . Column=" 1 ">
33 <TextBox S t y l e=" { S t a t i c R e s o u r c e TextBoxStyle1 } " 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 " />
34 <TextBox S t y l e=" { S t a t i c R e s o u r c e TextBoxStyle1 } " Text="
{ Binding ElementName=s l i d e r 2 , 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 2 " />
35 <TextBox S t y l e=" { S t a t i c R e s o u r c e TextBoxStyle1 } " Text="
{ Binding ElementName=s l i d e r 3 , Path=Value ,
U p d a t e S o u r c e T r i g g e r=PropertyChanged , Mode=TwoWay} "

64
Styling and Data Binding

Name=" t e x t b o x 3 " />


36 <TextBox S t y l e=" { S t a t i c R e s o u r c e TextBoxStyle1 } " Text="
{ Binding ElementName=s l i d e r 4 , 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 4 " />
37 <TextBox S t y l e=" { S t a t i c R e s o u r c e TextBoxStyle1 } " Text="
{ Binding ElementName=s l i d e r 5 , 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 5 " />
38 </ S t a c k P a n e l>
39 </ Grid>
40 </Window>

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 bidi-
rectional (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 " />

In order to implement this, the Text property contains a binding definition.

• ElementName refers to the control the TextBox binds.

• The Path value represents the target object property to be displayed.

• UpdateSourceTrigger represents the event which triggers the data exchange be-
tween the controls.

65
6. Windows Presentation Foundation

• Mode sets the direction in which the data should be exchanged, in this case we
want the slider to modify the TextBox value and vice versa.

The binding mechanism also allows formatting the string displayed in the TextBox
and different data conversion techniques which are out of the scope of this laboratory.

6.3 Animations
Test the application from Listings 6.5 and 6.6.

Listing 6.5: XML code


1 <Window x : C l a s s=" Animation . 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 " He ight=" 350 " Width=" 525 ">
5 <Border BorderBrush=" Gray " B o r d e r T h i c k n e s s=" 1 " Margin=" 4 "
He ight=" 374 " Width=" 523 ">
6 <Canvas He igh t=" 294 " Width=" 472 ">
7 <R e c t a n g l e F i l l="#D400CE51 " Width=" 75 " Hei ght=" 69 "
8 Canvas . Top=" 100 " Canvas . L e f t=" 396 " S t r o k e=" Brown " /
>
9 < E l l i p s e x : Name=" b a l l " Width=" 50 " Heig ht=" 50 " S t r o k e="
Brown " Canvas . Top=" 107 " Canvas . L e f t=" 90 ">
10 < E l l i p s e . F i l l>
11 <L i n e a r G r a d i e n t B r u s h>
12 <G r a d i e n t S t o p C o l o r=" Pink " O f f s e t=" 0 " />
13 <G r a d i e n t S t o p C o l o r="#D400CE51 " O f f s e t="
0 . 6 2 8 " />
14 </ L i n e a r G r a d i e n t B r u s h>
15 </ E l l i p s e . F i l l>
16 < E l l i p s e . RenderTransform>
17 <RotateTransform x : Name=" b a l l R o t a t e "
18 CenterX=" 25 " CenterY=" 25 " />
19 </ E l l i p s e . RenderTransform>
20 </ E l l i p s e>
21 </ Canvas>
22 </ Border>
23 </Window>

66
Animations

Listing 6.6: C# code


1 using System ;
2 using System . C o l l e c t i o n s . G e n e r i c ;
3 using System . Linq ;
4 using System . Text ;
5 using System . Windows ;
6 using System . Windows . C o n t r o l s ;
7 using System . Windows . Data ;
8 using System . Windows . Documents ;
9 using System . Windows . Input ;
10 using System . Windows . Media ;
11 using System . Windows . Media . Imaging ;
12 using System . Windows . N a v i g a t i o n ;
13 using System . Windows . Shapes ;
14
15 namespace Animation
16 {
17 /// <summary>
18 /// I n t e r a c t i o n l o g i c f o r MainWindow . xaml
19 /// </summary>
20 p u b l i c p a r t i a l c l a s s MainWindow : Window
21 {
22 p u b l i c MainWindow ( )
23 {
24 InitializeComponent () ;
25 CompositionTarget . Rendering += Move ;
26
27 }
28
29 Int32 counter = 0;
30 v o i d Move ( o b j e c t s e n d e r , EventArgs e )
31 {
32 counter = counter + 2;
33 Canvas . S e t L e f t ( b a l l , c o u n t e r ) ;
34 }
35 }
36 }

67
6. Windows Presentation Foundation

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

You might also like