indrumator ii
TRANSCRIPT
-
7/25/2019 Indrumator II
1/77
Technical University of Cluj-Napoca
Faculty of Automation and Computer Science
Industrial Informatics
Author:
Asist.dr.eng. Emilia-Daniela
Bordencea
Author:
Prof.dr.eng. Honoriu
Valean
2012
-
7/25/2019 Indrumator II
2/77
-
7/25/2019 Indrumator II
3/77
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.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
-
7/25/2019 Indrumator II
4/77
CONTENTS
3 Threads 29
3.1 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.1.1 Creating threads . . . . . . . . . . . . . . . . . . . . . . . . . . 303.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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424.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
-
7/25/2019 Indrumator II
5/77
CONTENTS
6.2 Styling and Data Binding . . . . . . . . . . . . . . . . . . . . . . . . . 62
6.2.1 WPF vs Windows Forms . . . . . . . . . . . . . . . . . . . . . 62
6.2.2 Styles in WPF . . . . . . . . . . . . . . . . . . . . . . . . . . . 636.2.3 Data Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
6.3 Animations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
6.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Bibliography 69
v
-
7/25/2019 Indrumator II
6/77
CONTENTS
vi
-
7/25/2019 Indrumator II
7/77
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
-
7/25/2019 Indrumator II
8/77
LIST OF FIGURES
5.4 Web Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.5 Add service reference (1) . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.6 Add service reference (2) . . . . . . . . . . . . . . . . . . . . . . . . . . 535.7 Add service reference (3) . . . . . . . . . . . . . . . . . . . . . . . . . . 54
6.1 Creating a WPF Application . . . . . . . . . . . . . . . . . . . . . . . 58
6.2 WPF button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
viii
-
7/25/2019 Indrumator II
9/77
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
-
7/25/2019 Indrumator II
10/77
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
-
7/25/2019 Indrumator II
11/77
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 e2 i n t a ;3 // I n i t i a l i z e4 a =1 ;5 // D ec la re and i n i t i a l i z e6 i n t c =1 ;7 // M u l ti p le v a r i ab l e can be d e cl a r ed in o ne s ta te me nt i f
t h ey h av e t h e same t y pe8 i n t first, second;9 // D ec la re 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 readonlymodifier.When local variables or fields are declared using the
constmodifier, they must be initialized. The constants are implicitly static.
1 co ns t i n t ct = 3 ;
On the other hand, the readonlyfields can be initialized within a constructor.
1 // I n i t i a l i z e a r e ad on ly f i e l d
2 p u bl i c r ea do nl y i n t ct = 3 ;
3 p u bl i c r ea do nl y i n t cn t;
4
5 p u b l i c my C ( )
6 {
7 // I n i t i a l i z e a r ea do nl y i n s ta nc e f i e l d
8 cn t = 4 ;
9 }
3
-
7/25/2019 Indrumator II
12/77
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 D a te T i m e c u r r e n t t im e = DateTime.N ow ; / / i t d i s p l a ys t he c u rr e nt d at etime
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,stringand 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
-
7/25/2019 Indrumator II
13/77
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; // n ot i n t a r ra 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 b y te[ ] [ ] scores;2 scores = new b y te[ 5 ] [ ] ;3 f o r (i n t x = 0 ; x < scores. Length; x++)4 {5 scores[ x ] = new b y te[ 4 ] ;6 }
You can have three-dimensional rectangular arrays or mix rectangular and jaggedarrays.
5
-
7/25/2019 Indrumator II
14/77
1. Console Applications
1 i n t[ , , ] buttons = new i n t [ 4 , 5 , 3 ] ; / / t h r e ed i m en s io n a l r e c t a n g u l a ra r r a y
2 i n t[ ] [ , , ] [ , ] numbers; / / s i n g l e d i m en s i on a l a r ra y o f t h re ed i m en s i on a l a r r a y s o f twod i me ns i on a l a r ra y s o f t yp e 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 nv=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 , a nd t h e n s e t n=n+12 x = ++n ; / / s e t s n=n +1 , a nd t he n s e t x = th e n ew v a lu e o f n
Mathematical and Logical Operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
& Logical AND
Logical XOR
| Logical OR
6
-
7/25/2019 Indrumator II
15/77
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
-
7/25/2019 Indrumator II
16/77
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 = " 2 0 ";2 i n t myNum = i n t. Parse (my Te xt ) ; // I t c on ve rt s s t r i n g t o
i n t e g e r .
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 S t re a m W r i t e r s w = new StreamWriter (" myFile . txt ", t r u e) ;
2 sw. WriteLine (" I am a f i l e ! ") ;
3 sw. Close( ) ;
8
-
7/25/2019 Indrumator II
17/77
C# syntax
Reading from a file:
1 S tr e a m R e a d e r s r = new StreamReader (" myFile . txt ") ;
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, S t r i n g S p l i t O p t i o n s.
R e m o v e E m p t y E n t r i e s) ;
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
-
7/25/2019 Indrumator II
18/77
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 (Figure1.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 .csextension
comes from C Sharp.
All the project files can be found in Solution Explorer(Figure1.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
-
7/25/2019 Indrumator II
19/77
My first C# application
In Listing1.1,the structure of a C#program is presented.
Listing 1.1: The structure of a C#program1 u s i n g System;2 u s i n g System. Collections. Generic;3 u s i n g System. Linq;4 u s i n g System. Text;56 namespace myFirstApp7 {8 c l a s s Program9 {
10 s t a t i c v oi 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 Systemnamespace classes
will be used. MyFirstAppis the applications name. There also exists a classProgram
which contains the Mainmethod.
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 Figure1.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
-
7/25/2019 Indrumator II
20/77
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
-
7/25/2019 Indrumator II
21/77
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 Figure1.5.
Figure 1.5: How to run an application in command line
13
-
7/25/2019 Indrumator II
22/77
-
7/25/2019 Indrumator II
23/77
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 classStack the public method ElementsNr() whichreturns 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. Lets 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
-
7/25/2019 Indrumator II
24/77
1. Console Applications
16
-
7/25/2019 Indrumator II
25/77
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 FileNew Project Visual C#and then select Windows Form Application.
Figure 2.1: Creating a Form Application
17
-
7/25/2019 Indrumator II
26/77
2. Windows Form Applications
A window like the one in Figure 2.2 will appear. The windows 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
-
7/25/2019 Indrumator II
27/77
Getting started
Listing 2.1: TheProgram class
1 u s i n g System;2 u s i n g System. Collections. Generic;
3 u s i n g System. Linq;4 u s i n g System. Windows. Forms;56 namespace MyFirstForm7 {8 s t a t i c c l a s s Program9 {
10 // / 11 / // The main e n tr y po i n t f o r th e a p p l i c a t i o n .12 // / 13 [STAThread]14 s t a t i c v oi d Main( )15 {16 Application. E n a b l e V i s u a lS t y l e s( ) ;
17 Application. S e t C o m p a t i b l e T e x t R en d e r i n g D e f a u l t (f a l s e) ;18 Application. R un ( 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
environments 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
-
7/25/2019 Indrumator II
28/77
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 userMonthCalendar displays a calendar of the current monthCheckBox yes/no optionLabel used for printing text labelListBox displays a list of articles from where the user can choosePictureBox used for adding imagesPointer used for selecting, moving or scaling a controlRadioButton gives the possibility of choosing one element from a cluster of
selectionsTextBox displays the text generated by an application or gives the possi-
bility to introduce a text
Buttons
First, lets 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
-
7/25/2019 Indrumator II
29/77
Getting started
will appear on your button inMy 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 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 eare 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 Listing2.2.
Listing 2.2: Display a MessageBox which contains some text
1 u s i n g System;2 u s i n g System. Collections. Generic;3 u s i n g System. ComponentModel;4 u s i n g System. Data;5 u s i n g System. Drawing;6 u s i n g System. Linq;7 u s i n g System. Text;
8 u s i n g System. Windows. Forms;9
10 namespace MyFirstForm11 {12 p u b l i c partial c l a s s Form1 : Form13 {14 p u b l i c Form1( )15 {16 I n i t i a l i z e C o m p o n e n t( ) ;17 }18 p r i v at e v oi d button1_Click (o b j e c t sender, E v e n t Ar g s e )19 {20 MessageBox. Show ("Me s s a ge ", "My F ir s t Msg ") ; / / d i s p l a ys
a wi ndo w w i t h t h e name " My F i r s t Msg " a nd am es sa ge " M e ss ag e " . I f "My F i r s t Msg " i s o m it t ed ,t h e window w i l l n ot h av e a ny name .
21 }22 }23 }
21
-
7/25/2019 Indrumator II
30/77
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 Figure2.4. Note the fact that the second TextBox is ReadOnly.
22
-
7/25/2019 Indrumator II
31/77
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, 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 p r i v a t e v oi d b u t t o n 1 _ C l i c k (o b j e c t sender, E v e n tA r g s 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 he t e xt f rom t he t e xt box
i n t he " myStr " v a r i a b l e5 textBox2. Text = myStr; / / p ut t he t e x t f ro m t h e " m yStr "
v a r i a b l e i n o ur s ec on d t e xt 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 Figure2.5.
23
-
7/25/2019 Indrumator II
32/77
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 theComputebutton 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, lets 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 Figure2.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 oi d b u t t o n 1 _ C l i c k (o b j e c t sender, E v e n tA r g s e )2 {
24
-
7/25/2019 Indrumator II
33/77
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 +te x tTb 1 +" "+ te x tTb 2 }
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 oi d b u t t o n 1 _ C l i c k (o b j e c t sender, E v e n tA r g s e )2 {3 i n t myNumber = 2 5 ;4 MessageBox. Show ("My n umbe r 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
-
7/25/2019 Indrumator II
34/77
2. Windows Form Applications
as follows.
1 p r i v a t e v oi d b u t t o n 1 _ C l i c k (o b j e c t sender, E v e n tA r g s e )2 {3 i n t myNumber = 2 5 ;4 MessageBox. Show ("My n umbe r i s "+my Nu m be r. 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 oi d b u t t o n 1 _ C l i c k (o b j e c t sender, E v e n tA r g s e )2 {3 F o r m 2 s e c o n d F or m = new Form2( ) ; / / c r e a t e s t he for m4 secondForm. Show( ) ; / / ma ke s t h e f or m t o show up5 }
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
-
7/25/2019 Indrumator II
35/77
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
-
7/25/2019 Indrumator II
36/77
2. Windows Form Applications
28
-
7/25/2019 Indrumator II
37/77
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
-
7/25/2019 Indrumator II
38/77
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, WaitSleepJoinorStopped.
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
Threadobject 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.
Listing3.1 creates a thread which prints "Hello! I am a thread." in console.
Listing 3.1: Creating a thread
1 u s i n g System;2 u s i n g System. Collections. Generic;3 u s i n g System. Linq;4 u s i n g System. Text;5 u s i n g System. Threading;67 namespace Threads8 {9 c l a s s Program
10 {11 s t a t i c v oi d CreatingThread( )12 {13 Console. WriteLine (" H e l l o ! I am a t h r e ad . ") ;14 }15 s t a t i c v oi d Main (s t r i n g[ ] args )16 {
17 T h r e a d S t ar t t s = new ThreadStart ( CreatingThread ) ;18 T h r e a d m y F i r s t T h re a d = new Thread ( ts ) ;19 myFirstThread. Start( ) ;20 }21 }22 }
30
-
7/25/2019 Indrumator II
39/77
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.
Listing3.2contains a program which creates two threads: main and worker. When
a thread starts, it has its IsAliveproperty true till the end. If a thread is stopped, it
cannot be restarted.
Listing 3.2: Creating two threads
1 u s i n g System;2 u s i n g System. Collections. Generic;3 u s i n g System. Linq;
4 u s i n g System. Text;5 u s i n g System. Threading;67 namespace Threads8 {9 c l a s s Program
10 {11 s t a t i c v oi d Main( )12 {13 Thread. CurrentThread. Name = " main th re a d ";14 T h r e a d w o r k e r = new Thread ( Hi ) ;15 worker. Name = " w o rk e r t h r e a d ";16 worker. Start( ) ;
17 Hi ( ) ;18 Console. ReadKey( ) ;19 }2021 s t a t i c v oi d Hi ( )22 {23 Console. WriteLine (" H i f ro m " + 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
-
7/25/2019 Indrumator II
40/77
3. Threads
statement, the example from listing3.3 will be considered.
Listing 3.3: Join method
1 u s i n g System;2 u s i n g System. Collections. Generic;3 u s i n g System. Linq;4 u s i n g System. Text;5 u s i n g System. Threading;67 namespace Threads8 {9 c l a s s Program
10 {11 s t a t i c v oi d Main( )12 {13 Thread. CurrentThread.Name = " main th re a d ";
14 T h r e a d w o r k e r = new Thread ( Hi ) ;15 worker.Name = " w o rk e r t h r e a d ";16 worker.Start( ) ;17 worker.Join( ) ;18 Hi ( ) ;19 }2021 s t a t i c v oi d Hi ( )22 {23 f o r (i n t i = 1 ; i
-
7/25/2019 Indrumator II
41/77
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 us es t he t hr ea d f o r 1 00 0 m i l l i s e c o n d s2 Thread. Sleep ( TimeSpan. FromHours (2 ) ) ; // p au se s t he t hr ea d f o r 2
h o u rs
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. Lockingis 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 callingEnter,
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
-
7/25/2019 Indrumator II
42/77
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). ThreadStatechecks the state of the thread (if it is blocked or not).
1 b o o l isblocked = (my Th re ad . ThreadState & ThreadState. W a i t S l e e p J oi n )
!= 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 Monitoris an advanced version ofLock. 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 Pulsecommand 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 (mo n ) ;2 t r y3 {4 // s yn c hr o ni z ed r e g io n f o r o bj5 }6 f i n a l l y7 {8 Monitor.Exit (mo n ) ;9 }
TheMonitorsare 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
-
7/25/2019 Indrumator II
43/77
Synchronization
to use the lock are blocked and they have to wait till the thread releases the lock.
The Monitorclass contains methods for controlling the threads synchronization.
They may allow the declaration of critical areas, where, at a time, only one thread canoperate. When you want to start synchronization, call theEnter method, specifying
the object which will be blocked. If the Monitoris 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
AMutexis different than a C# lock because it can be used for synchronizing betweenmultiple processes. A Mutex, with a name assigned to it, is known by the operating
system and is shared between different processes. Thus, a Mutexcan 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 WaitOnemethod is used and in order to release it, the
ReleaseMutexis 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 M u te x m u te x = new Mutex (f a l s e , " s t r i n g name ", out _new ) ;3 i f ( !_new )4 {5 MessageBox. Show (" O nly o ne i n s t a n c e c an be s t a r t e d ! ") ;6 Application. Exit( ) ;7 r e t u r n;8 }
3.2.4 Semaphore
TheSemaphoreclass 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
-
7/25/2019 Indrumator II
44/77
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 Lockcan 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 S e m a p h o re m y S e m = 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 Program2 {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 ;56 s t a t i c v oi d Main (s t r i n g[ ] args )7 {
8 f o r (i n t i = 1 ; i
-
7/25/2019 Indrumator II
45/77
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
-
7/25/2019 Indrumator II
46/77
3. Threads
38
-
7/25/2019 Indrumator II
47/77
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
-
7/25/2019 Indrumator II
48/77
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 S q lC o n n e c t i o n m y C o n=new SqlConnection (" Data Source=serverDb ;
Databas e=dbName; User ID=us er Id ; Password=pass ") ;4 myCon. Open( ) ;5 . . .
Where:
serverDb is the MSSQL server host;
dbName is the name of the database;
40
-
7/25/2019 Indrumator II
49/77
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 S q lC o m m a n d c m d = 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
-
7/25/2019 Indrumator II
50/77
4. Database
4.1.3 DataReader
The data from a database can be read by usingDataReader. 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 D a ta S et d s = new DataSet( ) ;
2 S ql D a t a A d a p t er d a = new SqlDataAdapter ("SELECT from myTable" ,
my Co n )
* 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.A dd (my DS . Tables[" T a b l e1 "] . Columns[" id "] , myDS.Tables
[" T a b l e 2 "] . Columns[" id "] ) ;
42
-
7/25/2019 Indrumator II
51/77
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: Universitiesand Faculties.
Before creating the project, launch SQL Server Configuration Management from
Start Programs Microsoft SQL Server 2008 Configuration Toolsand 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
Figure4.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
-
7/25/2019 Indrumator II
52/77
4. Database
Table 4.1: Universities
Column name Data type Allow Nulls
Id int NoNameUniv text NoCity text NoCode int No
Table 4.2: Faculties
Column name Data type Allow Nulls
Code int NoNameFac text No
presented in the tables4.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 Universitiesand Faculties. Now, lets add some
data in our tables. Right click on your Table, then selectShow Table Dataand 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
-
7/25/2019 Indrumator II
53/77
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;23 namespace myDatabase4 {5 p u b l i c partial c l a s s Form1 : Form6 {7 p u b l i c Form1( )8 {9 I n i t i a l i z e C o m p o n e n t( ) ;
10 }1112 p r i v at e v oi d Form1_Load (o b j e c t sender, E v e n tA r g s e )13 {
14 S q l C o n n e c ti o n m y C o n=new S q l C o n n e c t i o n( ) ; / / s e t up a SQLC on n ec t io n o b j e c t
15 }16 }17 }
After you set up the Connection object, the ConnectionString property can be
accessed. Thus, selectData Show Data Sourceand 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 NewConnectionbutton and then selectMicrosoft SQL Server Database File,Continueand
then browse to the database location.
You will find the seeking string (example: "Data Source=.
SQLEXPRESS;AttachDbFilename=DataDirectory
Database1.mdf;Integrated Security=True;User Instance=True") by expandingConnec-
tion String.
After your SqlConnection line, add the following code:
1 myCon. ConnectionString=" Data So ur ce =.\SQLEXPRESS; AttachDbF ilen ame =|
Da ta Dire c to ry |\ Da ta ba s e 1 . mdf ; In t e g r a te d S e c u ri ty =T ru e ; Us e r
In s ta n c e =T ru e ";
When you add this code in C# you will notice that errors are signaled. This
45
-
7/25/2019 Indrumator II
54/77
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 So ur ce =.\\SQLEXPRESS; AttachDb Filen ame
=|Da ta Dir e c to ry |\ \ Da ta b as e 1 . mdf ; In te g ra t e d S e c u ri ty =T ru e ; Us e r
In s ta n c e =T ru e ";
1 myCon. ConnectionString=@ " Data So ur ce =.\SQLEXPRESS; AttachD bFile name
=|Da ta Dir e c to ry |\ Da ta b as e 1 . mdf ; In te g ra t e d S e c u ri ty =T ru e ; Us e r
In s ta n c e =T ru e ";
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 cre-
ated, display in a ListBox all the Universities, in a TextBox the university code and
in another the corresponding faculty.
46
-
7/25/2019 Indrumator II
55/77
My first database
Listing 4.2: Example
1 p r i v at e v oi d Form1_Load (o b j e c t sender, E v e n tA r g s e )2 {
3 myCon. Open( ) ;4 dsUniv = new DataSet( ) ;5 dsFac = new DataSet( ) ;67 dsUniv = new SqlDataAdapter ("SELECT f r om U n i v e r s i t i e s ",
my Co n ) ;8 daUniv. Fill ( dsUniv , " U n i v e r s i t i e s ") ;9
10 daFac = new SqlDataAdapter ("SELECT f r om F a c u l t i e s ", myCon );
11 daFac. Fill ( dsFac, " F a c u l t i e s ") ;1213 f o r e a c h ( D a ta R o w d r i n dsUniv. Tables[" U n i v e r s i t i e s "] . Rows )14 {
15 S t ri n g n a me = dr. ItemArray. GetValue (1 ) .ToString( ) ;16 listBox1. Items.A dd ( name ) ;17 }18 }1920 p r i v at e v oi d l i s t B o x 1 _ S e l e c t e d I n d e x C h a n g e d (o b j e c t sender, EventArgs
e )21 {22 S t r i n g U n i v S e l e c te d = listBox1. SelectedItem.ToString( ) ;2324 f o r e a c h ( D a t aR o w d r 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 }3233 f o r e a c h ( D a t aR o w d r 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
-
7/25/2019 Indrumator II
56/77
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
-
7/25/2019 Indrumator II
57/77
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 AccessProtocol (SOAP).
Figure 5.1: Web Services Triangle Architecture. Source: [2]
49
-
7/25/2019 Indrumator II
58/77
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 isused 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 figure5.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 Projectbutton 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
-
7/25/2019 Indrumator II
59/77
Getting started
Explorer (see Figure5.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 WorldWeb Service
1 u s i n g System;2 u s i n g System. Collections. Generic;3 u s i n g System. Linq;4 u s i n g System. W eb ;5 u s i n g System. W eb . Services;6
7 namespace WebService18 {9 // /
10 / // Summary d e s c r i p t i o n f o r S e r v i c e 111 // / 12 [WebService ( Namespace = " http :// tempuri . org /") ]13 [W e b S e r v i c e B in d i n g ( ConformsTo = WsiProfiles. B a s i c P r o f i le 1 _ 1 ) ]14 [System. ComponentModel. ToolboxItem (f a l s e) ]15 // To a l lo w t h i s Web S e r vi c e t o b e c a l l e d fr om s c r i p t , u si n g
ASP.NET AJAX, uncomment the fo ll ow in g l i n e .16 / / [ S ys te m . 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 ub l ic c l a s s Service1 : System.W eb .Services. WebService18 {
19 [WebMethod]20 p u bl i c s t r i n g HelloWorld( )21 {22 r e t u r n " He l lo W orld " ;23 }24 }25 }
51
-
7/25/2019 Indrumator II
60/77
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 bl i c s t r i n g HelloWorld( )3 {4 r e t u r n " He l lo W orld " ;5 }
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 [WebMethod]2 p u bl i c i n t Ad d (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
Figure5.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
-
7/25/2019 Indrumator II
61/77
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 projectmyFirstClient. Then, add a web service reference to the
client, as shown in the Figures5.5 and 5.6.
Figure 5.5: Add service reference (1)
Figure 5.6: Add service reference (2)
53
-
7/25/2019 Indrumator II
62/77
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.7and
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: TheClient code
1 s t a t i c v oi d Main (s t r i n g[ ] args )2 {3 myFirstClient. localhost. S e r v i c e1 s e r v i c e = new
my Fi rs t Cl ie nt . localhost. Service1( ) ;4 i n t su m= service. A dd (2 ,3 ) ;5 Console. WriteLine (" The sum i s "+su m.ToString() ) ;6 Console.ReadKey( ) ;7 }
Exercise: Create another client for making use of your service.
54
-
7/25/2019 Indrumator II
63/77
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
-
7/25/2019 Indrumator II
64/77
5. Web Services
56
-
7/25/2019 Indrumator II
65/77
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 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
-
7/25/2019 Indrumator II
66/77
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 Figure6.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
-
7/25/2019 Indrumator II
67/77
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 5 6 7 8 9
10 11
Buttons
Figure 6.2: WPF button
59
-
7/25/2019 Indrumator II
68/77
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 u s i n g S ys te m;2 u s i n g S ys te m.C o l l e c t i o n s. G e n e r i c;3 u s i n g S ys te m.Linq;4 u s i n g S ys te m.Text;5 u s i n g S ys te m. Windows ;6 u s i n g S ys te m. Windows .C o n t r o l s;7 u s i n g S ys te m. Windows . Data ;8 u s i n g S ys te m. Windows .Documents;9 u s i n g S ys te m. Windows .In p u t;
10 u s i n g S ys te m. Windows .Media;11 u s i n g S ys te m. Windows .Media.Imaging;12 u s i n g S ys te m. Windows .N a v i g a t i o n;13 u s i n g S ys te m. Windows .Shapes;1415 namesp ace MyFirstWPF16 {17 p u b l i c p a r t i a l c l a s s MainWindow : Window18 {19 pu bl ic MainWindow( )20 {21 I n i t i a l i z e C o m p o n e n t( ) ;22 }
2324 p r i v a t e v o i d b u tt o n1 _ Cl i ck (o b j e c t s en de r, RoutedEventArgs e )25 {26 MessageBox. Show (" Hi ! ") ;27 }28 }29 }
60
-
7/25/2019 Indrumator II
69/77
Getting started
The XML button code is listed in the following.
Listing 6.3: XML button code
1 5 6 7 8 9
10 11 12
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
The table6.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 clearedComboBox 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
-
7/25/2019 Indrumator II
70/77
6. Windows Presentation Foundation
6.1.2 Layouts
In WPF, the layouts are used for arranging controls in complex environments. The
Table6.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 childs 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.
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
-
7/25/2019 Indrumator II
71/77
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 DataBinding.
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 tag, the style definition must be added.
1 2 3 4 5 6 7 8
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
Multiple sliders can have the same style assigned. This solves the problem of
modifying a property in several controls.
63
-
7/25/2019 Indrumator II
72/77
6. Windows Presentation Foundation
Listing 6.4: Example with multiple sliders
1 5 6 7 8 9
10 11 12 13 14 15
16 17 18 1920 21 22 23 24 25 26 27 28
29
30
31 32 33
34
35
-
7/25/2019 Indrumator II
73/77
Styling and Data Binding
Name=" textbox 3 "/>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 bidi-
rectional (source target).
Data Binding between UI Elements
The issue of displaying the slider value in a TextBoxand be able to modify data in
both directions is much simpler to be solved in WPF. To bind a TextBoxcontrol to a
Slider, the TextBox.Text property must be binded to the Slider.Valueproperty.
1
In order to implement this, the Text property contains a binding definition.
ElementNamerefers to the control the TextBox binds.
ThePath value represents the target object property to be displayed.
UpdateSourceTriggerrepresents the event which triggers the data exchange be-
tween the controls.
65
-
7/25/2019 Indrumator II
74/77
6. Windows Presentation Foundation
Modesets the direction in which the data should be exchanged, in this case we
want the slider to modify the TextBoxvalue 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 and6.6.
Listing 6.5: XML code
1 5 6 7 9 10 < E l l i p s e. F i l l>11
12 13 14 15 16 < E l l i p s e. RenderTransform>17 19 20 21 22 23
66
-
7/25/2019 Indrumator II
75/77
Animations
Listing 6.6: C#code
1 u s i n g S ys te m;2 u s i n g S ys te m.C o l l e c t i o n s. G e n e r i c;
3 u s i n g S ys te m.Linq;4 u s i n g S ys te m.Text;5 u s i n g S ys te m. Windows ;6 u s i n g S ys te m. Windows .C o n t r o l s;7 u s i n g S ys te m. Windows . Data ;8 u s i n g S ys te m. Windows .Documents;9 u s i n g S ys te m. Windows .In p u t;
10 u s i n g S ys te m. Windows .Media;11 u s i n g S ys te m. Windows .Media.Imaging;12 u s i n g S ys te m. Windows .N a v i g a t i o n;13 u s i n g S ys te m. Windows .Shapes;1415 namespace Animation16 {
17 / // 18 / // I n t e r a c t i o n l o g i c f o r M ainWindow . x am l19 / // 20 p u b l i c p a r t i a l c l a s s MainWindow : Window21 {22 pu bl ic MainWindow()23 {24 I n i t i a l i z e C o m p o n e n t ( ) ;25 Compositi onTarget . Rendering += Move ;2627 }2829 I n t3 2 c o un t er = 0 ;
30 v o i d Move ( o b j e c t s e n d e r , E ve n tA r gs e )31 {32 c o un t er = c o un t er + 2 ;33 C an va s . S e t L e f t ( b a l l , c o u n te r ) ;34 }35 }36 }
67
-
7/25/2019 Indrumator II
76/77
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
-
7/25/2019 Indrumator II
77/77
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.