Programming With .NET Introduction
Course 502
502/CN/P.1/403/O.3
© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
© LEARNING TREE INTERNATIONAL, INC.All rights reserved.
All trademarked product and company names are the property of their respective trademark holders.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, or translated into any language, without the prior written
permission of the publisher.
Copying software used in this course is prohibited without the express permission of Learning Tree International, Inc. Making unauthorized copies of
such software violates federal copyright law, which includes both civil and criminal penalties.
© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The author would like to acknowledge the following for their contributions tothis course:
Stacy Diehl
Ulf Malmström
Candice Ciampa
Mike Murray
Nancy Wong Bryan
My wife, Martine
Lysander Rehnstrom
Joey Gagliardo
Acknowledgments
Introduction and Overview
© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this course, you will
Design and program applications using Microsoft .NET and Visual Studio
Learn the syntax of the Visual Basic (VB) and C# programming languages
Write a .NET Windows Forms application
Code for reuse using object orientation, inheritance, and class libraries
Create and program an ASP.NET website
Allow users to log in and create accounts using Web Forms authentication
Create a SQL Server database
Save and access database data using .NET
Deploy .NET Windows and web applications
Course Objectives
20-
© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Introduction and Overview
Chapter 1 Starting to Program .NET With Visual Studio
Chapter 2 C# and Visual Basic Language Syntax
Chapter 3 Programming Windows User Interfaces
Chapter 4 Object-Oriented Programming
Chapter 5 Designing Web User Interfaces With ASP.NET
Chapter 6 Saving Data With Relational Databases
Chapter 7 Deployment
Chapter 8 Course Summary
Course Evaluation
Appendix A Answers to Review Questions and Glossary
Course Contents
30-
© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Course Materials
Course Notes• Copies of all slides and supplemental
presentation material
Exercise Manual
Visit your My Learning Tree account for additional information and resources related to this course
40-
© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Can be done in either C# or Visual Basic
Many exercises have bonuses• Have much less direction• Designed to apply what you have learned
C:\502 folder• Contains starting points for each
exercise• Contains incremental solutions
for all exercises• Feel free to copy and paste code
from the finished exercisesolutions if you prefer
Solution launcher provides quickaccess to exercises and solutions
Course Exercises
C# code
VB code
Exercise starting points
Finished exercises
50-
© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Please visit our .NET blog• http://dotnet.learningtree.com
Learning Tree International’s .NET Blog
60-
Starting to Program .NET With Visual Studio
Chapter 1
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
After completing this chapter, you will be able to • Create a simple .NET program
To accomplish this, you will Create a Visual Studio project Learn the basics of .NET programming Design and program classes Add data to classes with properties Add behavior to classes with methods Begin programming our case study
Chapter Objectives
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Chapter Contents
Creating Programs in Visual Studio Hands-On Exercise 1.1
Analyzing the Flash Cards Application
Classes, Variables, and Properties
Objects
Hands-On Exercise 1.2
Methods
Hands-On Exercise 1.3
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
The .NET Framework is so large, parts of it have been given names• ASP.NET is the part of the framework used for building Web applications• Windows Forms and WPF are used for building desktop applications
.NET Application Types
ASP.NET Windows Forms
ADO.NET
Windows Presentation Foundation (WPF)
LINQ to SQL
Windows Communication Foundation (WCF)
Windows Workflow Foundation (WF)
C# and VB Language Enhancements
LINQ to Objects Entity Framework
System.XML Web Services Remoting
ClickOnce Deployment
2.0
3.0
3.5
Parallel Computing F#, Iron Python, Iron Ruby
4.0
Dynamic Language Runtime
Vers
ions
4.5 Windows Azure HTML 5
Windows 8 and Windows Phone Development
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Visual Studio is the main tool for creating .NET applications
Any kind of computer application can be created with .NET• Windows applications• Web applications• Console
applications• And others
Visual Studio
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Visual Studio Solutions are used to create applications• Solutions consist of one or more projects
Projects consist of • Source-code files• References to external code libraries used by the project• Resources (like graphics and audio files)• Configuration files
To create a Visual Studio project:• Open Visual Studio• Select File | New |
Project• This opens the New
Project dialog
Visual Studio Solutions and Projects
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Select a programming language• Visual Basic and C# are the most common
– These languages will be covered in this course
Specify the name of theproject• Location will be a folder
to save the project in
Choose the project template• Windows, Console,
Empty Project, etc.
New Project Dialog
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Choosing a Language Illustrated
MicroSoft Intermediate Language code (MSIL)
Hardware
Operating system
Common Language Runtime (CLR)
VB code
VB compiler (vbc.exe)
C# code
C# compiler (csc.exe)
Other languages
Other language compilers
Machine code
9© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Choosing a template tells Visual Studio to• Set references to .NET libraries that
are most common for that application type• Set default project properties appropriate
to that application type• Create default files that can be used as
templates
In the exercise, you will choose the Empty Project template• This is to demonstrate some of what
Visual Studio automates
Visual Studio Project Templates
10© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Used to manage projects in Visual Studio• Lists a project’s files and references
Right-click the project to• Add code files (classes)• Access project properties• Build the project (compile)• And more
Solution Explorer
11© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
A class is the primary container for code in a .NET program• Defined using the Class keyword• Classes contain data (variables) and behavior (functions)
Visual Basic and C# code:
Classes can contain• Properties (to save data)• Methods (functions declared inside a class)• Events (messages sent from the class)• Constructors (functions that are run automatically when the class is used)
Classes
We’ll discuss each of these in detail later
public class FlashCards{
}
Public Class FlashCards
End Class
def·i·ni·tion
12© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
All code in .NET must be written inside a class• Classes are kept in source-code files
To create a class1. Right-click the project in Solution Explorer2. Select Add | Class3. Give the class a name
appropriate to the code it will contain
Adding Code
13© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
A statement is a line of code
In Visual Basic, statements end at the end of a line• Long lines can be divided using the space + underscore character ( _)
– Since 2010, VB supports implied line continuation, so the underscore is not always necessary
In C#, statements end with a semicolon (;)
Visual Basic code:
Statements
Each line of code is a statement
Space + underscore indicates that multiple lines are treated as a single statement
def·i·ni·tion
14© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
C# code:
Statements
Each statement ends with a semicolon
Missing semicolon indicates that multiple lines are treated as a single statement
15© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
When a program starts, the computer needs to know what to do first• In .NET, that is a function called Main• The .NET runtime calls this function when the program executes
Visual Basic code:
C# code:
A Program’s Entry Point
Public Class StartupPublic Shared Sub Main()
Console.WriteLine("Welcome to Flash Cards!")Console.ReadLine()
End SubEnd Class
class Startup{
public static void Main(){
Console.WriteLine("Welcome to Flash Cards!");Console.ReadLine();
}}
We’ll discuss creatingfunctions and the Shared/statickeywords later
16© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
We’ve been hired by our local elementary school to write a program to help the kids master basic math skills (addition, subtraction, multiplication, and division). Essentially, the program is an electronic version of flash cards, which you may have been quizzed with when you were a child.
To keep costs down, the school has asked us to keep the program as simple as possible, using just a character-based User Interface (UI).
Later, the school is hoping to add more features if the program is well received.
Case Study: The Flash Cards Program
∑Xii=1X =
n
ŋ
17© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Two main methods:• Console.WriteLine()—Outputs a message to the user• Console.ReadLine()—Waits for the <Enter> key and collects the user’s
input• Console application ends when there is nothing left for it to do
– Use Console.ReadLine() to prevent the program from exiting
Programming Console Applications
18© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Chapter Contents
Creating Programs in Visual Studio
Hands-On Exercise 1.1 Analyzing the Flash Cards Application
Classes, Variables, and Properties
Objects
Hands-On Exercise 1.2
Methods
Hands-On Exercise 1.3
19© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Hands-On Exercise 1.1
In your Exercise Manual, please refer to Hands-On Exercise 1.1: Creating the FlashCards Project
20© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Helps the programmer find errors• Breakpoints can be set to stop the program’s execution• Can single-step through code by pressing the <F11> key• Can resume the program by pressing <F5>
To set a breakpoint, click the gray border on the left side of the code window
The Debugger
21© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Add comments to code and document what everything does• In VB, anything prefixed with an apostrophe (') is ignored by the compiler• In C#, use two slashes (//)
Make your code easy for the next programmer to understand• Use descriptive variable and method names and avoid abbreviations• Divide long, complex statements into multiple statements• Include detailed messages when throwing exceptions
Commenting Code
Remember, the next programmer who has to figure out your code will probably be you!
22© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Chapter Contents
Creating Programs in Visual Studio
Hands-On Exercise 1.1
Analyzing the Flash Cards Application
Classes, Variables, and Properties
Objects
Hands-On Exercise 1.2
Methods
Hands-On Exercise 1.3
23© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
We talked to the customer regarding how the Flash Cards program should work—below is what we found:
The program should ask the students (users) who they are
Before each question, the program should ask students what math operation they want to be quizzed on• Addition, subtraction, multiplication, or division
It will build an equation using two randomly generated numbers between 0 and 99
The students will then provide the answer and be told whether they were correct
The program should keep track of the number of questions the students answer correctly and inform them of their percentage score after each answer
Each time, the students should be asked whether they want to continue
Our Case Study: Flash Cards Requirements
24© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Your instructor will divide you into groups, then take a few minutes to do the following: • The data required by the program will be stored inside properties• Read through the requirements• In the top portion of the box below, list the properties needed by the program
Analyzing the Data Required for Flash Cards
FlashCardsGame
Methods will go here
Do Now
25© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Again in your groups, take a few minutes to do the following: • The things the program will need to do will determine its methods• Again, read through the requirements• Below the properties, list the methods needed in the Flash Cards program
Analyzing Flash Cards Functionality
FlashCardsGame
Properties should be here
Do Now
26© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
The properties and the methods (functions) we will use in the Flash Cards program are documented below:
Solution: Flash Cards Requirements
FlashCardsGame
UserOperationNumber1Number2TriesCorrect
GenerateNumbers()BuildEquation()CheckAnswer()CalculatePercentCorrect()CalculateCorrectAnswer()
27© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Chapter Contents
Creating Programs in Visual Studio
Hands-On Exercise 1.1
Analyzing the Flash Cards Application
Classes, Variables, and Properties Objects
Hands-On Exercise 1.2
Methods
Hands-On Exercise 1.3
28© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
A variable is a named location in memory used to store, retrieve, and change data
Must specify two things when declaring a variable:• Variable name• Data type
Variable name rules:• Must begin with a letter or underscore ( _ )• Can contain only letters, numbers, and underscores ( _ )• Cannot be a keyword• In C#, variable names are case-sensitive, but not in Visual Basic
Data type• Specifies how much memory to reserve• The computer ensures that the data at that location is valid
Variables def·i·ni·tion
29© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Visual Basic code:
C# code:
Variable Declaration Examples
string input;double answer;
Dim input As StringDim answer As Double
30© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
VB keyword C# keyword TypeString string Used to store characters (text)Integer int Used to store whole numbersDouble double Used to store numbers with a decimalDate DateTime Used to store dates and timeBoolean bool Used to store true or false
Some Common Data Types
We’ll cover data types in detail later
31© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
VB and C# Operators
Operation VB C# NotesAddition + +
Subtraction - -
Multiplication * *
Division / /
Integer Division \ N/A In C#, dividing integers results in integer divisionModulus Mod % Divides, and returns only the remainderExponentiation ^ N/A Use Math.Pow() function in C#
Increment N/A ++ Add 1Decrement N/A -- Subtract 1Assignment = =
Add to += += x += 1 is equivalent to x = x + 1
Subtract from -= -= x -= 1 is equivalent to x = x - 1
Multiply by *= *= x *= 1 is equivalent to x = x * 1
String concatenation & or + +
32© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Properties provide access to the data stored in a class• Short syntax allows them to be created with a single line• Longer syntax on next slide allows additional logic to be added to properties
Visual Basic code:
C# code:
Properties def·i·ni·tion
Public Property User As StringPublic Property Number1 As DoublePublic Property Number2 As DoublePublic Property Correct As Integer
public string User{ get; set; }public double Number1{ get; set; }public double Number2{ get; set; }public int Correct{ get; set; }
33© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Logic can be added to properties when they are fully implemented• Allows for data manipulation or validation to be done within the property
Properties contain two parts:• Get clause is used when the value of the property is requested• Set clause is used when a change in the value is requested
Properties could be read- or write-only by removing the Set or Get clause
Data is in this case actually saved in _operation variable• Keyword Private means that _operation cannot be accessed directly
from outside the class
VB code:
Fully Implemented Properties
Private _operation As StringPublic Property Operation() As String
GetReturn _operation
End GetSet(value As String)
_operation = valueEnd Set
End Property
34© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
C# code:
Fully Implemented Properties
private string _operation;public string Operation{
get{
return _operation;}set{
_operation = value;}
}
35© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Chapter Contents
Creating Programs in Visual Studio
Hands-On Exercise 1.1
Analyzing the Flash Cards Application
Classes, Variables, and Properties
Objects Hands-On Exercise 1.2
Methods
Hands-On Exercise 1.3
36© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
An object is an instance of a class in memory• Hence the term object-oriented programming
Create a variable of the class type and construct it with the New keyword• New tells the computer to create an instance of the class in memory
Visual Basic code:
• Declaration can be done on two lines
C# code:
Objects
Dim game As New FlashCardsGame()
Dim game As FlashCardsGamegame = New FlashCardsGame()
def·i·ni·tion
FlashCardsGame game = new FlashCardsGame();
FlashCardsGame game;game = new FlashCardsGame();
37© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Once constructed, an object’s public properties and methods can be accessed
Visual Basic code:
C# code:
Using an Object
User is a property of the FlashCardsGame class
GenerateNumbers is a method of the FlashCardsGame class
game.User = Console.ReadLine();Console.WriteLine("Welcome " + game.User);game.GenerateNumbers();
game.User = Console.ReadLine()Console.WriteLine("Welcome " + game.User)game.GenerateNumbers()
game is an instance of the FlashCardsGame class
38© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Chapter Contents
Creating Programs in Visual Studio
Hands-On Exercise 1.1
Analyzing the Flash Cards Application
Classes, Variables, and Properties
Objects
Hands-On Exercise 1.2 Methods
Hands-On Exercise 1.3
39© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Hands-On Exercise 1.2
In your Exercise Manual, please refer to Hands-On Exercise 1.2: Creating the FlashCardsGame Class
40© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Chapter Contents
Creating Programs in Visual Studio
Hands-On Exercise 1.1
Analyzing the Flash Cards Application
Classes, Variables, and Properties
Objects
Hands-On Exercise 1.2
Methods Hands-On Exercise 1.3
41© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
A method is a named block of code that performs a series of statements• Must be inside a class• Require a unique name that should be descriptive• May or may not return a value • Can have arguments (parameters) passed to them
Public methods can be called from outside the class
Private methods are used as helper functions• Called only from within the class
Methods def·i·ni·tion
42© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Methods usually return some value• Can be any data type• Return data type is defined when defining the function• Return keyword is used to return the value and exit the function
Visual Basic code:
C# code:
Coding Methods
Public Function BuildEquation() As String
'Code omittedReturn Number1.ToString() + "+" + Number2.ToString()
End Function
public string BuildEquation(){
// Code omittedreturn Number1.ToString() + "+" + Number2.ToString();
}
43© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Often arguments or variables are passed into methods• Allows the function to be more flexible• Each argument must have a name and data type like any other variable• Any number of arguments can be passed, separated by commas
Visual Basic and C# code:
Passing Arguments to Methods
Public Function CheckAnswer(answer As Double) _ As Boolean
'Code omittedIf CalculateCorrectAnswer() = answer Then…
End Function
public bool CheckAnswer(double answer){
// Code omittedif (CalculateCorrectAnswer()== answer)…
}
44© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Some methods just do things and do not return any value• In VB, these are known as subroutines
– Defined with the keyword Sub• In C#, these are functions with a return type of void
Visual Basic code:
C# code:
Methods That Do Not Return Anything
public void GenerateNumbers(){
Random randomNumber = new Random();Number1 = randomNumber.Next(0, 99);Number2 = randomNumber.Next(0, 99);
}
Public Sub GenerateNumbers()Dim randomNumber As New Random()Number1 = randomNumber.Next(0, 99)Number2 = randomNumber.Next(0, 99)
End Sub2
45© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
All code (fields, methods, properties, events, and constructors) must be inside a class
VB code
Code Placement
Public Class FlashCardsGame
Public Property User As StringPublic Property Number1 As DoublePublic Property Number2 As Double
Public Sub GenerateNumbers()Number1 = 1Number2 = 2
End Sub
Public Function BuildEquation() As StringReturn "1 + 2"
End Function
End Class
Class starts
Class ends
Properties
Method
Method
46© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
C# code
Code Placement
public class FlashCardsGame{
public string User{ get; set; }public double Number1{ get; set; }public double Number2{ get; set; }
public void GenerateNumbers(){
Number1 = 1;Number2 = 2;
}
public string BuildEquation(){
return "1 + 2"; }
}
Class starts
Class ends
Properties
Method
Method
47© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Chapter Contents
Creating Programs in Visual Studio
Hands-On Exercise 1.1
Analyzing the Flash Cards Application
Classes, Variables, and Properties
Hands-On Exercise 1.2
Objects
Methods
Hands-On Exercise 1.3
48© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Hands-On Exercise 1.3
In your Exercise Manual, please refer to Hands-On Exercise 1.3:
Adding Methods to the FlashCardsGame Class
49© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
You are now able to• Create a simple .NET program
You have Created a Visual Studio project Learned the basics of .NET programming Designed and programmed classes Added data to classes with properties Added behavior to classes with methods Begun programming our case study
Chapter Summary
50© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
What are the different types of applications that can be created with .NET?
What is a .NET program’s entry point?
Which are the two most common .NET languages? Which is better?
What tool in Visual Studio is used to manage projects?
What is a statement?
Chapter 1 Review Questions
51© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-
Code in .NET must be written inside a:
Name three things that might be in a class:
What must be specified when declaring a variable?
Properties provide access to what within a class?
Define a method:
Chapter 1 Review Questions
C# and Visual Basic Language Syntax
Chapter 2
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
After completing this chapter, you will be able to • Program in C# and Visual Basic
To accomplish this, you will Investigate data types and type conversions Use If and Case statements to allow programs to make decisions Program loops Handle errors
Chapter Objectives
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Chapter Contents
Data Types and Type Conversions Hands-On Exercise 2.1
Decision-Making Statements
Hands-On Exercise 2.2
Repeating Code With Loops
Hands-On Exercise 2.3
Exceptions
Hands-On Exercise 2.4
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
When a variable is declared, its data type is specified• Determines the amount of memory allocated for the variable
.NET ensures that a variable’s value is valid for its type• This is known as type safety
If we enter the following code, what would happen if the user typed Joe?
_____________________________________________________________
A variable must be of an appropriate data type for the data it will contain
Sometimes its value must be converted to other data types
Data Types
Dim Age As IntegerConsole.WriteLine("Enter your age.")Age = Console.ReadLine()
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Can contain any series of letters, numbers, and symbols• Can be very large• Amount of memory consumed depends on the size of the string
In .NET, a wealth of functionality is built into the String data type• Below are some common examples:
Strings
Member DescriptionLength Returns the number of characters in the string
ToUpper() Converts the string to all uppercase characters
ToLower() Converts the string to all lowercase characters
Trim() Removes all whitespace characters from the beginning and end of the string
Replace() Replaces all occurrences of one string of characters with anotherStartsWith() Determines whether the string begins with a specified value
SubString() Retrieves part of the string; enter the start character and the number of characters to retrieve; the first character is character 0
IsNullOrEmpty() Returns a true if the string has no value.
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
What is the value of String2?
Now what is the value of String2?
Now what is the value of String2?
Examples of Using the String Type
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Adding strings together is called concatenation• Done with the + operator in both C# and VB• Can also be done with & in VB
Complex concatenation can be simpler with the String.Format()method
• The {#} characters embedded in the string are placeholders for variables
• After the string, the correct number of arguments are passed to the function
• The variables replace the placeholdersin the resulting string
String Concatenation and String.Format()
Console.WriteLine("Welcome " + game.User);
Console.WriteLine( String.Format("Your score is {0} out of {1} for {2}%", game.Correct, game.Tries, game.PercentCorrect));
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Are numbers that do not include a decimal• Can be positive or negative
In .NET, there are different types of integers• The more memory the integer consumes, the bigger the number can be• Types include Short, Integer, and Long
When declaring a variable, which integer type should you choose?
Integers
9© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
The code example below shows the largest number for each integer type• i consumes 2 bytes of memory• j consumes 4 bytes of memory• k consumes 8 bytes of memory• The values could be similarly negative
• Is it necessary to memorize the upper and lower bound of each type?
In C#, the types are short, int, and long
Integer Sizes
10© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Real Numbers
Numbers that include a decimal• Can be both positive and negative• Range depends on the precision (number of decimal places)
VB type C# type Bytes Used forSingle float 4 Small real numbersDouble double 8 Large real numbersDecimal decimal 16 Currency calculations
11© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Numeric types have a method called Parse()• Expects a string argument• Will do the conversion if it is possible
If the string cannot be successfully converted to the number, an exception is raised
Visual Basic code:
Converting Strings to Numbers
More on exception handling later
12© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
TryParse() takes two arguments and returns True or False• First argument is the string to be converted to a number• Second argument is the numeric variable that will hold the conversion
– In C#, the out keyword must be used before second argument• If the string cannot be converted to a number, False is returned; otherwise True
Visual Basic and C# code:
Converting Strings to Numbers With TryParse()
Dim input As StringDim answer As Doubleinput = Console.ReadLine()If Double.TryParse(input, answer) = False Then
Console.WriteLine("Invalid input, try again.")End If
string input;double answer;input = Console.ReadLine();if (Double.TryParse(input, out answer) == false){
Console.WriteLine("Invalid input, try again.");}
13© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
All .NET types have a method called ToString()• Always converts that type to a string representation of the value
C# code:
Converting Numbers to Strings
14© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Stored as a number but can be only True or False• ToString() method returns string “True” or “False”• Boolean.Parse() method takes a string “True” or “False” and converts it to
a Boolean
Visual Basic and C# code:
Boolean Data Type
15© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Dates
Represented as DateTime type• Actually stored as an 8-byte numeric variable• Range from 1/1/0001 to 11:59:59 PM 12/31/9999• Time is precise to 100 nanoseconds (ticks)
Numerous methods for performing date and time calculations• DateTime.Now returns the current date and time• Add(), AddDays(), AddHours(), AddMilliseconds(), etc.
Numerous methods for converting dates and time to a string
Method() Returns (on a U.S. computer)ToString() 9/8/2004 7:47:25 PMToLongDateString() Wednesday, September 08, 2004ToShortDateString() 9/8/2004ToLongTimeString() 7:47:25 PMToShortTimeString() 7:47 PM
16© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
An array is a variable that can contain multiple values
The size of the array must be specified when declaring it• Each value is referred to by its index number• Indexes in .NET always begin with the number 0
In Visual Basic, when declaring an array, the upper bound is specified• Use parentheses for accessing items in the array
In C#, the number of items that the array can hold is specified• Use square brackets for accessing items in the array
Arrays
Dim MonthSales(11) As Double
double[] MonthSales = new double[12];
def·i·ni·tion
17© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Chapter Contents
Data Types and Type Conversions
Hands-On Exercise 2.1 Decision-Making Statements
Hands-On Exercise 2.2
Repeating Code With Loops
Hands-On Exercise 2.3
Exceptions
Hands-On Exercise 2.4
18© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Hands-On Exercise 2.1
In your Exercise Manual, please refer to Hands-On Exercise 2.1: Programming Data Types
19© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
In VB and C#, data-type conversions can be done in the following ways:• Use some method built into the data type• Use a method built into the System.Convert class• Use a function built into the language
– More common in Visual Basic• Perform a cast
Type Conversions Review
20© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
If there is a method of the data type that will do the conversion, use it• It will likely be the most efficient
VB and C# code:
Type Conversions: Code Examples
Dim s As String = "100"Dim n As Double = 100.0Dim i As Integeri = Integer.Parse(s)i = System.Convert.ToInt32(s)i = CInt(s)i = CType(n, Integer)
string s = "100";double n = 100.00;int i;i = int.Parse(s);i = System.Convert.ToInt32(s);i = (int)n;
We’ll see more examples of doing type casts later in the course
21© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Implicit Type Conversions
.NET will do an implicit type conversion when there cannot be loss of data• Larger types can be assigned values of smaller types implicitly• Floating-point numbers can be assigned integer values implicitly
In the following code sample, which statement is not valid and why?
22© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Chapter Contents
Data Types and Type Conversions
Hands-On Exercise 2.1
Decision-Making Statements Hands-On Exercise 2.2
Repeating Code With Loops
Hands-On Exercise 2.3
Exceptions
Hands-On Exercise 2.4
23© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Sometimes the program needs to decide only whether to do something• If the divisor does not equal zero, then do the math
Can be written on one line or multiple lines• If written on multiple lines, the block of code needs to be ended
Visual Basic code:
If Statement
In VB, an If block ends with the End Ifstatement
In C#, if blocks are contained inside curly braces
C# code:
24© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
If-Then statements can test against one or more criteria expressions• Boolean operators are used to determine whether a variable meets the criteria
Some Visual Basic and C# examples:
Criteria Expressions
If Job = "Programmer" Then GiveRaise()if(LoggedIn != true) Response.Redirect("Login.aspx");If Age < 18 Then ApplyDiscount()if (Hours > 40) CalculateOverTime();If EndDate >= StartDate Then RunReport()
To test for VB C#Equality = ==
Inequality <> !=
Less than < <
Less than or equal to <= <=
Greater than > >
Greater than or equal to >= >=
25© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Sometimes both of two criteria have to be true• Separate the criteria with AndAlso in Visual Basic or && in C#
Sometimes at least one of two criteria has to be true• Separate the criteria with OrElse in Visual Basic or || in C#
Multiple Criteria
If HireDate < Now.AddYears(-3) AndAlso LastRaise < Now.AddYears(-1) ThenPayRate = PayRate * 1.1
End If
If HireDate < Now.AddYears(-3) OrElse LastRaise < Now.AddYears(-1) ThenPayRate = PayRate * 1.1
End If
if (HireDate < DateTime.Now.AddYears(-3) && LastRaise < DateTime.Now.AddYears(-1)){
PayRate = PayRate * 1.1;}
if (HireDate < DateTime.Now.AddYears(-3) || LastRaise < DateTime.Now.AddYears(-1)){
PayRate = PayRate * 1.1;}
26© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Criteria expressions can be as complex as needed• Statements can be grouped together with parentheses
Multiple Criteria
If (HireDate < Now.AddYears(-3) AndAlso LastRaise < Now.AddYears(-1)) _OrElse Job = "Programmer" Then
PayRate = PayRate * 1.1
End If
if ((HireDate < DateTime.Now.AddYears(-3) && LastRaise < DateTime.Now.AddYears(-1))|| Job == "Programmer")
{PayRate = PayRate*1.1;
}
27© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Else clause allows for an alternative branch• If something is true, pursue one path• Else, go a different way
Visual Basic and C# code:
If-Then-Else
28© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Sometimes more than two branches are required• ElseIf clause allows for as many branches as required• Else can be used as the final case
Visual Basic code:
If-Then-ElseIf-Else
Note that only the code inside the first true condition will apply
29© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
C# code:
If-Then-ElseIf-Else
Note that only the code inside the first true condition will apply
30© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Is an alternative to an If statement with multiple conditions• A variable is checked against multiple cases • The code in the first matching case executes• Can have a default case at the end
Can be easier to read than a complex If statement
Visual Basic code:
Select…Case (switch) Statement
31© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
C# code:
Select…Case (switch) Statement
In C#, each case must end with some flow control statement. This is most often done with a break statement. A returnwould also work.
32© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Chapter Contents
Data Types and Type Conversions
Hands-On Exercise 2.1
Decision-Making Statements
Hands-On Exercise 2.2 Repeating Code With Loops
Hands-On Exercise 2.3
Exceptions
Hands-On Exercise 2.4
33© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Hands-On Exercise 2.2
In your Exercise Manual, please refer to Hands-On Exercise 2.2: Using If Statements
34© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Chapter Contents
Data Types and Type Conversions
Hands-On Exercise 2.1
Decision-Making Statements
Hands-On Exercise 2.2
Repeating Code With Loops Hands-On Exercise 2.3
Exceptions
Hands-On Exercise 2.4
35© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Are used when• The number of iterations is known• The number of iterations can be easily calculated
Require a variable to act as a counter, and a beginning and ending range• Each time through the loop, the variable is incremented by the amount
specified
For-Next Loops
36© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Visual Basic code:
C# code:
• What is another example of when a For-Next loop would be appropriate?
For-Next Loops
Public Sub PrintMonthlySales()
For i As Integer = 0 To 11 Step 1Console.WriteLine(Sales(i))
Next
End Sub
public void PrintMonthlySales(){
for (int i = 0; i < 12; i++){
Console.WriteLine(Sales[i]);}
}
In VB, an increment of 1 is the default, so it would rarely be specified. If one wanted to go backward, specify Step -1
37© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Are used when• It is impossible to know how many times to perform the loop• It would be too inefficient to make that calculation
Each statement inside the Do-Loop block is repeated
Visual Basic code:
• What is wrong with the above loop?
Do-While Loops
38© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Use when the operations inside the loop must always happen at least once
Visual Basic and C# code:
Give an example of when a bottom-evaluation Do loop would be appropriate:
Bottom-Evaluation Loops
do{game.GenerateNumbers();// Code to play the Flash Cards game omittedConsole.WriteLine("Do you want to play again (Y or N)?");input = Console.ReadLine();
} while (! input.ToUpper().StartsWith("N"));
Dogame.GenerateNumbers()' Code to play the Flash Cards game omittedConsole.WriteLine("Do you want to play again (Y or N)?")input = Console.ReadLine()
Loop While Not input.ToUpper().StartsWith("N")
39© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Use when the operations inside the loop may never be needed
Visual Basic and C# code:
• Give an example of when a top-evaluation loop would be appropriate:
Top-Evaluation Loops
40© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Chapter Contents
Data Types and Type Conversions
Hands-On Exercise 2.1
Decision-Making Statements
Hands-On Exercise 2.2
Repeating Code With Loops
Hands-On Exercise 2.3 Exceptions
Hands-On Exercise 2.4
41© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Hands-On Exercise 2.3
In your Exercise Manual, please refer to Hands-On Exercise 2.3: Programming Loops
42© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Chapter Contents
Data Types and Type Conversions
Hands-On Exercise 2.1
Decision-Making Statements
Hands-On Exercise 2.2
Repeating Code With Loops
Hands-On Exercise 2.3
Exceptions Hands-On Exercise 2.4
43© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
An exception is a message sent from a method in response to some invalid circumstance• Exceptions must be caught or the program will crash• Classes often throw exceptions if they are used incorrectly
Use the Throw keyword to activate the exception • Specify a message that explains why the exception was thrown• Often done in response to bad user input
Visual Basic code:
Exceptions
Public Property Operation() As String' Get clause omittedSet(value As String)Dim input As String = value.ToUpper().Substring(0, 1)If input = "A" Or input = "S" Or input = "M" Or input = "D" Then
_operation = inputElse
Throw New Exception _ ("Must enter Add, Subtract, Multiply or Divide")
End IfEnd Set
End Property
If the user enters invalid data, throw the exception
def·i·ni·tion
44© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
C# code:
Exceptions
public string Operation{
get{
return _operation;}set{
string input = value.ToUpper().Substring(0, 1);
if (input == "A" || input == "S" ||input == "M" || input == "D")_operation = input;
elsethrow new Exception("Must enter Add, Subtract, Multiply or Divide");
}}
If the user enters invalid data, throw the exception
45© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Exceptions are handled with a Try-Catch error handler• Try to do something• If an exception is raised, Catch it
Can optionally have a Finally statement• Finally is for code that runs whether or not an exception is raised
Visual Basic code:
Try-Catch Exception Handling
Dim inputValid As Boolean = FalseDo
Console.WriteLine _("Do you want to (A)dd, (S)ubtract, (M)ultiply or (D)ivide?")
Trygame.Operation = Console.ReadLine()inputValid = True
Catch ex As ExceptionConsole.WriteLine(ex.Message)
End TryLoop While inputValid = False
46© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
C# code:
Try-Catch Exception Handling
bool inputValid = false;do{
Console.WriteLine("Do you want to (A)dd, (S)ubtract, (M)ultiply or (D)ivide?");
try{
game.Operation = Console.ReadLine();inputValid = true;
}catch (Exception ex){
Console.WriteLine(ex.Message);}
} while (inputValid == false);
47© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Chapter Contents
Data Types and Type Conversions
Hands-On Exercise 2.1
Decision-Making Statements
Hands-On Exercise 2.2
Repeating Code With Loops
Hands-On Exercise 2.3
Exceptions
Hands-On Exercise 2.4
48© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
Hands-On Exercise 2.4
In your Exercise Manual, please refer to Hands-On Exercise 2.4: Structured Exception Handling
49© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
You are now able to • Program in C# and Visual Basic
You have Investigated data types and type conversions Used If and Case statements to allow programs to make decisions Programmed loops Handled errors
Chapter Summary
50© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
What are the two types of numbers?
How would one decide whether to declare a variable as Integer or Long?
What does it mean to say that .NET is a type-safe environment?
How could a String be converted to an Integer?
What is implicit type conversion?
Chapter 2 Review Questions
51© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
What constructs can be used for a decision-making statement?
What are the two types of loops?
When should a Try-Catch error handler be used?
Rewrite the following using a Select-Case or switch statement:
Chapter 2 Review Questions
Dim pet As StringIf pet = "Dog" then
Feed("Bone")ElseIf pet = "Cat" then
Feed("Catsup")ElseIf pet = "Frog" then
Feed("ToCat")Else
Feed("Steak")End If
52© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-
The C# language, see• Course 419, C# Programming
The Visual Basic language, see• Course 503, Visual Basic® Programming for .NET
Automated testing, see• Course 511, .NET Best Practices and Design Patterns
To Learn More About…
®
419503511
Programming Windows User Interfaces
Chapter 3
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
We delivered our Flash Cards program and it was exactly what they wanted.But now they want a slick graphical user interface. Oh well, such is the life of a programmer. The question is: With such a major change, are we going tohave to rewrite the whole program?
Open your Flash Cards program and answer the following questions:
Does the FlashCardsGame class have any user-interface code? • In other words, does it ever do a Console.WriteLine() or
Console.ReadLine()?
Where is all the user-interface code located?
So, do we have to rewrite the whole program? If not, what do we have to replace?
Those Ever-Changing Requirements
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
After completing this chapter, you will be able to • Program a Windows application with .NET
To accomplish this, you will Create a Windows-based user interface for Flash Cards Investigate event-driven programming Handle events from Windows forms and controls Declare and raise events from custom classes Retrieve user input with dialog forms
Chapter Objectives
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Chapter Contents
Windows Forms Applications Overview
Hands-On Exercise 3.1
Event-Driven Programming
Hands-On Exercise 3.2
Raising Events
Hands-On Exercise 3.3
Dialogs
Hands-On Exercise 3.4
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Consist of a series of forms, or screens• One form is the startup or controlling form• Forms can open or activate other forms• Forms have controls • Forms can have menus
Forms allow the user to retrieve and manipulate data• Each form displays data inside its controls• Menus and controls are used to save and retrieve data, create new records,
etc.
Windows Applications
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Add forms to projects using Solution Explorer• Right-click the project and select Add | Windows Form• Give the form a name
Form names should be descriptive and follow a convention• FlashCardsForm
• Microsoft standard in .NET
Adding Forms to a .NET Project
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Property DescriptionName The variable name used to refer to the formFormBorderStyle Determines border style and whether or not the form is sizableMaximizeBox Determines whether a maximize button is in the caption barMinimizeBox Determines whether a minimize button is in the caption barStartPosition Determines where the form should appear when loadedSize The size of the form in pixels (Height and Width)
Text Determines the caption of the form
WindowState Determines whether the form is maximized, minimized, or normal in size
AcceptButton The button whose Click event runs when the user presses <Enter>
Form Properties Some common properties of Windows forms
• Can be set from the Properties window • Can be set in code
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Allows design of Windows forms with a WYSIWYG display• Controls are dragged from the Toolbox and positioned on the screen• Automatically generates the code in the background• Components with no
visual representation are displayed in the tray at the bottom of the form
Windows Forms Designer
WYSIWYG = what you see is what you get
9© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Toolbox
Allows drag-and-drop access to common controls and components• Organized as a series of tabs• Tabs can be expanded and collapsed • Tabs change depending on the type of application
10© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Allows for setting control properties at design time• Generates code inside the code window as properties are set• List of properties is dynamic depending on the control selected
Allows properties to be set only to appropriate data types• Includes various drop-downs and
dialogs that make setting property values easier
• Double-click to walk around preset choices
Properties Window
11© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Controls are dragged from the Toolbox and dropped on the form• Positioned and sized on the screen with the mouse
Controls should be given descriptive names• PlayButton, AddRadioButton, AnswerTextBox, etc.
All controls work in a similar way with many properties in common• Each control also has properties specific to itself
Adding Controls to a Form
12© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Common properties of controls• Can be set from the Properties window• Can be set in code• Most properties can be changed at design time or runtime
Control Properties
Property DescriptionName The name used in code to identify the objectText The text contained in the controlLocation The position of the top left corner of the control with respect to its form
Size The size of the control in pixels (could also use Height and Widthproperties)
Font The font used to display text in the controlTabIndex Determines the Tab order of the control
13© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Drag the MenuStrip control from the Toolbox onto the form• Icon is displayed in the tray at the bottom of the form• Form’s MainMenuStrip property is set to the MenuStrip control’s name
To create menu items• Click the MenuStrip control• Type the menu text• Use the arrow keys to move
up, down, left, and right
Menu items are named based on their text• File menu is automatically
named FileToolStripMenuItem
Adding a Menu to a Form
14© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
To create access keys, prefix any letter with the ampersand character (&) • User can select that item by typing the underlined letter• For top-level items, press the <Alt> key and type that letter
Can also set ShortcutKeys property• Pick a shortcut key and set the ShowShortcutKeys property to True
Properties of menu items:
Menu Items
Property DescriptionName The name used in code to identify the menu itemText The text of the menu item. Prefix any letter with the &
character to underline that character and create an access keyChecked Set to True or False to put a checkmark next to that itemShortcutKeys The shortcut keys on the keyboard that selects the menu itemShowShortcutKeys Determines whether the shortcut key is displayed when the
menu is expanded
15© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Use project properties to change the application type to Windows Forms• Still requires an entry point that starts the controlling form
Call System.Windows.Forms.Application.Run() to start the program• Pass a new instance of the controlling form as an argument to Run() method• Closing that form will stop the program
Starting a Windows Application
System.Windows.Forms.Application.Run(new FlashCardsForm());
16© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
A form is a class that knows how to display itself on the screen• Properties determine how the form looks• Methods allow it to be displayed on or removed from the screen• Events are raised as the user interacts with the form
To open a form• Declare a variable of the form’s type
– Use the New keyword to create an instance of the form• Call the form object’s Show() method to display it on the screen
Visual Basic and C# code:
Opening Forms
Dim frm As New FlashCardsFormfrm.Show()
FlashCardsForm frm = new FlashCardsForm();frm.Show();
17© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Chapter Contents
Windows Forms Applications Overview
Hands-On Exercise 3.1 Event-Driven Programming
Hands-On Exercise 3.2
Raising Events
Hands-On Exercise 3.3
Dialogs
Hands-On Exercise 3.4
18© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Hands-On Exercise 3.1
In your Exercise Manual, please refer to Hands-On Exercise 3.1: Designing Windows Forms
19© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Chapter Contents
Windows Forms Applications Overview
Hands-On Exercise 3.1
Event-Driven Programming Hands-On Exercise 3.2
Raising Events
Hands-On Exercise 3.3
Dialogs
Hands-On Exercise 3.4
20© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
An event is a message sent from controls or other objects• Some action causes an event to be raised• Programmer can choose to respond to the event or not
Windows applications run in a loop waiting for something to do• Events are raised• If an event handler exists, the code inside that function runs
Examples of events:• User clicks a button and that button’s Click event is raised• User clicks a menu item and that menu item’s Click event is raised• A form is shown on the screen and its Load event is raised
Many more events are raised than one would write event handlers for
Events def·i·ni·tion
21© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Form Events
Forms raise many events• When they are displayed• When they are closed• When they receive or lose the focus
Common form events:
Event DescriptionLoad Occurs before the form is displayed for the first time; used to initialize
the controls and variables of a formFormClosing Occurs when a request to close the form is received but before the
form is actually closed; gives user an opportunity to cancel the requestFormClosed Occurs when the form is closedActivated Occurs when the form receives the focus
22© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Control Events
Depending on the type of control, many different events are commonly used
Common control events:
Event DescriptionClick Occurs when the mouse is clicked on the controlDoubleClick Occurs when the mouse is double-clicked on the controlTextChanged Occurs when the text in a textbox changesValidating Occurs when a textbox or other control loses focus, but
only if the control’s text or value has changedSelectedIndexChanged Occurs when the selected item in a list box or combo box
changesCheckedChanged Occurs when a checkbox is checked or unchecked
23© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
An event handler is a function that runs in response to an event being raised
Controls have many events, but one is always assigned as the default• Not surprisingly, the default is usually the one that is used• Creating event handlers is usually automated by the designer
To create an event handler for a control or form, double-click it• The code window opens, and an event handler is created• The event handler handles the default event
Visual Basic code:
Event Handlers
This function handles the Click event of the Play button
def·i·ni·tion
24© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
C# code:
Event Handlers
this.PlayButton.Click += new System.EventHandler(this.PlayButton_Click);
In C#, this line of code is generated to specify the function to run when the event is raised
25© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
To create an event handler for an event that is not the default• Click the lighting bolt in the
Properties window• Double-click the event
Creating Non-Default Event Handlers
Click here to see all the events for a control
Double-click an event to generate the event handler
26© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Chapter Contents
Windows Forms Applications Overview
Hands-On Exercise 3.1
Event-Driven Programming
Hands-On Exercise 3.2 Raising Events
Hands-On Exercise 3.3
Dialogs
Hands-On Exercise 3.4
27© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Hands-On Exercise 3.2
In your Exercise Manual, please refer to Hands-On Exercise 3.2: Programming Windows Events
28© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Chapter Contents
Windows Forms Applications Overview
Hands-On Exercise 3.1
Event-Driven Programming
Hands-On Exercise 3.2
Raising Events Hands-On Exercise 3.3
Dialogs
Hands-On Exercise 3.4
29© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Someone had a good idea that students should be able to accumulate points as they answer questions correctly. For each correct answer, 10 points will be added to the student’s score. This should be displayed on the screen.
Let the FlashCardGame class maintain the current score• Program this class to raise an event when the score changes• The event would be received by the user interface• The user interface would have an event handler that updates the score
Those Ever-Changing Requirements
30© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
1. Declare the event• Event names should be appropriate to the action that has occurred • Click, Load, TextChanged, ScoreChanged, etc.
2. Raise the event at the appropriate time• The ScoreChanged event will be raised in the Score property’s setter
Steps to Programming Events
31© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Declaring the event exposes it outside the class• Events are declared at the class level• Use the Event keyword• The data type of the event defines the arguments required by event handlers
EventHandler data type is the default data type for events• Requires two arguments, sender and an event argument e
Visual Basic code:
C# code:
Declaring an Event
Public Event ScoreChanged As EventHandler
public event EventHandler ScoreChanged;
32© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Use the RaiseEvent keyword• Specify the event name
Supply the arguments• Sender and event argument• The sender is always the current instance of the class (Me)• By default, the event argument is empty
Visual Basic code:
Raising an Event in Visual Basic
Public Property Score() As IntegerGet
Return mScoreEnd GetSet(value As Integer)
mScore = value
RaiseEvent ScoreChanged(Me, EventArgs.Empty)End Set
End Property
33© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Call the event as if it were a function of that name• if statement required to ensure at least one event handler has been created
Supply the arguments• Sender and event argument• The sender is always the current instance of the class (this)• By default, the event argument is empty
C# code:
Raising an Event in C#
public int Score{
get{ return mScore; }set{
mScore = value;
if (ScoreChanged != null){
ScoreChanged(this, EventArgs.Empty);}
}}
34© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Chapter Contents
Windows Forms Applications Overview
Hands-On Exercise 3.1
Event-Driven Programming
Hands-On Exercise 3.2
Raising Events
Hands-On Exercise 3.3 Dialogs
Hands-On Exercise 3.4
35© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Hands-On Exercise 3.3
In your Exercise Manual, please refer to Hands-On Exercise 3.3: Declaring and Raising Events
36© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Chapter Contents
Windows Forms Applications Overview
Hands-On Exercise 3.1
Event-Driven Programming
Hands-On Exercise 3.2
Raising Events
Hands-On Exercise 3.3
Dialogs Hands-On Exercise 3.4
37© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
A dialog form is a form that is used to query the user for information
Typical dialog form properties:
Dialog Forms
Property Value Description
FormBorderStyle FixedDialog Determines the border of the form; FixedDialog style cannot be resized
AcceptButton OK or Open button The button that is “clicked” when the user presses the <Enter> key
CancelButton Cancel or Close button The button that is “clicked” when the user presses the <Esc> key
ControlBox False Determines whether the form has a control box; usually turned off for a dialog
MinimizeBox False Determines whether the form has a minimize button
MaximizeBox False Determines whether the form has a maximize button
StartPositionCenterScreen or CenterParent
Determines where the form is displayed on the screen
def·i·ni·tion
38© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Displays a form on the screen modally• This means code execution will stop until the form is closed• After the form is closed, retrieve the values from its controls
Visual Basic and C# code:
ShowDialog() Method
UserDialogForm userDialog = new UserDialogForm();userDialog.ShowDialog();game.User = userDialog.UserTextBox.Text;this.WelcomeLabel.Text = "Hello " + game.User;
Dim userDialog As New UserDialogFormuserDialog.ShowDialog()game.User = userDialog.UserTextBox.TextMe.WelcomeLabel.Text = "Hello " + game.User
39© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
A value can be assigned to a button’s DialogResult property• If set to anything but None, clicking the button will close a form that is
displayed with the ShowDialog() method• The form’s ShowDialog() method returns the value of the DialogResult
property
DialogResult property values come from the DialogResultenumeration• Values are Abort, Cancel, Ignore, No, None, OK, Retry, Yes
DialogResult Property
I’ll meet you at the airport baggage claim!
OK, bye.
40© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Can use the FormClosing event of the form to ask the user if they are sure
Use the MessageBox.Show() method to query the user• Specify which buttons should be included with the message box• The button clicked returns from the Show() method
Use an If statement to cancel the action if the user is not sure• Cancel property is included in the CancelEventArgs argument of the FormClosing event
Collecting User Input with MessageBox
41© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Visual Basic and C# code:
Collecting User Input with MessageBox Examples
42© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Chapter Contents
Windows Forms Applications Overview
Hands-On Exercise 3.1
Event-Driven Programming
Hands-On Exercise 3.2
Raising Events
Hands-On Exercise 3.3
Dialogs
Hands-On Exercise 3.4
43© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Hands-On Exercise 3.4
In your Exercise Manual, please refer to Hands-On Exercise 3.4: Using a Dialog Form to Retrieve User Input
44© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
You are now able to • Program a Windows application with .NET
You have Created a Windows-based user interface for Flash Cards Investigated event-driven programming Handled events from Windows forms and controls Declared and raised events from custom classes Retrieved user input with dialog forms
Chapter Summary
45© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
What does a Windows application consist of?
What method is used to display a form on the screen?
What are some of the standard Windows controls?
What is the difference between an event and an event handler?
What does it mean to display a form modally? How is this done?
Chapter 3 Review Questions
46© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-
Windows Presentation Foundation, see• Course 975, WPF and Silverlight® Introduction
To Learn More About…
®
975
Object-Oriented Programming
Chapter 4
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
After completing this chapter, you will be able to • Create a .NET class library to allow for code reuse
To accomplish this, you will Separate responsibilities into multiple classes for easier maintenance Use inheritance to simplify application logic Create a Class Library project in Visual Studio
Chapter Objectives
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
After delivering the Windows version of Flash Cards, we received some feedback from the customer
They decided multiplication is too hard; for multiplication, the random numbers should be between 0 and 12
For division, they want us to rig the numbers so that the students always get a question that will result in a whole number between 1 and 9
Customer Feedback
∑Xii=1X =
n
ŋ
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
Chapter Contents
The Single Responsibility Principle Hands-On Exercise 4.1
Inheritance
Hands-On Exercise 4.2
Class Libraries
Hands-On Exercise 4.3
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
The Single Responsibility Principle states that a class should do one job• A class should have only one reason to change
Examples:• A class that displays data to a user should not also talk to a database• A class that saves and retrieves data from a database should not know anything
about how that data is represented to the user• Complex business processing, data validation, or transactions should be
encapsulated within some controlling class
• How might following this principle make programs easier to maintain?
Single Responsibility Principle def·i·ni·tion
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
In the current version of FlashCards, there are two classes:• FlashCardsForm defines the user interface• FlashCardsGame maintains the game
Current FlashCards Classes
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
In the case study, another class called NumberGenerator will be added• Responsible only for generating the random numbers for the FlashCardsGame class
• An instance of FlashCardsGame is passed to it • It sets that instance’s Number1 and Number2 properties
VB code:
Coding the NumberGenerator Class
Public Class NumberGenerator
Public Sub GenerateNumbers(flashcard As FlashCardsGame)Dim randomNumber As _New Random(DateTime.Now.Millisecond)
flashcard.Number1 = randomNumber.Next(0, 99)flashcard.Number2 = randomNumber.Next(0, 99)
End Sub
End Class
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
C# code:
Coding the NumberGenerator Class
public class NumberGenerator{
public void GenerateNumbers(FlashCardsGame flashcard){
Random randomNumber =new Random(DateTime.Now.Millisecond);
flashcard.Number1 = randomNumber.Next(0, 99);flashcard.Number2 = randomNumber.Next(0, 99);
}}
9© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
An instance of NumberGenerator is created in FlashCardsGame• FlashCardsGame must pass a reference to itself when using it
VB and C# code:
Using the NumberGenerator Class
Public Class FlashCardsGame
‘ Code omittedPublic Sub GenerateNumbers()
Dim generator As NumberGeneratorgenerator = New NumberGenerator()generator.GenerateNumbers(Me)
End Subpublic class FlashCardsGame{
// Code omittedpublic void GenerateNumbers(){
NumberGenerator generator;generator = new NumberGenerator();generator.GenerateNumbers(this);
}}
10© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
Me in Visual Basic or this in C# refers to the current instance of a class• More explicit when referring to a member of a class from within that class• Can be used to pass a reference of the current class to an external function• Used when raising events (represents the sender)
VB code:
Me (this) Keyword
Public Sub New(operation As String)
Me.Operation = operationEnd Sub
Public Sub GenerateNumbers()Dim generator As NumberGeneratorgenerator = New NumberGenerator()
generator.GenerateNumbers(Me)End Sub
RaiseEvent ScoreChanged(Me, EventArgs.Empty)
11© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
C# code:
Me (this) Keyword
public FlashCardsGame(string operation){
this.Operation = operation;}
public void GenerateNumbers(){
NumberGenerator generator;generator = new NumberGenerator();
generator.GenerateNumbers(this);}
if (ScoreChanged != null){
ScoreChanged(this, EventArgs.Empty);}
12© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
A constructor is a function that runs automatically when a class is instantiated• In VB, the constructor is a subroutine named New• In C#, the constructor is a function with no return type (not even void), with the
same name as the class
When an instance of a class is created, properties may need to be initialized• Especially fields accessed via read-only properties • Initialization is done inside the class’s constructor
Visual Basic code:
Constructors
Public Class FlashCardsGame
Public Sub New(operation As String)Me.Operation = operation
End Sub…
def·i·ni·tion
13© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
C# code:
Constructors
public class FlashCardsGame{
public FlashCardsGame(string operation){
this.Operation = operation;}
…
14© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
Chapter Contents
The Single Responsibility Principle
Hands-On Exercise 4.1 Inheritance
Hands-On Exercise 4.2
Class Libraries
Hands-On Exercise 4.3
15© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
Hands-On Exercise 4.1
In your Exercise Manual, please refer to Hands-On Exercise 4.1: Coding the NumberGenerator Class
16© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
Chapter Contents
The Single Responsibility Principle
Hands-On Exercise 4.1
Inheritance Hands-On Exercise 4.2
Class Libraries
Hands-On Exercise 4.3
17© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
Inheritance allows a class to reuse and extend functionality of another• The base class provides the reusable behavior• The derived class can add new behaviors or change the existing behaviors
Inheritance, when used correctly, can• Reduce code duplication• Reduce complexity• Make testing easier
Visual Basic and C# code:
Inheritance
Public Class MultiplicationNumberGenerator
Inherits NumberGenerator
End Class
def·i·ni·tion
public class MultiplicationNumberGenerator : NumberGenerator{
}
18© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
1. Reduce code duplication• Sometimes a program has multiple classes with similar fields, properties,
and methods• Add a base class and move the common behaviors to that class• Have each class inherit from the base class
2. Reduce complexity• Sometimes a class has a variable that affects its behavior• If statements within the class check the variable and do things differently
based on its value– This makes using, understanding, and testing the class more difficult
• Add a derived class for each type and move the conditional logic
Two Reasons to Use Inheritance
19© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
NumberGenerator class calculates numbers for Addition and Subtraction
Derived classes override the GenerateNumbers() method for multiplication and division
Inheritance Hierarchy
20© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
A virtual method is one that is programmed in the base class but can be changed in the derived class if necessary• The base class has default functionality
Visual Basic code:• Use the Overridable keyword in the base class• Use the Overrides keyword in the derived class
Virtual Methods
Public Class NumberGenerator
Public Overridable Sub GenerateNumbers(flashcard As FlashCardsGame)Dim randomNumber As _
New Random(DateTime.Now.Millisecond)
flashcard.Number1 = randomNumber.Next(0, 99)flashcard.Number2 = randomNumber.Next(0, 99)
End SubEnd Class
Public Class MultiplicationNumberGeneratorInherits NumberGenerator
Public Overrides Sub GenerateNumbers(flashcard As FlashCardsGame)Dim randomNumber As _New Random(DateTime.Now.Millisecond)
flashcard.Number1 = randomNumber.Next(1, 12)flashcard.Number2 = randomNumber.Next(1, 12)
End SubEnd Class
def·i·ni·tion
21© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
C# code:• Use the virtual keyword in the base class• Use the override keyword in the derived class
Virtual Methods
public class NumberGenerator{
public virtual void GenerateNumbers(FlashCardsGame flashcard){
Random randomNumber =new Random(DateTime.Now.Millisecond);
flashcard.Number1 = randomNumber.Next(0, 99);flashcard.Number2 = randomNumber.Next(0, 99);
}
public class DivisionNumberGenerator : NumberGenerator{
public override void GenerateNumbers(FlashCardsGame flashcard){
Random randomNumber =new Random(DateTime.Now.Millisecond);
int temp;temp = randomNumber.Next(1, 9);flashcard.Number2 = randomNumber.Next(1, 12);flashcard.Number1 = temp * flashcard.Number2;
}}
def·i·ni·tion
22© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
The program must decide which number generator to use• The variable uses the base class type in its declaration• Any type of NumberGenerator can be assigned to that variable
VB and C# code:
Constructing the Correct Class
Public Sub GenerateNumbers()
Dim generator As NumberGenerator
Select Case Me.OperationCase "M"
generator = New MultiplicationNumberGenerator()Case "D"
generator = New DivisionNumberGenerator()Case Else
generator = New NumberGenerator()End Select
generator.GenerateNumbers(Me)End Sub
23© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
C# code:
Constructing the Correct Class
public void GenerateNumbers(){
NumberGenerator generator;
switch (this.Operation){
case "M":generator = new MultiplicationNumberGenerator();break;
case "D":generator = new DivisionNumberGenerator();break;
default:generator = new NumberGenerator();break;
}generator.GenerateNumbers(this);
}
24© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
Chapter Contents
The Single Responsibility Principle
Hands-On Exercise 4.1
Inheritance
Hands-On Exercise 4.2 Class Libraries
Hands-On Exercise 4.3
25© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
Hands-On Exercise 4.2
In your Exercise Manual, please refer to Hands-On Exercise 4.2: Inheriting From the NumberGenerator Class
26© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
Chapter Contents
The Single Responsibility Principle
Hands-On Exercise 4.1
Inheritance
Hands-On Exercise 4.2
Class Libraries Hands-On Exercise 4.3
27© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
A class library is an application that contains reusable classes but cannot be executed on its own• Compiled with the .dll file extension• There is no entry point• Can be accessed only from some other running program
Reasons to use class libraries:1. Allow the classes to be reused in multiple applications2. Allow for better organization of classes, especially on large projects3. Can be easier for multiple developers or multiple teams to divide work
Class Libraries
28© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
Steps:1. Right-click your solution in Solution Explorer2. Select Add | New Project3. Choose your preferred language4. Select Class Library from the list of templates
Creating a Class Library Project
29© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
To use the classes in a library from another project, set a reference to it• This copies the .dll file into that project’s bin folder
Steps:1. Right-click the project in Solution Explorer and select Add Reference2. In the Add Reference dialog, choose the Projects tab3. Choose the library from the list
Setting References
30© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
Adding Imports (VB) or using (C#) to the top of a code file allows a class to be used without specifying its namespace• Refer to the class as though it was a part of the current project
Visual Basic code:
C# code:
Imports (using)
Imports FlashCardsLibrary
Public Class FlashCardsFormPrivate WithEvents game As New FlashCardsGame' code omitted
End Class
using FlashCardsLibrary;namespace FlashCards{
public partial class FlashCardsForm : Form{
private FlashCardsGame game = new FlashCardsGame();// code omitted
}}
31© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
Chapter Contents
The Single Responsibility Principle
Hands-On Exercise 4.1
Inheritance
Hands-On Exercise 4.2
Class Libraries
Hands-On Exercise 4.3
32© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
Hands-On Exercise 4.3
In your Exercise Manual, please refer to Hands-On Exercise 4.3: Creating the FlashCards Library
33© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
You are now able to • Create a .NET class library to allow for code reuse
You have Separated responsibilities into multiple classes for easier maintenance Used inheritance to simplify application logic Created a Class Library project in Visual Studio
Chapter Summary
34© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
Define the Single Responsibility Principle:
Define a constructor:
Give two reasons to use inheritance:
List some advantages of class libraries:
Chapter 4 Review Questions
35© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-
The programming process, analysis, and class design, see• Course 933, Agile Software Development and Modeling
To Learn More About…
®
933
Designing Web User Interfaces With ASP.NET
Chapter 5
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
We delivered our Windows version of the Flash Cards application, and it was exactly what they wanted. But now they want a web version that runs in a browser.
With such a major change, are we going to have to rewrite the whole program?
What can be reused?
Those Ever-Changing Requirements
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
After completing this chapter, you will be able to • Create a web application using ASP.NET
To accomplish this, you will Create an ASP.NET Web Application project in Visual Studio Construct Web Forms user interfaces Process user requests over the web Allow users to create accounts and log in using Web Forms Authentication Style ASP.NET websites using Cascading Style Sheets
Chapter Objectives
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Chapter Contents
Creating Web Applications Hands-On Exercise 5.1
Processing ASP.NET Web Forms
Hands-On Exercise 5.2
Web Forms Security
Hands-On Exercise 5.3
Styling ASP.NET Applications
Hands-On Exercise 5.4
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Use standard Internet protocols• TCP/IP to connect to the Internet• HTTP for web requests and responses
Require a web server• Web servers handle all HTTP requests• Applications are configured under IIS
Web server waits for user requests• Returns web pages to the browser
Web Applications
HTTP = Hypertext Transfer ProtocolIIS = Internet Information ServicesTCP/IP = Transmission Control Protocol/Internet Protocol
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Web applications return data in three languages to the browser:1. HTML (HyperText Markup Language)2. CSS (Cascading Style Sheets)3. JavaScript
HTML is used to describe the page content• Headings are used to emphasize content• <div> and <p> tags are used to organize content• <form> and <input> elements are used to collect information• <a> elements are used to create hyperlinks to other pages
CSS is used to style page content• Fonts, colors, size, and positioning should all be done using CSS
JavaScript is used to add dynamic behaviors to web pages• JavaScript is downloaded to the browser as raw text• The browser compiles and executes the JavaScript code
Web Application Languages
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
HTML is a text-based markup language used to format data in a browser
Page is divided into two sections• Head is used for title and certain non-visible elements• Body contains the formatted data displayed to the user
Elements determine how text should be formatted• Each element has an opening and closing tag
HTML
Opening tag
def·i·ni·tion
<a href="Default.aspx">Home</a>
Tag valueValue of tag attribute
Closing tagTag attribute
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Contain controls that allow users to send data back to the server• Controls include text boxes, list boxes, drop-downs, checkboxes, radio
buttons, submit buttons, and reset buttons
Have two main attributes:• action attribute determines where the form is submitted• method attribute determines how the control values are submitted
Input element is used to create controls inside the form
HTML Forms
<form method="post" action="Login.aspx">User name:<input type="text" /><br />Password:<input type="password" /><br /><br /><input type="submit" value="Login" />
</form>
9© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Some Common HTML Tags
Tag Description<html></html> Surround the entire HTML page<head></head> At the top of the page; includes the title, which is displayed in the
title bar of the browser<body></body> Below the head; includes the text displayed to the user<h1></h1> Heading 1; used for large, bold text suitable for a heading; also,
h2, h3, h4, h5, and h6
<p></p> Paragraph tag; used to separate text. Inserts a blank line<br /> Break; used to move to a new line, but does not insert a blank
line<form></form> Contains HTML text boxes, drop-downs, checkboxes, radio
buttons, and list boxes for building an input/output form<input /> Used to create input fields on forms. Type attribute is set to
text, password, radio, checkbox, submit, reset, etc.<a></a> Anchor tag used to create hyperlinks; href attribute determines
the URL to the link; value determines the text that is underlined
URL = uniform resource locator
10© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Sample HTML Page<html xmlns="http://www.w3.org/1999/xhtml"><head>
<title>Login</title></head><body>
<h1>Ralph's Pretty Good Web site!</h1><a href="Default.aspx">Home</a><br /><br /><form method="post" action="Login.aspx">User name:<input type="text" /><br />Password:<input type="password" /><br /><br /><input type="submit" value="Login" /></form>
</body></html>
11© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Simplify web application development• HTML is automatically generated• Form input is automatically retrieved
Web Forms controls are used to design pages• Just drag and drop on the form• Processing is done much like Windows applications
Require the .NET Framework on the server
IIS software must also be installed on the web server• Routes requests for pages with the .aspx extension to .NET for processing
ASP.NET Applications
12© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Steps:1. Right-click solution in Solution Explorer and select Add | New Project2. Choose the preferred language and the web branch of the tree view3. Choose ASP.NET Web Application from the list of templates4. Specify an appropriate name and folder location for the web project files
Creating ASP.NET Projects With Visual Studio
13© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
There are multiple frameworks that can be used within ASP.NET• ASP.NET Web Forms • ASP.NET MVC• Web API
These frameworks can be used independently or together
This class will useASP.NET Web Forms
ASP.NET Templates
14© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Includes predefined default pages and resources• Default master page• Home page• About and contact pages• Pages for registering and logging in• Default theme and style sheet• Commonly used JavaScript files• Etc.
ASP.NET Web Forms Application Template
15© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Managing Web Projects With Solution Explorer
ASP.NET projects work a little differently than Windows programs• Code is executed on the server• The ASP.NET code generates HTML, CSS,
and JavaScript• Sends the results back to the browser
Web projects can contain• Web pages with the .aspx file extension
– Each page has a code-behind file in VB or C#
• Databases, placed in the App_Data folder• Other resources, such as graphics, style
sheets, and JavaScript files
16© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Are like a template for all other pages in a website• If a web form uses a master page, all the master page content is included• If master page content changes, it is automatically reflected in the web form• Headers, footers, menus, and links are examples of things to put on the
master page
Page-specific content will be placed in a ContentPlaceHolder element• Content placeholders can be in the HTML <head> and <body>• Any number of content placeholders can be added to the master page
Master Pages
17© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Sample Master Page
18© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Are used to generate web pages in ASP.NET• Require .aspx file extension• Contain one <form></form> element• Form is always submitted to itself• All controls on the web page are contained within the form
To create a web form• Right-click the web project
in Solution Explorer• Select from the menu
Add | New Item• Select the “Web Form with
Master Page” template• Give the web form an
appropriate name• Will be prompted to select
the Master Page
Web Forms
19© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Dragged and dropped from the Toolbox onto the web form page• Names and properties are
very similar to Windows controls
• Programmed like Windows controls
Automatically generate HTML that is sent to the browser
Web Form Controls
Click Source to view the ASP.NET markup. Click Split to show both the markup and Design views.
20© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
FlashCards will include the following:
Site.master
• The master page for all other pages
Default.aspx
• The FlashCards home page
Login.aspx
• Lets the user log in to the application
Register.aspx
• Allows new users to create accounts
FlashCards.aspx
• Allows the user to play the game• Very similar to the Windows version
Web Forms for the FlashCards Website
21© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
FlashCards Web Pages
22© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Chapter Contents
Creating Web Applications
Hands-On Exercise 5.1 Processing ASP.NET Web Forms
Hands-On Exercise 5.2
Web Forms Security
Hands-On Exercise 5.3
Styling ASP.NET Applications
Hands-On Exercise 5.4
23© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Hands-On Exercise 5.1
In your Exercise Manual, please refer to Hands-On Exercise 5.1: Creating an ASP.NET Web Application
24© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Chapter Contents
Creating Web Applications
Hands-On Exercise 5.1
Processing ASP.NET Web Forms Hands-On Exercise 5.2
Web Forms Security
Hands-On Exercise 5.3
Styling ASP.NET Applications
Hands-On Exercise 5.4
25© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
ASP.NET processing is event-driven in the same way as Windows applications• Web forms must be submitted back to the server for the events to fire
Web page has events that are fired on each request
Web form controls have events just like their Windows counterparts• For example, the ASP.NET Button control raises a Click event
Can handle any other events as needed• For example, the FlashCards.aspx page will handle the FlashCardsGame
class ScoreChanged event
Property values of ASP.NET controls can be retrieved and updated in the same ways as with Windows Forms
Web Forms Processing With Events
26© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Page’s Load event is used to process pages• Raised every time the page is requested• Also occurs when the form is submitted• IsPostback property determines if the form is being requested the first time
IsPostback equals false when the page is being requested via a hyperlink• Controls should be initialized only on the first request
IsPostback equals true when the user has submitted the form• Process the form submission
Visual Basic code:
Processing Web Forms
Protected Sub Page_Load(sender As Object…If IsPostBack = False Then
QuestionLabel.Text = ""game.User = "Joe"WelcomeLabel.Text = "Hello " + game.User + "."
ElseFormSubmitted()
End IfEnd Sub
27© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
C# code:
Processing Web Forms
protected void Page_Load(object sender, EventArgs e)
{ if (IsPostBack == false){
QuestionLabel.Text = "";game.User = "Joe";WelcomeLabel.Text = "Hello " + game.User + ".";
}else{
FormSubmitted();}
}
28© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Web pages are completely destroyed after each request is processed• Need a way to store user variables that need to live beyond a single request
Session variables allow information to be stored for each user• Available to every web form in the application• Each user has his or her own copy of each Session variable• Session variables are destroyed on the server after a period of inactivity
– By default 20 minutes
Creating and accessing Session variables is done using name–value pairs• Value of a Session variable can be of any data type
User Variables
VB: Session("VariableName") = SomeValue
C#: Session["VariableName"] = SomeValue;
29© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Visual Basic code for using a Session variable:
C# code for using a Session variable:
Creating and Retrieving Session Variables
If Session("FlashCardsGame") Is Nothing Thengame = New FlashCardsGame()Session("FlashCardsGame") = game
Elsegame = Session("FlashCardsGame")
End If
Create the Sessionvariable
Retrieve the variable
if (Session["FlashCardsGame"]== null){
game = new FlashCardsGame();Session["FlashCardsGame"] = game;
}else{
game = (FlashCardsGame)Session["FlashCardsGame"];}
Create the Sessionvariable
Retrieve the variable
30© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Chapter Contents
Creating Web Applications
Hands-On Exercise 5.1
Processing ASP.NET Web Forms
Hands-On Exercise 5.2 Web Forms Security
Hands-On Exercise 5.3
Styling ASP.NET Applications
Hands-On Exercise 5.4
31© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Hands-On Exercise 5.2
In your Exercise Manual, please refer to Hands-On Exercise 5.2: Programming ASP.NET Web Forms
32© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Chapter Contents
Creating Web Applications
Hands-On Exercise 5.1
Processing ASP.NET Web Forms
Hands-On Exercise 5.2
Web Forms Security Hands-On Exercise 5.3
Styling ASP.NET Applications
Hands-On Exercise 5.4
33© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Is used to control access to a website• Configured in the Web.config file• Access rules are used to set permissions on folders
The ASP.NET template preconfigures Web Forms security
ASP.NET Web Forms Security
34© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Determine who has the rights to view pages in the website folder• Defined within a Web.config file in each folder that requires security• Forces someone to log in before accessing pages within this folder• All pages in a folder should have the same access rules
Can allow or deny users based on username or role
Example access rule:
Access Rules
<?xml version="1.0" encoding="utf-8"?><configuration>
<system.web><authorization>
<deny users="?" /></authorization>
</system.web></configuration>
35© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Once access rules are defined, anonymous users are automatically redirected to Login.aspx• Login control generates
the page
After logging in, users are redirected to the page they originally requested• Notice the variable
embedded in the URL
Login Page
36© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Need to identify who the user is
Can be accessed via the User class• User.Identity.Name returns the user’s name
Visual Basic and C# code:
Identifying Users
Protected Sub Page_Load(sender As Object…
If IsPostBack = False ThenQuestionLabel.Text = ""WelcomeLabel.Text = "Hello " + User.Identity.Name
End IfEnd Sub
protected void Page_Load(object sender, EventArgs e){
if (IsPostBack == false){
QuestionLabel.Text = "";
WelcomeLabel.Text = "Hello " + User.Identity.Name;}
}
37© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Chapter Contents
Creating Web Applications
Hands-On Exercise 5.1
Processing ASP.NET Web Forms
Hands-On Exercise 5.2
Web Forms Security
Hands-On Exercise 5.3 Styling ASP.NET Applications
Hands-On Exercise 5.4
38© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Hands-On Exercise 5.3
In your Exercise Manual, please refer to Hands-On Exercise 5.3: Web Forms Security
39© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Chapter Contents
Creating Web Applications
Hands-On Exercise 5.1
Processing ASP.NET Web Forms
Hands-On Exercise 5.2
Web Forms Security
Hands-On Exercise 5.3
Styling ASP.NET Applications Hands-On Exercise 5.4
40© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
CSS styles control formatting of all HTML pages• Fonts, colors, graphics, positioning, and even behaviors can be controlled
inside style sheets
Styles consist of• Cascading Style Sheets (CSS) • Graphics that are applied by the styles
A default style is added by the template• Can customize the CSS or create a
completely new theme
The styles are loaded by the master page
ASP.NET Styles
41© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Are text files that contain styles that can be applied to any HTML tag• Each CSS file is downloaded to the browser and the styles are applied• CSS is a W3C standard supported by all
browsers
Style rules can be created for any HTML element• Attributes and values are defined in the rule• These are then added to each instance of the
HTML element by the browser
Rules consist of• Selectors that determine which elements the
style will be applied to• Curly braces delimit the styles• Attributes and values separated by colons• Each attribute/value pair ends with a semicolon
Cascading Style Sheets
W3C = World Wide Web Consortium
42© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
CSS Selector Examples
a {color: #333;text-decoration: underline;
}input, textarea{
color: #333;font-size: 1.2em;width: 300px;
}input[type="radio"] {
background: transparent;left: 125px;
}.score {
font-size: xx-large;color: red;
}#question {
font-size: xx-large;vertical-align: top;
}
Selectors determine which elements a style is applied to• Can be all elements of some type• Comma can be used to specify multiple
elements• Square brackets [ ] can be used to select
elements with a particular attribute value• Prefixing a selector with a period selects
elements whose class attribute is set to that value
• Prefixing a selector with a pound sign (#) selects elements whose id attribute is set to that value
43© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
In the CSS file, right-click one of the style elements and select Build Style• This opens the Modify Style dialog
The Modify Style dialog provides a graphical interface for specifying attributes and their values
Creating Styles
Preview the effect of the style
Select the appropriate category
44© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Styling for Mobile Devices
The default CSS file includes style rules for mobile devices• Uses a CSS media query to select
devices with small screens• Allows ASP.NET applications to look
good on mobile phones by default
45© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
The theme is applied to the website inside the master page file• Done in the <head></head> element
Applying the Theme to the Website
<head runat="server"><meta charset="utf-8" /><title>Flash Cards <%: Page.Title %> </title><asp:PlaceHolder runat="server">
<%: Scripts.Render("~/bundles/modernizr") %></asp:PlaceHolder>
<webopt:BundleReference runat="server" Path="~/Content/css" /><link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
</head>
46© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Chapter Contents
Creating Web Applications
Hands-On Exercise 5.1
Processing ASP.NET Web Forms
Hands-On Exercise 5.2
Web Forms Security
Hands-On Exercise 5.3
Styling ASP.NET Applications
Hands-On Exercise 5.4
47© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Hands-On Exercise 5.4
In your Exercise Manual, please refer to Hands-On Exercise 5.4: Styling Sites With CSS
48© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
You are now able to • Create a web application using ASP.NET
You have Created an ASP.NET Web Application project in Visual Studio Constructed Web Forms user interfaces Processed user requests over the web Allowed users to create accounts and log in using Web Forms Authentication Styled ASP.NET websites using Cascading Style Sheets
Chapter Summary
49© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
In web applications, requests are made via which protocol?
What language is used to display data in a browser?
What HTML tag is used to allow a user to send data to a web server?
What would be the syntax for a link to Microsoft’s website?
Chapter 5 Review Questions
50© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
In .NET, what technology is used to create web applications?
What property of the page object determines if the form was submitted?
What ASP.NET object is used to create user variables?
To force all users of a website to create an account, what access rule would be written?
Chapter 5 Review Questions
51© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-
Developing web applications, see• Course 2621, Building ASP.NET Web Applications• Course 977, Building Web Applications with ASP.NET MVC
To Learn More About…
®
2621977
Saving Data With Relational Databases
Chapter 6
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
We delivered our ASP.NET version of the Flash Cards application and it was exactly what they wanted. But then the customers had a meeting to talk about the program.
The teachers want to be able to review what the students are working on and what they are getting right and wrong. They want every flash card to be saved, along with the student’s answer.
They also decided that they wanted students to be able to accumulate points over time. When the students log in, they want the program to show them their lifetime statistics and score, as well as the score of the current game.
• What are we going to need to accomplish these requirements?
Those Ever-Changing Requirements
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
After completing this chapter, you will be able to • Program a database application in .NET
To accomplish this, you will Create a SQL Server database Write SQL queries to create, retrieve, update, and delete database data Execute SQL queries using Entity Framework code Automate the display of data on a web page using ASP.NET data binding
Chapter Objectives
SQL = structured query language
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Chapter Contents
Creating SQL Server DatabasesWith Visual Studio
Hands-On Exercise 6.1
Database CRUD
Creating and Updating Records With Entity Framework
Hands-On Exercise 6.2
Retrieving Records
Hands-On Exercise 6.3
Data Binding With ASP.NET
Hands-On Exercise 6.4
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Databases make data access efficient and secure• Fast searches and sorts• Record locking for multi-user access• Security by user or group
Relational databases contain• Tables• Indexes• Relationships
Relational Database Systems
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
SQL Server databases can be created using Solution Explorer1. Right-click the App_Data folder of the project and select Add | New Item2. Select SQL Server Database from the list of templates3. Name the database appropriately
The database then is displayed in Server Explorer
Creating a SQL Server Database
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Visual Studio Server Explorer
Provides access to resources on a network server or the local machine• Log files• Services• Performance counters• And more
Use Server Explorer to access SQL Server databases• Tree lists all databases set up on the SQL
server• Each database can be expanded to view
tables and fields• Right-click the table and select “Show Table
data” to view the table’s records
Can access any other type of database, as well
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Once created, the new database is included in the tree• Expand the database• Right-click the Tables branch and select Add New Table• This opens the Table Designer
Creating Tables
9© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Fields are defined for each row• Enter field name under Name• Specify the data type from the
drop-down• Add any constraints and properties
for each field
Constraints and properties:• Length specifies maximum field
length• Allow Nulls checkbox determines if
the field can be empty • Default Value is used if a value is
not specified when the record is added
Table Designer
10© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
The SQL Server data types used in FlashCards are as follows• There are many other SQL Server data types
SQL Server Data Types
Data type Descriptionnvarchar Used to hold strings; set the Length to determine the
maximum size of the string in the fielddatetime Used for dates and includes the timeint Used to store whole numbers. Equivalent to a .NET
32-bit Integerfloat Used for real numbers. Closest equivalent to a .NET
Double
11© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
A primary key is a constraint that guarantees each row in a table is unique• Consists of one or more indexed fields• “Allow Nulls” must be false• Can set “Is Identity” field to True to create a counter
Right-click the field and select Set Primary Key• A primary key index is automatically created for that field• Allow Nulls checkbox is cleared• Identified by the key icon next to the field
Creating the Primary Key
12© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Right-click Indexes on the right side of the Table Designer and select Add New | Index• Give the index a descriptive name• Click the ellipsis (…) next to the Columns property in the Properties window• Add the fields to be included in the index and set their sort order
Adding Indexes
13© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Setting Index Properties Illustrated
14© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
The Table Designer is really generating an SQL script• Can be saved or executed against the database within Visual Studio• Can edit the SQL code directly if required
SQL Script
15© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Click the Update button on the Table Designer to execute the script• Will add the new table and indexes to the database
Executing the Script
16© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Chapter Contents
Creating SQL Server Databases With Visual Studio
Hands-On Exercise 6.1 Database CRUD
Creating and Updating Records With Entity Framework
Hands-On Exercise 6.2
Retrieving Records
Hands-On Exercise 6.3
Data Binding With ASP.NET
Hands-On Exercise 6.4
17© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Hands-On Exercise 6.1
In your Exercise Manual, please refer to Hands-On Exercise 6.1: Creating a SQL Server Database
18© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Chapter Contents
Creating SQL Server Databases With Visual Studio
Hands-On Exercise 6.1
Database CRUD Creating and Updating Records
With Entity Framework
Hands-On Exercise 6.2
Retrieving Records
Hands-On Exercise 6.3
Data Binding With ASP.NET
Hands-On Exercise 6.4
19© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
SQL is the standard language used by all databases, for all modifications• Creating, changing, or deleting tables and indexes• Adding users or groups• Inserting, updating, and deleting data• And much more
Application developers need to know how to do four things with SQL:• Create records• Retrieve records• Update records• Delete records
Structured Query Language (SQL) def·i·ni·tion
20© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
SQL Insert query is used to add records to the database
An Insert example for a SQL Server database:
• Scores is the table to add a record to• Followed by the fields in the table to be set• Followed by the values to set the fields to
In this example, values are passed as parameters• {#} used as placeholders for the parameters that will be passed• Parameter values are set in code before running the query
Creating Records
INSERT INTO Scores (UserName, QuestionTime, Equation, CorrectAnswer, StudentAnswer, Points) VALUES ({0}, {1}, {2}, {3}, {4}, {5})
21© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
SQL Select query is used to retrieve records from the database
Use the asterisk (*) to get all the fields from the table
Specify the fields if all of them are not required
Use the Where clause to filter the records• Again, a parameter is used to pass a value to the database
To sort the records, add the Order By clause
Retrieving Records
SELECT CorrectAnswer, StudentAnswer, Points FROM Scores
SELECT * FROM Scores
SELECT CorrectAnswer, StudentAnswer, Points FROM Scores WHERE UserName = {0}
SELECT CorrectAnswer, StudentAnswer, Points FROM Scores WHERE UserName = {0} ORDER BY QuestionTime
22© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
SQL Update query is used to change a record
An update example for a SQL Server database:
• Updates the Scores table• Sets each field equal to the parameter value passed• The Where clause is used to determine which record or records to update
Updating Records
UPDATE Scores SET StudentAnswer = {0}, Points = {1} WHERE ID = {2}
23© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
SQL Delete query is used to remove a record
A delete example for a SQL Server database:
• The Where clause determines the record or records to delete
What would happen without the Where clause?
Deleting Records
DELETE FROM Scores WHERE ID = {0}
24© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Chapter Contents
Creating SQL Server Databases With Visual Studio
Hands-On Exercise 6.1
Database CRUD
Creating and Updating Records With Entity Framework
Hands-On Exercise 6.2
Retrieving Records
Hands-On Exercise 6.3
Data Binding With ASP.NET
Hands-On Exercise 6.4
25© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
NuGet
NuGet is a technology to add functionality to the .NET Framework
Classes added as packages• Developed by Microsoft or others
We will use it to add the Entity Framework• Functionality for database access
26© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Adding Entity Framework
Entity Framework is added to a project as a NuGet package• Multiple files and references are added at the same time
Steps1. Select Tools | Library Package Manager | Manage NuGet Packages for Solution2. Select EntityFramework
and click Install3. Select the projects to use
EF in4. Accept the license
agreement
27© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Use the Entity Framework DbContext class to connect to SQL Server• Add an Imports (using) statement to System.Data.Entity• Create the DbContext class passing a connection string in the constructor• Return the Database property
Visual Basic and C# code:
Accessing a SQL Server Database
Public Shared ReadOnly Property FlashCardsDatabase As DatabaseGet
Dim connection As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=…”
Return New DbContext(connection).DatabaseEnd Get
End Propertypublic static Database FlashCardsDatabase{
get{
string connection = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=…";
return new DbContext(connection).Database;}
}In C#, the @ sign is required here, so the “\” characters in the connection string are treated literally as “\” characters
28© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Server Explorer automatically generates connection strings• Select the database from the Data Connections branch of Server Explorer• Can then copy and paste the connection string from the Properties window
Generating a Connection String
29© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Use the ExecuteSqlCommand()method of the Database class
1. Define the SQL statement as a string• Use {#} placeholders to embed parameters into the query
2. Call the ExecuteSqlCommand() method passing the SQL statement followed by values for the required parameters
Running a Query
Insert, Update, and Delete queries are all run the same way.Only the queries and the parameters are different.
30© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Visual Basic code:
Running a Query
Public Shared Sub SaveFlashCard(flashCard As FlashCardsGame, studentAnswer As Double, points As Integer)
Dim sql As Stringsql = "INSERT INTO Scores (UserName, QuestionTime, Equation,
CorrectAnswer, StudentAnswer, Points) VALUES ({0}, {1}, {2}, {3}, {4}, {5})”
FlashCardsDatabase.ExecuteSqlCommand(sql, flashCard.User, DateTime.Now, flashCard.BuildEquation(), flashCard.CalculateCorrectAnswer(), studentAnswer, points)
End Sub
31© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
C# code:
Running a Query
public static void SaveFlashCard(FlashCardsGame flashCard, doublestudentAnswer, int points)
{string sql;sql = "INSERT INTO Scores (UserName, QuestionTime, Equation,
CorrectAnswer, StudentAnswer, Points) VALUES ({0}, {1}, {2}, {3}, {4}, {5})";
FlashCardsDatabase.ExecuteSqlCommand(sql, flashCard.User, DateTime.Now, flashCard.BuildEquation(), flashCard.CalculateCorrectAnswer(), studentAnswer, points);
}
32© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Methods can be declared as Shared in VB or static in C#• These methods can then be called without creating an instance of the class• Just specify the class name and and the method name
– Console.ReadLine() is an example of a static method
VB code:
C# code:
Shared (static) Methods
FlashCardsDataAccess.SaveFlashCard(game, answer, 10);
FlashCardsDataAccess.SaveFlashCard(game, answer, 10)
33© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Chapter Contents
Creating SQL Server Databases With Visual Studio
Hands-On Exercise 6.1
Database CRUD
Creating and Updating Records With Entity Framework
Hands-On Exercise 6.2 Retrieving Records
Hands-On Exercise 6.3
Data Binding With ASP.NET
Hands-On Exercise 6.4
34© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Hands-On Exercise 6.2
In your Exercise Manual, please refer to Hands-On Exercise 6.2: Saving Data in the Database
35© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Chapter Contents
Creating SQL Server Databases With Visual Studio
Hands-On Exercise 6.1
Database CRUD
Creating and Updating Records With Entity Framework
Hands-On Exercise 6.2
Retrieving Records Hands-On Exercise 6.3
Data Binding With ASP.NET
Hands-On Exercise 6.4
36© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Use the SqlQuery() method of the Database class• Pass a SQL Select statement and required parameters as arguments• Returns a collection that contains the query results
Needs a class that will contain the results of the query• Properties required for each field being returned by the Select statement• Entity Framework will automatically create an instance for each record returned• Class properties will automatically be set
Use a For-Each loop to loop through the returned collection
Executing a Select Query
37© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Visual Basic code:
Executing a Select Query
Public Shared Function GetLifeTimeStatistics(username As String) As String
Dim sql As StringDim questions, correct, points As Integer
sql = "SELECT CorrectAnswer, StudentAnswer, Points FROM Scores WHERE UserName = {0}"
Dim scores = FlashCardsDatabase.SqlQuery(Of Score)(sql, username)
For Each score In scoresquestions += 1If score.CorrectAnswer = score.StudentAnswer Then
correct += 1End Ifpoints += score.Points
Next
Return String.Format _("All time, you have {0} correct out of {1} questions for {2} points." _, correct, questions, points)
End Function
38© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
C# code:
Executing a Select Query
public static string GetLifeTimeStatistics(string username){
string sql;int questions = 0;int correct = 0;int points = 0;
sql = "Select CorrectAnswer, StudentAnswer, Points FROM Scores WHERE UserName = {0}";
var scores = FlashCardsDatabase.SqlQuery<Score>(sql, username);
foreach (var score in scores){
questions += 1;if (score.CorrectAnswer == score.StudentAnswer)
correct += 1;points += score.Points;
}return String.Format(
"All time, you have {0} correct out of {1} questions for {2} points.”, correct, questions, points);
}
39© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
A class is required to hold the results of a select query• Must contain a property for each field being returned
VB code:
C# code:
Class to Hold the Query Result
Public Class ScorePublic Property CorrectAnswer As DoublePublic Property StudentAnswer As DoublePublic Property Points As Integer
End Class
public class Score{
public double CorrectAnswer { get; set; }public double StudentAnswer { get; set; }public int Points { get; set; }
}
40© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Easy way to loop through each item in a collection of item• Create a variable to represent each item• Specify the collection to loop through
VB and C# code:
For-Each Loop
For Each score In scoresquestions += 1If score.CorrectAnswer = score.StudentAnswer Then
correct += 1End Ifpoints += score.Points
Next
foreach (var score in scores){
questions += 1;if (score.CorrectAnswer == score.StudentAnswer)
correct += 1;points += score.Points;
}
41© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Chapter Contents
Creating SQL Server Databases With Visual Studio
Hands-On Exercise 6.1
Database CRUD
Creating and Updating Records With Entity Framework
Hands-On Exercise 6.2
Retrieving Records
Hands-On Exercise 6.3 Data Binding With ASP.NET
Hands-On Exercise 6.4
42© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Hands-On Exercise 6.3
In your Exercise Manual, please refer to Hands-On Exercise 6.3: Retrieving Database Data
43© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Chapter Contents
Creating SQL Server Databases With Visual Studio
Hands-On Exercise 6.1
Database CRUD
Creating and Updating Records With Entity Framework
Hands-On Exercise 6.2
Retrieving Records
Hands-On Exercise 6.3
Data Binding With ASP.NET Hands-On Exercise 6.4
44© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
We delivered our Flash Cards application with the database and the lifetime scores, and it was exactly what they wanted
Now they want a student history page that shows all the flash cards they’ve ever answered
Those Ever-Changing Requirements
45© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Data-Bound Controls
ASP.NET includes a number of controls that automate the display of database data
GridView is used to display data in an HTML table• Allows sorting, selecting, and editing of the data
FormView and DetailsView controls are used to display data one record at a time• Support paging, editing, inserting, and deleting
records
Repeater control allows any HTML content to be “repeated” for each row in a data source• Similar to a mail-merge in Word, but for HTML
46© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
All data-bound controls are used in a similar way• Can be configured using a wizard in the Visual Studio designer• Or can be configured in the ASP.NET source code directly
Each control is bound to a data source• Data sources retrieve the underlying data• The control then formats that data on the page
Configuring Data-Bound Controls
47© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
There are a number of different data source controls that can supply data to the controls• SQLDataSource is used to connect to any modern relational database• ObjectDataSource can return data from any function call
– Can also specify functions used to update data• XMLDataSource is used to display data from an XML file or web service• There are other data sources as well
Each data source works in a similar way• Every data-bound control
supports every data source
Data Sources
XML = extensible markup language
48© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
The case study uses SQLDataSource
1. Select the connection string
2. Save the connection string to the Web.config file
3. Select the table and fields to retrieve
4. Add Where clause to filter the data
Configure Data Source Wizard
49© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Once the data source is configured, the grid displays each column• Click Edit Columns to specify formatting options• Check Enable Paging to divide results into multiple smaller pages of data• Check Enable Sorting to allow records to be sorted by column
Customizing the DataGrid Control
50© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
ASP.NET Source Code
<asp:HiddenField ID="username" runat="server" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"DataSourceID="HistoryDataSource" AllowPaging="True">
<Columns><asp:BoundField DataField="QuestionTime" HeaderText="QuestionTime" /><asp:BoundField DataField="Equation" HeaderText="Equation" /><asp:BoundField DataField="CorrectAnswer" HeaderText="CorrectAnswer" /><asp:BoundField DataField="StudentAnswer" HeaderText="StudentAnswer" /><asp:BoundField DataField="Points" HeaderText="Points” />
</Columns></asp:GridView>
<asp:SqlDataSource ID="HistoryDataSource" runat="server"ConnectionString="<%$ ConnectionStrings:ConnectionString %>”
SelectCommand="SELECT [QuestionTime], [Equation], [CorrectAnswer], [StudentAnswer], [Points] FROM [Scores] WHERE ([Username] = @Username) ORDER BY [QuestionTime] DESC">
<SelectParameters><asp:ControlParameter ControlID="username" Name="Username”
PropertyName="Value" Type="String" /></SelectParameters>
</asp:SqlDataSource>
51© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Chapter Contents
Creating SQL Server Databases With Visual Studio
Hands-On Exercise 6.1
Database CRUD
Creating and Updating Records With Entity Framework
Hands-On Exercise 6.2
Retrieving Records
Hands-On Exercise 6.3
Data Binding With ASP.NET
Hands-On Exercise 6.4
52© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Hands-On Exercise 6.4
In your Exercise Manual, please refer to Hands-On Exercise 6.4: Data Binding With ASP.NET
53© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
You are now able to • Program a database application in .NET
You have Created a SQL Server database Written SQL queries to create, retrieve, update, and delete database data Executed SQL queries using Entity Framework code Automated the display of data on a web page using ASP.NET data binding
Chapter Summary
54© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
What do relational databases consist of?
What are the four types of queries used by application developers?
What tool in Visual Studio is used to access SQL Server databases?
What are the steps to executing a query in a .NET program?
Chapter 6 Review Questions
55© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Suppose you have a table called Users with the fields ID, Username, and Password, where ID is the primary key. Write valid Insert, Update, and Delete queries below:
Chapter 6 Review Questions
56© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-
Designing SQL Server databases, see• Course 2107, SQL Server® 2012 Introduction
To Learn More About…
®
2107
Deployment
Chapter 7
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
After completing this chapter, you will be able to • Deploy a .NET application
To accomplish this, you will see how to Use ClickOnce deployment to install the Flash Cards Windows version Publish the Flash Cards ASP.NET application to the web
Chapter Objectives
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
Chapter Contents
Prerequisites Deploying Windows Applications
With ClickOnce
Publishing Web Applications
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
Prior to .NET, Windows deployment required complex setup programs• Changes were made to the Windows Registry• Because components (.dlls) were shared by applications, installing a new
application sometimes broke an old application
.NET deployment has been vastly simplified• Install the .NET Framework in the target computer• Copy the application’s files onto that machine• Test!
Web and Windows deployment are only slightly different• Web applications need to be on a machine with IIS installed• A virtual directory needs to be created on the server to put the web application
in
Deploying .NET Applications
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
Download and install from Microsoft’s website• dotnetfx.exe is the program that needs to be downloaded and run• Make sure to get the correct version
– Version 1.1 if using Visual Studio 2003– Version 2.0 if using Visual Studio 2005– Version 3.5 if using Visual Studio 2008– Version 4.0 if using Visual Studio 2010– Version 4.5 if using Visual Studio 2012– Version 4.5.1 if using Visual Studio 2013
See Microsoft’s website for links and information• The .NET Framework home page:http://msdn.microsoft.com/netframework/
Important if deploying a web application!• IIS must be installed and running before installing the .NET Framework• Test it by opening a browser and typing:http://localhost
Installing the .NET Framework
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
Before deployment, change the build from Debug to Release• Optimizes the build for performance• Eliminates breakpoints• Removes any output to the debug window
Select the Build | Configuration Manager menu• Or just select Release from the Configuration Manager drop-down on the
Visual Studio toolbar
Configuring a Release Build
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
Every project is compiled to target a .NET Framework version• Can set this under Project Properties
The target framework must be installed on the target machine• Can specify an earlier version, but then newer .NET features are not available
Target Framework Version
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
Chapter Contents
Prerequisites
Deploying Windows Applications With ClickOnce
Publishing Web Applications
9© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
Publishing an application with ClickOnce• Copies the application and its required files to a virtual directory or folder• Automatically checks for and installs .NET on the user’s machine• Can automatically check for new versions of the application
Two types of ClickOnce deployments:• Launched applications• Installed applications
ClickOnce Deployment
10© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
Launched applications are available only over the web• Must click a hyperlink to the ClickOnce deployment manifest• To update a program, just re-publish it
– Most up-to-date version of the program is always run• Application cannot be run if the user is offline
Installed applications• The user must be online to do the initial install of the application• The application is downloaded and a Start menu icon is created
– The application now works on- or offline• Can configure the application to check for updates when it is run
Launched vs. Installed Applications
11© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
Done from the Publish tab of the project properties window• Publish location can be a web server, FTP server, or just a folder location• Specify whether to use a launched or installed application• Specify prerequisites and how to handle updates• Specify the version number
Configuring ClickOnce Deployment
FTP = File Transfer Protocol
12© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
Prerequisites are components required by the application• The correct version of the .NET Framework is always a prerequisite• May also include SQL Server Express, the Windows Installer, etc.• Prerequisites can be downloaded from the vendor’s website
Prerequisites
13© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
The deployment can be set up to check for new versions• Either before or after the application starts• The program will automatically look for new versions when started• Users will be prompted to install the new version
Specifying a minimum version number will force users to update
Updates
14© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
ClickOnce creates a setup program and a deployment manifest• Deploy to a web server, and then provide users a hyperlink to the manifest
If it is an installed application, a Start menu icon will be created• Users can remove the program from the Control Panel• The program will check for updates every time it is started
Deployed Files
15© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
Chapter Contents
Prerequisites
Deploying Windows Applications With ClickOnce
Publishing Web Applications
16© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
An ASP.NET application must be deployed to a server• Server requires Internet Information Services (IIS) to be installed
– Done differently depending on the version of Windows• ASP.NET must be installed on the server
as well
Multiple versions of ASP.NET can be installed on the same server• Each application must be configured to use
the correct version
Configuring IIS for ASP.NET Hosting
17© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
Every ASP.NET application runs in an application pool• One application pool is assigned as the default• Each application pool uses a .NET Framework version• Can add any number of application pools
Application pools also are assigned an identity• This is the account that an ASP.NET application will run under• The application cannot do anything not allowed by that account
Application Pools
18© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
An ASP.NET application will be assigned to the default application pool• Can be changed by going to that web application’s advanced settings
An ASP.NET application should have an application pool that• Uses the correct .NET Framework version• Has an identity that has
the rights required by the application
Assigning Application Pools to ASP.NET Websites
ASP.NET 3 and 3.5 applications use .NET 2 application pools.
ASP.NET 4.5 applications use .NET 4 application pools.
19© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
Can create publishing profiles that control how a website is deployed• Right-click the ASP.NET project and select Publish
Configure• Where the web application is deployed• Production database connection strings• Can deploy databases to a target SQL Server
Web Publishing
20© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
In the Connection tab, specify the target web server• Service URL is the domain name or IP address of the server• Site application is the target web application name• Web deployment must be configured on this server by the administrator
If web deployment is not enabled, select Web Deployment Package as the publish method• This will create a .zip file
with the application• This can then be imported
manually by the web serveradministrator
Specifying Web Server Location
21© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
Configure database settings on the Settings tab• Specify connection strings to production server• The Web.config file will be updated automatically on the web server• “Update database” checkbox will add databases to the database server
Database Settings
22© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
Click the Publish button to deploy the application• Web application will be created or updated on the web server• Databases will be deployed• Web.config file will be updated
Publishing the Application
23© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
The database connection string was hard-coded into the application• Once the site is deployed, this connection string will be different• The solution is to read the connection string from the config file at runtime
Steps:• Set a reference to the System.Configuration library• Use the ConfigurationManager class to read the connection string
VB code:
C# code:
Reading Connection Strings From the Web.Config File
Dim connection As String = ConfigurationManager.ConnectionStrings("FlashCardsConnectionString").ConnectionString
Return New DbContext(connection).Database
string connection = ConfigurationManager.ConnectionStrings["FlashCardsConnectionString"].ConnectionString;
return new DbContext(connection).Database;
24© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-
You are now able to • Deploy a .NET application
You have seen how to Use ClickOnce deployment to install the Flash Cards Windows version Publish the Flash Cards ASP.NET application to the web
Chapter Summary
Course Summary
Chapter 8
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-
We deployed our Flash Cards application. But then kids starting using it and, based on their feedback, we have the following additional requirements:1. The students said there should be levels. The questions should start easy
and get harder and they should get more points at higher levels2. There should be a High Scores page3. They want avatars (pictures that express their mood) attached to their
accounts4. They didn’t like how it looked. There needs to be a better theme and it
should be customizable by the student
This is your homework• Everything required to implement these features, we have learned this week
Those Ever-Changing Requirements
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-
Go to www.bbqmath.com to see a finished version of the case study• Completed source code is also available
Course 502 Case Study Online
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-
Please visit our .NET blog• http://dotnet.learningtree.com
Learning Tree International’s .NET Blog
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-
To learn more about analysis, OO design, and testing, see• Course 933, Agile Software Development and Modeling
To learn more about ASP.NET web development, see• Course 2621, Building ASP.NET Web Applications
To learn more about a .NET language, see• Course 419, C# Programming• Course 503, Visual Basic® Programming for .NET
Where to Go From Here
®
OO = object-oriented
9332621419503
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-
In this course, you have
Designed and programmed applications using Microsoft .NET and Visual Studio
Learned the syntax of the VB and C# programming languages
Written a .NET Windows Forms application
Coded for reuse using object orientation, inheritance, and class libraries
Created and programmed an ASP.NET website
Allowed users to log in and create accounts using Web Forms authentication
Created a SQL Server database
Saved and accessed database data using .NET
Deployed .NET Windows and web applications
Course Summary
Answers to Review Questions and Glossary
Appendix A
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-
• What are the different types of applications that can be created with .NET?
____________________________________________________________
• What is a .NET program’s entry point?
____________________________________________________________
• Which are the two most common .NET languages? Which is better?
____________________________________________________________
• What tool in Visual Studio is used to manage projects?
____________________________________________________________
• What is a statement?
____________________________________________________________
Chapter 1 Review Questions
Windows Forms, ASP.NET Web, Console applications, and others
A void function or subroutine called Main()
Visual Basic and C#. Both offer the same functionality; only the syntax is different.
Solution Explorer
A line of code
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-
• Code in .NET must be written inside a:
____________________________________________________________
• Name three things that might be in a class:
____________________________________________________________
• What must be specified when declaring a variable?
____________________________________________________________
Properties provide access to what within a class?
____________________________________________________________
Define a method:
____________________________________________________________
Chapter 1 Review Questions
A class
Fields (variables), Methods (functions), Properties (methods disguised as fields)
Name, data type, and visibility
The data required by a class
A method is a named block of code that performs a series of statements (a function).
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-
• What are the two types of numbers?
____________________________________________________________
• How would one decide whether to declare a variable as Integer or Long?
____________________________________________________________
• What does it mean to say that .NET is a type-safe environment?
____________________________________________________________
• How could a String be converted to an Integer?
____________________________________________________________
• What is implicit type conversion?
____________________________________________________________
Chapter 2 Review Questions
Integer and real numbers
Based on how large (or small) the variable could be
Only a valid value can be assigned to a variable based on its declared type
i = Integer.Parse("100") or Integer.TryParse("100", i)
An automatic type conversion that the system will do when there is no chance for loss of data. For example, when converting an Integer into a Double.
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-
What constructs can be used for a decision-making statement?
________________________________________________________________
What are the two types of loops?
________________________________________________________________
When should a Try-Catch error handler be used?
________________________________________________________________
Rewrite the following using a Select-Case or switch statement:
Chapter 2 Review Questions
Dim pet as StringIf pet = "Dog" then
Feed("Bone")ElseIf pet = "Cat" then
Feed("Catsup")ElseIf pet = "Frog" then
Feed("ToCat")Else
Feed("Steak")End If
If or Select-Case (switch)
For-Next and Do-While loops
In exceptional circumstances; i.e., things that are beyond a programmer’s control
Select Case petCase "Dog"
Feed("Bone")Case "Cat"
Feed("Catsup")Case "Frog"
Feed("ToCat")Case Else
Feed("Steak")End Select
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-
• What does a Windows application consist of?
____________________________________________________________
• What method is used to display a form on the screen?
____________________________________________________________
• What are some of the standard Windows controls?
____________________________________________________________
• What is the difference between an event and an event handler?
____________________________________________________________
• What does it mean to display a form modally? How is this done?
____________________________________________________________
Chapter 3 Review Questions
A collection of forms, each of which contains a collection of controls
Show()
Label, TextBox, Button, Checkbox, RadioButton, ComboBox, ListBox, etc.
An event is a message sent from a class; a handler is a function that runs in response
Code execution stops until a modal form is closed. Use the ShowDialog()method to display a form modally
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-
• Define the Single Responsibility Principle:
______________________________________________________________
• Define a constructor:
______________________________________________________________
• Give two reasons to use inheritance:
_______________________________________________________________
_______________________________________________________________
• List some advantages of class libraries:
_______________________________________________________________
Chapter 4 Review Questions
A class should have only one reason to change. It should do one complete job.
A function that runs automatically when a class is created
1. Reduce code duplication
2. Reduce complexity
Reusability, better organization, easier to divide the work on large projects
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-
• In web applications, requests are made via which protocol?
_______________________________________________________________
• What language is used to display data in a browser?
_______________________________________________________________
• What HTML tag is used to allow a user to send data to a web server?
_______________________________________________________________
• What would be the syntax for a link to Microsoft’s website?
_______________________________________________________________
Chapter 5 Review Questions
HTTP over TCP/IP
HTML
<Form></Form>
<a href="http://www.microsoft.com">Microsoft</a>
9© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-
• In .NET, what technology is used to create web applications?
_______________________________________________________________
• What property of the page object determines if the form was submitted?
_______________________________________________________________
• What ASP.NET object is used to create user variables?
_______________________________________________________________
• To force all users of a website to create an account, what access rule would be written?
_______________________________________________________________
Chapter 5 Review Questions
ASP.NET
IsPostback
Session
<deny users="?" />
10© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-
• What do relational databases consist of?
_____________________________________________________________
• What are the four types of queries used by application developers?
_____________________________________________________________
• What tool in Visual Studio is used to access SQL Server databases?
_____________________________________________________________
• What are the steps to executing a query in a .NET program?
_____________________________________________________________
Chapter 6 Review Questions
Tables, indexes, relationships
Select, Insert, Update, Delete
Server Explorer
1. Create a Entity Database object, using an appropriate connection string2. Specify a SQL query (including parameters) to run3. Use the ExecuteSQLCommand method of the DbContext.Database object,
including the SQL text and the required parameters
11© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-
• Suppose you have a table called Users with the fields ID, Username, and Password, where ID is the primary key. Write valid Insert, Update, and Delete queries below:
_______________________________________________________________
_______________________________________________________________
_______________________________________________________________
_______________________________________________________________
_______________________________________________________________
_______________________________________________________________
Chapter 6 Review Questions
Insert Into Users (ID, Username, Password) Values (@ID, @Username,@Password)
Update Users Set Username = @UserName, Password = @Password WhereID = @ID
Delete From Users Where ID = @ID
12© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-
Abstract method: A method definition inside a base class; there is no real implementation programmed, and it forces the derived class to include the method
Array: A variable that can contain multiple values
Class: The primary container for code in a .NET program, defined using the Class keyword; classes contain fields, methods, properties, events, and constructors
Constructor: A function that runs automatically when a class is created
Dialog form: A form that is used to query the user for information; typically shown on the screen modally
Event: A message sent from controls or other objects; some action causes an event to be raised; programmer can choose to respond to the event or not
Event handler: A function that runs in response to an event being raised
Glossary
13© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-
Exception: A message sent from a method in response to some invalid circumstance; exceptions must be caught, or the program will crash
Field: A variable declared directly inside a class, not inside a function
Function: A named block of code that performs a series of statements
HTML: (hypertext markup language) A text-based markup language used to format data in a browser
Index: Consists of one or more fields sorted alphabetically for each record; includes the position in the file for each record; indexes allow records to be found quickly
Inheritance: Allows a class to reuse and extend functionality of another; the base class provides the reusable behavior; the derived class can add new behaviors or change the existing behaviors
Integration tests: A higher-level test that proves that multiple units or classes work well together
Glossary
14© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-
Loop: A series of statements that needs to be repeated a number of times
Method: A function defined inside a class
Object: An instance of a class in memory, hence the term object-oriented programming
Property: A method disguised as a field; when fully implemented, contains two parts: the Get clause is used to return a value; the Setclause is used to change the value of an underlying field
Regression tests: Tests that prove that changes to code don’t break existing functionality
Relationship: Specifies how the records in the tables of a relational database are linked; one-to-many relationships are the most common, where the primary key of one table has a link to a foreign key in another table
Glossary
15© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-
Scope: Determines when a variable or function is loaded into memory; a variable or function is available as long as it is in memory; a variable’s lifetime ends when it goes out of scope, and it is removed from memory
Single Responsibility Principle: A class should have only one reason to change; it should do one job completely
Statement: A line of code
SQL: The standard language used by all databases, for all modifications
Unit tests: Low-level tests that prove that the functionality provided by “units” of code works correctly
Variable: A named location in memory used to store, retrieve, and change data
Virtual directory: A folder that appears to be below the web server’s root, but may be located at any physical location
Glossary
16© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-
Virtual method: A method that is programmed in the base class but can be changed in the derived class if necessary
Visibility: Determines whether a variable or function can be used outside its class; a variable’s or function’s visibility can be public or private
Glossary