9781285096261_ch15_PPTx
Download
Report
Transcript 9781285096261_ch15_PPTx
15
Web-Based
Applications
C# Programming: From Problem Analysis to Program Design
C# Programming: From Problem Analysis to Program Design
4th Edition
1
Chapter Objectives
• Discover how Web-based applications differ from
Windows applications
• Use ASP.NET to create Web applications
• Develop and configure Web Forms pages
• Learn about different types of controls that can be
added to Web applications
• Add HTML and Web Forms server controls to
Web applications
C# Programming: From Problem Analysis to Program Design
2
Chapter Objectives (continued)
• Add validation, custom, and composite controls to
verify user input, display calendars, and connect to
database tables
• Become aware of Web Services and Windows
communication Foundation (WCF) and their
implications for distributed applications
• Learn how mobile applications for smart devices
are developed using Visual Studio
C# Programming: From Problem Analysis to Program Design
3
Web-Based Applications
• Runs within an Internet browser
• Collection of one or more related files or
components stored on a server
• Web server is software that hosts or delivers Web
application
• Hardware at location where Web server software
is loaded is often called a Web server
– It is the software that makes the equipment special
and thus enables the computer to be called a server
C# Programming: From Problem Analysis to Program Design
4
Web Programming Model
• MessageBox dialog boxes are not used with Web
applications
– Output would be displayed on the server
– Output displayed through Label or other objects on Web
page
• Each request to view a Web page requires round trip to
the server
– Requests page via Hypertext Transfer Protocol (HTTP)
– Page sent back as Hypertext Markup Language (HTML)
document
C# Programming: From Problem Analysis to Program Design
5
Web Programming Model
(continued)
• Page is rendered – converted from HTML upon
return to the browser
• Every postback trip to the server creates new
object
– Causes Web pages to be stateless
• Pages do not retain their values from one trip to the
Web server to the next
C# Programming: From Problem Analysis to Program Design
6
Static Pages
• Client-side application
• Provide no interaction with the user
• Does not require any processing on the client
computer or by a Web server
– Precreated pages residing on the server's hard drive
– Delivered as HTML or XHTML document
• Files contains formatting markup tags
C# Programming: From Problem Analysis to Program Design
7
Static Pages (continued)
Figure 15-1 Output from a Web page
C# Programming: From Problem Analysis to Program Design
8
Static Pages (continued)
<xhtml>
<head>
<!-- default.htm -->
<title>
Simple Static Page
</title>
<!-- creates caption -->
</head>
<!-- comments on right -->
<body bgColor="#aabbff"> <!-- blue background -->
<center>
<h1> Example page </p> </h1>
<br/> <br/>
<!-- break to next line-->
<img src="bird.jpg" />
</center>
<br/> <br/>
<a href="http://www.cengage.com/ + . . .">Doyle’s Books at Cengage</a>
Review StaticPage Example
C# Programming: From Problem Analysis to Program Design
9
Dynamic Pages
• Involve processing in addition to rendering the
formatting HTML tags
• One programming model is to use traditional or
classic Active Server Pages (ASP)
– Includes script code in the HTML file – client-side
scripts
– Server-side scripts require processing to be done at
the server level before page is delivered
– VBScript and JavaScript – scripting languages
C# Programming: From Problem Analysis to Program Design
10
Dynamic Pages (continued)
Figure 15-2 Server-side processing of a dynamic Web page
C# Programming: From Problem Analysis to Program Design
11
ASP.NET
• Does not require writing code in a separate
scripting language
• Includes a number of classes as part of the .NET
Framework
• To identify an ASP from an ASP.NET Web
application, look at file extensions
– ASP Web page ends with an .asp file extension
– ASP.NET Web page ends with an .aspx file
extension
C# Programming: From Problem Analysis to Program Design
12
ASP.NET (continued)
• Two options for developing ASP.NET
applications
• Use the new ASP.NET Development Server
– Available with Visual Studio
– Preferred option for developing and testing
applications from a directory on a local machine
• Second option: use Microsoft Internet Information
Services (IIS)
C# Programming: From Problem Analysis to Program Design
13
Visual Studio for Web Developer
•
•
•
•
Includes built-in ASP.NET development server
WYSIWYG – drag-and-drop approach to design
Includes features to publish applications
Includes option to create a File System Web site
– Store and run your Web application in any
directory on your local machine
• Development Server does not enable the site to be
accessed by remote machines or multiple users
C# Programming: From Problem Analysis to Program Design
14
IIS option
• To use this option, Microsoft Internet Information
Services (IIS) must be installed
– IIS provides software tools for managing Web
server
– IIS requires a server-like operating system
– IIS component should be installed before loading
the .NET Framework
C# Programming: From Problem Analysis to Program Design
15
ASP.NET Programming Models
• Model-View-Controller (MVC)
– Separates application into three attributes
• Model – info for app is described, including data
and validation rules
• View described through HTML markup
• Controller contains the control-flow logic, which
describes interaction between the Model and View
• Lower level – doesn’t provide widget controls
• Web Forms Page
C# Programming: From Problem Analysis to Program Design
16
Web Forms Page
• System.Web.UI namespace
– Namespace includes Control class, inherited by the
HTMLControl and WebControl classes
– Namespace also includes Page class
• Web applications designed with event-driven
model, but there are fewer events
– Web Forms page instead of Windows Forms
• Build an ASP.NET Web application; two separate
files are created
C# Programming: From Problem Analysis to Program Design
17
Web Forms Page (continued)
• Web Forms page file
– Stores visual elements
– Container file from which the controls are displayed
– Contains static XHTML tags
• Code-behind file
– Where the programming logic resides
– Stores event-handler methods
C# Programming: From Problem Analysis to Program Design
18
Creating a Web Site
By default,
projects are
created at
http://localhost
when HTTP is
selected.
Browsing is
enabled with
File System
option
Figure 15-3 Web application template for ASP.NET
C# Programming: From Problem Analysis to Program Design
19
Creating a Web Site (continued)
• Unlike sites created with IIS, you can select any
directory location on local machine
• Files are not stored at localhost
(c:\Inetpub\wwwroot)
• Create Web page using
– FILE > New > Web Site
instead of File > New > Project
• Open existing Web page
– FILE > Open > Web Site
C# Programming: From Problem Analysis to Program Design
20
Creating a Web Site (continued)
Selecting File
System option
enables you to
specify where the
Web site files are
stored on your
local machine
Figure 15-4 Opening an existing Web site
C# Programming: From Problem Analysis to Program Design
21
Web Page
• File ending in .aspx holds the HTML tags
– View and directly edit the HTML source
– Tags are automatically inserted for head, title, body,
form, and div
• First two lines in the .aspx markup file are called
page directives
– Page directives are delimited with <% and %>
• Language is identified and CodeFile name is listed
• AutoEventWireup attribute set to true
– Event-handler methods in the class are used
C# Programming: From Problem Analysis to Program Design
22
Web Page (continued)
Selected
Source
tab
Figure 15-5 Source code for HTML file
C# Programming: From Problem Analysis to Program Design
23
Web Page (continued)
• When a new Web Site using the ASP.NET Web
Forms Site template is created, automatically get
MasterPage added
– attribute, MasterPageFile="~/Site.Master",
specifies the path for MasterPage
– should see Site.master in the Solution Explorer
window
• Inherits attribute identifies which class the codebehind file extends
C# Programming: From Problem Analysis to Program Design
24
Web Page (continued)
• Web sites
created using
ASP.NET
Web Forms
Site option
open with
this template
• Master page
and
Cascading
Style Sheet
included
Figure 15-6 HTML document in Design mode
C# Programming: From Problem Analysis to Program Design
25
Master Pages
• Allows you to create and maintain a consistent
theme across several pages for a Web site
• Site.master node listed in the Solution Explorer
window is master page
– Automatically created when you create New, Web
Site, ASP.NET Web Forms Site
– File ends with an extension of .master
– Contains formatting XHTML tags
– Can include static text, HTML, and server controls
C# Programming: From Problem Analysis to Program Design
26
Master Pages (continued)
Figure 15-7 Site.master Master page
C# Programming: From Problem Analysis to Program Design
27
Master Pages (continued)
• Default.aspx page has a special @ Master
directive instead of @ Page directive
• Master pages consist of two pieces: master page
itself and one or more content pages
– When users request content pages, master page is
merged with content page to produce output
• Master page has one or more ContentPlaceHolders
defined with an ID
C# Programming: From Problem Analysis to Program Design
28
Master Pages (continued)
Lines 4
through 32
provide the
content for
the
MainContent
ContentPlace
Holders
Figure 15-8 MainContent in the About.aspx page
C# Programming: From Problem Analysis to Program Design
29
Master Pages (continued)
Lines 21
through 41
provide the
content for
the
MainContent
ContentPlace
Holders for
the
Default.aspx
page
Figure 15-9 MainContent in the Default.aspx page
C# Programming: From Problem Analysis to Program Design
30
Master Pages (continued)
• <asp:Content in content pages is what ties the
element back to the Site.master page
– DynamicPage Web application includes content
pages for Default, About, and Contact. Additional
contact pages (Login and Register) are under
Account node.
• Content folder node shown in the Solution
Explorer window reveals a file named Site.css
– Site.css is a style sheet automatically added when
ASP.NET Web Forms Site template selected
C# Programming: From Problem Analysis to Program Design
31
Cascading Style Sheet (CSS)
• CSS enables more consistency across pages
– Able to separate actual content from the appearance
• Uses style sheets to describe how elements will
look in terms of their layout, fonts, and colors
• Style sheet includes a list of rules
– Each rule consists of selector and one or more
declarative blocks
• Declarative block enclosed in curly brace
• Inside block find property, colon and value
C# Programming: From Problem Analysis to Program Design
32
Cascading Style Sheet (continued)
Style
sheet is
very
readable
and easy
to
modify
Figure 15-10 Site.css
C# Programming: From Problem Analysis to Program Design
33
Cascading Style Sheet (continued)
body
Declarative block
Selector
{
background-color: #fff;
border-top: solid 10px #000;
color: #333;
font-size: .85em;
font-family: "Segoe UI", Verdana, Helvetica, Sans-Serif;
margin: 0;
padding: 0;
}
Property
Value
C# Programming: From Problem Analysis to Program Design
34
Cascading Style Sheet (continued)
• Can go directly
into the Sites.css
file and type new
values or add
additional
property lines
• OR, use the
Modify Style
configuration
Figure 15-11 Modify Style
wizard
C# Programming: From Problem Analysis to Program Design
35
Code-Behind File
• Initially looks similar to Windows applications, but
it is different
• No Main( ) method
– Page_Load( ) event handler
• Contains many namespaces imported automatically
• Can debug and execute Web application from
within the IDE
– Default Web browser is launched
C# Programming: From Problem Analysis to Program Design
36
Code-Behind File (continued)
Figure 15-12 Code-behind file
C# Programming: From Problem Analysis to Program Design
37
Code-Behind File (continued)
• Auto generated code not created for applications
until you run the application
– No hidden .designer.cs file as with Windows apps
• Default.aspx created and automatically opened in
Source view when you first start building a Web
site
• App_Data folder is automatically created
– Reserved for storing data files
Review DynamicPage Example
C# Programming: From Problem Analysis to Program Design
38
ASP.NET Empty Web Site
• No files are created when you select FILE, New,
Web Site, ASP.NET Empty Web Site
– No extra folders are created
– To get the .aspx file added, select Add New Item,
Web Form from Solution Explorer window
• Code-behind file (.aspx.cs) is then created
• Like Windows applications, can set some
properties during design using Properties window
– Adds code to .aspx, file containing the HTML tags
C# Programming: From Problem Analysis to Program Design
39
HTML Document File
• Page object properties – fewer (and named
differently) than available Windows Form object
Table 15-1 HTML document properties
C# Programming: From Problem Analysis to Program Design
40
HTML Document File (continued)
Table 15-1 HTML document properties (continued)
C# Programming: From Problem Analysis to Program Design
41
Controls
• Standard
• Data
• Validation
• Navigation
• Login
• WebParts
• AJAX Extensions
• Dynamic Data
• Reporting
• HTML
C# Programming: From Problem Analysis to Program Design
42
Controls (continued)
• Toolbox controls available in both Design and
Source mode
– Drag and drop controls onto the .aspx Source
(HTML) markup page as easily as you drop it on
Design page
• Several different types of controls available in
Toolbox
• Most Web Forms controls you will be using are
stored under the Standard node on the Toolbox
C# Programming: From Problem Analysis to Program Design
43
HTML Controls
• Can be added to your page using a WYSIWYG
drag-and-drop approach
– FORMAT menu enables you to change Font,
Background or Foreground Color, or add New Style
• Can Set Position to Relative or Absolute positioning
– Can select controls and use Align, Rights or Lefts or Justify
• TABLE menu enables you to insert tables or merge
cells
• Special Block Format tool on Formatting toolbar
– Enables you to select a segment of text and apply styles
like heading tags or create ordered or unordered lists
C# Programming: From Problem Analysis to Program Design
44
HTML Controls (continued)
Figure 15-13 Block format for design mode
C# Programming: From Problem Analysis to Program Design
45
Adding HTML
Controls
• Client side controls
• Limited number of HTML controls
• Input Text and Image objects
added to HTMLExample Web
application
– FILE, New, Web Site, ASP.NET
Empty Web Site selected
– Default.aspx file added
Figure 15-14 HTML controls
C# Programming: From Problem Analysis to Program Design
46
HTML Controls (continued)
HTML controls
do not maintain
state
Values in text
boxes lost when
Submit clicked
Figure 15-15 Submit button clicked
C# Programming: From Problem Analysis to Program Design
47
HTML Server Controls
• You can give the server access to the values entered
by the user
• Running HTML Controls as Server Controls
– runat="server" attribute is automatically added to the
tags for controls from Standard tab on Toolbox
• Controls become programmable – double clicking
Button now generates event-handler method
• runat="server" attribute added to HTML tags to
button and Input(Text) controls
C# Programming: From Problem Analysis to Program Design
48
HTML Server Controls (continued)
<h3 style="text-align: left">First name:<input id="txtFirst"
runat="server" type="text" /></h3>
<h3 style="text-align: left"> </h3>
<h3 style="text-align: left">Last name:<input id="txtLast"
runat="server" type="text" /></h3>
<h3 style="text-align: left"> </h3>
<h3 style="text-align: left">Email:<input id="txtEmail"
runat="server" type="text" /></h3>
C# Programming: From Problem Analysis to Program Design
runat="server"
added to HTML
Input (Text)
textboxes
49
Server Control Events
private void btnSubmit_ServerClick(object
sender, EventArgs e)
{
this.lblResult.Text = "Thanks!! "Text
+
this.txtFirst.Value + " "property
+
used with
this.txtLast.Value +
Label
" Information will be forwarded
to: " +
this.txtEmail.Value;
Value property
}
used with
Input(Text) control
Review HTMLExample Example
C# Programming: From Problem Analysis to Program Design
50
Server Control Events (continued)
Number in address
bar following
localhost (as the port
number) is a
relatively random
number, placed there
when you specify the
Location as File
System
Figure 15-16 Web page after postback
C# Programming: From Problem Analysis to Program Design
51
Web Forms Standard Server
Controls
• Can mix and match HTML and Standard controls
on your page
• Web Forms Server Controls referred to as
Standard controls
– Also referred to as Web Server controls, Web
controls, ASP server controls, or simply Web
Forms controls
C# Programming: From Problem Analysis to Program Design
52
Available Web Forms Controls
• Standard Controls have more built-in features than
HTML controls
– Look and act like their Windows counterparts
(Fewer controls and fewer events to program)
– Use object-oriented model
• Web Forms controls do not map straight to HTML
– Often it may take several HTML tags to represent
one Web Forms control
C# Programming: From Problem Analysis to Program Design
53
Web Forms Server Controls
(continued)
•
Figure 15-17 Web Forms server standard controls
C# Programming: From Problem Analysis to Program Design
54
Web Forms Server Controls (continued)
• Visual Studio prefixes the control name with
<asp:control and ends the tag with /asp:control>
– Also runat= "server" appended
<asp:controlName attributes runat="server" /asp:control>
– Other attributes included with XHTML tags
• ASP.NET run time automatically performs the
code generation
– Runtime creates partial class dynamically
C# Programming: From Problem Analysis to Program Design
55
Web Forms Controls of the Common
Form Type
• Fewer properties found with Web Forms types of
controls than you find with their Windows Forms
counterparts
• Control’s properties, like Windows apps, can be
set using the Properties window in Visual Studio
– Settings (visual) are stored in the HTML document
– File ending with the .aspx extension
C# Programming: From Problem Analysis to Program Design
56
HTML (.aspx) File
• Setting Button object’s ID (name) as btnSubmit,
changing its Text value to Submit Info, changing
positioning properties, and registering eventhandler method produces following tags:
<asp:Button ID="btnSubmit" runat="server"
style="z-index: 1; left: 400px; top: 321px;
position: absolute; width: 90px; height: 24px;
text-align: center" Text="Submit Info"
OnClick="btnSubmit_Click" />
C# Programming: From Problem Analysis to Program Design
57
Changing Properties within
Visual Studio
• Comparison of Windows Forms button with Web
Forms Standard button control object
–
–
–
–
Windows Forms button: 60 events
Web Forms Standard button control: 8 events
Windows Forms button control: 76 properties
Web Forms Standard button control: 36 properties
C# Programming: From Problem Analysis to Program Design
58
Changing Properties
within Visual
Studio (continued)
Figure 15-18 Properties for the
Label control object
C# Programming: From Problem Analysis to Program Design
59
Events
• By default, only a few events trigger postback to the
server
– Buttons click events do
– Changes in selections to ListBox, RadioButton,
RadioButtonList, CheckBox, CheckBoxList, and
DropDownList do not
• AutoPostBack property can be set to true to
automatically trigger a postback to the server
• Be judicious with changes to AutoPostBack property
C# Programming: From Problem Analysis to Program Design
60
Adding Common Form-Type
Controls
Web site
called
WebControls
created using
ASP.NET
Empty Web
Site template
Figure 15-19 Web site after adding server controls
C# Programming: From Problem Analysis to Program Design
61
Wiring Event-Handler Methods
Figure 15-20 Wiring the same event
to three RadioButton objects
All three radio buttons
wired to the same
event-handler method
C# Programming: From Problem Analysis to Program Design
62
RadioButton Event-Handler
Method
private void radioButton_CheckedChanged(object sender,
System.EventArgs e)
Method the
{
three radio
if (this.radBtnFresSop.Checked)
buttons
{
invoke
this.lblClassif.Text = "Freshmen & Sophomores ";
}
else if (this.radBtnJrSr.Checked)
{
// More statements
C# Programming: From Problem Analysis to Program Design
63
Button Event-Handler Method
(continued)
private void btnSubmit_Click(object sender, System.EventArgs e)
{
this.lblSubmit.Text = "Thanks " + this.txtBxFname.Text +
"! You will be contacted... ";
Retrieve values
from
from
TextBox
TextBox…
and
if (lstBxInterests.SelectedIndex > -1)
selections
and selections
from
{
from
ListBox
ListBox
this.lblSubmit.Text += " to discuss joining" +
" the \"" + this.lstBxInterests.SelectedItem.Text + "\" team.";
}
}
C# Programming: From Problem Analysis to Program Design
64
Validation, Custom, and Composite
Controls
Table 15-2 Controls of .NET validation
C# Programming: From Problem Analysis to Program Design
65
Validation Control Properties
• Treat validation control objects like any other
control (drag and drop onto page)
• Properties
– ControlToValidate
• Tie the validation control to a specific page control
object
– ErrorMessage
• Set to the message you want displayed when the
input control does not pass the validation
C# Programming: From Problem Analysis to Program Design
66
Validation Controls (continued)
RequiredField
Validator
control is
placed beside
the object it is
validating
Figure 15-21 Adding a
RequiredFieldValidator control
C# Programming: From Problem Analysis to Program Design
67
Page Validation
• Every control field on the page that has an
associated validation control is checked when the
page is posted
• CausesValidation property of Button(s) can be set
to false
– By default, every Button object's CausesValidation
property is set to true
C# Programming: From Problem Analysis to Program Design
68
Page Validation (continued)
Figure 15-22 Error message from the
RequiredFieldValidator control
C# Programming: From Problem Analysis to Program Design
69
Calendar Control
• Display calendar months on a Web page
– Calendar is live
– Can view and select dates
• Properties
– SelectedDate
• Used to pick the month, day, and year for display
• Initially set to the current date; date can be set
programmatically
– Customize with gridlines, borders; change font,
background, foreground colors; set cell padding
and spacing
C# Programming: From Problem Analysis to Program Design
70
Calendar Control (continued)
Use Page_Load( )
event-handler
method to set the
date with program
statements
Figure 15-23 Switching between .aspx and .aspx.cs files
C# Programming: From Problem Analysis to Program Design
71
Calendar Control
(continued)
• Calendar control is based on
DateTime class
– DateTime includes a large
number of useful members
Figure 15-24 Using the Properties
window to set the SelectedDate
property
C# Programming: From Problem Analysis to Program Design
72
Date
Time
class
Table 15-3
Members of
the DateTime
class
C# Programming: From Problem Analysis to Program Design
73
Using a Calendar Control in
Applications
private void btnShowNextMeeting_Click
(object sender, System.EventArgs e)
{
Calendar1.SelectedDates.Clear( );
DateTime meetingDate = new DateTime (DateTime.Today.Year,
DateTime.Today.Month, DateTime.Today.Day, 8,0,0);
meetingDate = meetingDate.AddDays(7);
if (meetingDate.DayOfWeek.ToString() == "Sunday")
{
Event-handler
meetingDate = meetingDate.AddDays(1);
for
}
Next Meeting
button
C# Programming: From Problem Analysis to Program Design
74
Using a Calendar Control in
Applications (continued)
Calendar1.TodaysDate = meetingDate;
Calendar1.SelectedDate = Calendar1.TodaysDate;
this.lblMsg.Text = ("Meeting next week: " +
meetingDate.DayOfWeek +
", " + meetingDate.Month +
"/" + meetingDate.Day + " at " +
meetingDate.Hour + " P.M.");
}
// end of btnShowNextMeeting_Click( ) method
C# Programming: From Problem Analysis to Program Design
75
Calendar Control (continued)
Displayed date
(for next meeting)
Figure 15-25 Calendar showing different dates selected
C# Programming: From Problem Analysis to Program Design
76
GridView Controls
• Similar to DataGridView used with Windows
applications
• Display data in a tabular format
– Each row represents record; column represents field
• Can bind data to a data source, such as a database
• Common data source classes used to bind
GridView objects to the actual data
– DataReader
– DataSet
C# Programming: From Problem Analysis to Program Design
77
GridView Control
• GridView features
– Automatic data binding
– Auto generation of buttons for selecting, editing,
and deleting
– Automatic sorting
– Automatic paging
• GridView control for displaying data from Access
database added to WebControls example
C# Programming: From Problem Analysis to Program Design
78
Using a DataGrid Control in
Applications
• Use OleDB Data Provider for Access database
– Connection string identifies the provider as an
Access database and specifies the name of the
database
• Follow same guidelines/steps used to connect to
database using Windows application
– Minor change needed for Web application
• DataBind( ) method call is different for Web
applications
C# Programming: From Problem Analysis to Program Design
79
WebControls Application –
Database Access
private void btnShowMembers_Click(object sender, System.EventArgs e)
{
lblMembers.Visible = true;
try
{
string sConnection =
"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=C:\\CSharpProjects\\member.accdb";
OleDbConnection dbConn = new OleDbConnection(sConnection);
string sql = "Select FirstName, LastName From memberTable " +
"Order By LastName Asc, FirstName Asc;";
C# Programming: From Problem Analysis to Program Design
80
OleDbCommand dbCmd = new OleDbCommand( );
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
OleDbDataAdapter memberDataAdap = new
OleDbDataAdapter( );
memberDataAdap.SelectCommand = dbCmd;
DataSet memberDS = new DataSet( );
// DataSet declared as protected class member
memberDataAdap.Fill(memberDS, "memberTable");
grdViewMembers.DataSource = memberDS;
// Binding is only change needed from the Windows app
this.grdViewMembers.DataBind( );
lblMembers.Visible = true;
grdViewMembers.Visible = true;
}
catch (System.Exception exc)
{
this.lblMsg.Text = exc.Message;
}
}
Review WebControls Example
C# Programming: From Problem Analysis to Program Design
81
AccessDataSource
• Can use the data visual configuration tools and
have statements automatically generated for you
– Instead of writing the program statements
• AccessDataSource and SqlDataSource
– These classes reduce the need for accessing
individual Data Provider classes
– All providers (SQL Server, Oracle, ODBC, and
OLEDB) can use SqlDataSource.
C# Programming: From Problem Analysis to Program Design
82
AccessDataSource (continued)
•
•
•
•
AccessDataSource inherits from the SqlDataSource
Use SQL queries to perform data retrieval
Includes large number of properties and methods
Do not have to set the Connection String property
– Just identify the location of the Access file using the
DataFile property
– Can provide relative path to the data base
• Use visual configuration tools to connect
C# Programming: From Problem Analysis to Program Design
83
Using Visual Tools to Connect
GridView object
dragged to form
New Data
Source
Smart tag
Figure 15-26 Binding data source to the GridView
C# Programming: From Problem Analysis to Program Design
84
Use Visual Tools to Connect (continued)
Figure 15-27 Connecting to Access database
C# Programming: From Problem Analysis to Program Design
85
Use Visual Tools to Connect (continued)
Place database
in the reserved
App_Data
directory
Figure 15-28 Relative address for the Access database
C# Programming: From Problem Analysis to Program Design
86
Use Visual Tools to Connect (continued)
Database is now referenced
by a relative path…if you
move the Web Site,
ASP.NET looks for
database in App_Data
folder
Figure 15-29 AccessDataSource Object
C# Programming: From Problem Analysis to Program Design
87
Use Visual Tools to Connect (continued)
Query builder
launched if
you select
these buttons
Figure 15-30 Identify what data to retrieve
C# Programming: From Problem Analysis to Program Design
88
Use Visual Tools to Connect (continued)
• Options available from
GridView’s smart tag
to enable paging,
sorting, and selection
• Enable Sorting makes
it possible for you to
select a column and
have table reordered
• Edit Columns option
displays dialog box
with field properties
Figure 15-31 GridView tasks
C# Programming: From Problem Analysis to Program Design
89
Setting the Visibility Property
• With WebControls Example, method
btnShowMembers_Click( ) no longer needs code
to connect to the database and populate the control
on the page
– Done behind the scenes by the Configure Data Source
wizard
protected void btnShowMembers_Click(object sender, EventArgs e)
{
lblMembers.Visible = true;
Visible property
grdViewMembers.Visible = true;
initially set to
}
false
C# Programming: From Problem Analysis to Program Design
90
Modifying the Data
• By default, DataGrid control displays data in readonly format
– To allow users to edit data, use Advanced tab from
the Data Source Configuration tool to configure the
select statement
• This generates the additional Insert, Delete, and
Update SQL statements
– All primary key values must be retrieved as part of
the select statement
– Key columns can be removed using the smart tag
once the configuration is complete
– Smart tag then reveals options of Enable Editing and
Enable Deleting.
C# Programming: From Problem Analysis to Program Design
91
Use Visual Tools to Connect (continued)
• If Enable Editing
and Enable
Deleting selected,
new columns are
display when
application runs
– Edit
– Delete
Clicking the Edit button
causes the row of data to
be displayed in an
editable format
Figure 15-32 Modifying
data table
Review
WebControlsUsingConfigTool
Example
C# Programming: From Problem Analysis to Program Design
92
Other Controls
• Navigation
– Can add site navigation by defining a site map
• Use controls such as TreeView and SiteMapPath
• Data
– Explore DetailsView and FormView controls
– Display and edit data from different data sources
– Automatically retrieve data when page runs
C# Programming: From Problem Analysis to Program Design
93
Other Controls (continued)
• Login
– Security control that enables you to authenticate users
– PasswordRecovery control helps users change or
remember passwords
– LoginStatus control lets you present a Login or
Logout button
C# Programming: From Problem Analysis to Program Design
94
Other Controls (continued)
Table 15-4 Additional Web Forms control classes
C# Programming: From Problem Analysis to Program Design
95
Other
Controls
(continued)
Table 15-4 Additional
Web Forms control
classes (continued)
C# Programming: From Problem Analysis to Program Design
96
Web Services
• Enable exchange of data from one computer to
another, over the Internet or an intranet
– Applications that return data
– Do not involve presentation layer
• Uses standard protocols
– Hypertext Transfer Protocol (HTTP)
– Extensible Markup Language (XML)
– Simple Object Access Protocol (SOAP)
– Web Services Description Language (WSDL)
C# Programming: From Problem Analysis to Program Design
97
Web Services (continued)
• Messages are sent as XML from one method to
another
– Data is physically returned as part of an XML
message
• XML uses tags to provide format for describing data
like HTML
– HTML tags tell browser how to display data in
different formats
– XML is readable
– XML uses tags to describe the data being exchanged
C# Programming: From Problem Analysis to Program Design
98
Windows Communication
Foundation (WCF)
• Application Programming Interface (API)
• Used to build connected service-oriented
applications
• Provides class libraries and tools for enabling
software entities to communicate using any
protocol, including those used by Web services
• WCF supports sending messages by using HTTP,
as well as TCP, named pipes, and Microsoft
Message Queuing (MSMQ)
C# Programming: From Problem Analysis to Program Design
99
Smart Device Applications
(Optional)
• Mobile application development involves writing
apps for handheld devices (Smart phones or tablets)
• Many different platforms
– Most are incompatible
– Android, Apple iOS, Blackberry and Windows Phone
• Windows Phone successor to Windows Mobile
platform
• Two options for developing Windows Phone apps
C# Programming: From Problem Analysis to Program Design
100
Smart Device Applications
(continued)
• Can create Windows 8 or Windows 7.x mobile
applications using Visual Studio
– To create a Windows 8 Phone application, you
must be running Windows 8 operating system and
have 4 MB of RAM
– Windows 7.x applications can be created on
machines running earlier operating systems
versions
C# Programming: From Problem Analysis to Program Design
101
Smart Device Applications
(continued)
• If you install Visual Studio 2012 on a Windows 8
machine, whenever you create a Windows Phone
application, you are able to select which Windows
Phone platform (Windows 8 or Windows 7.5) you
want to target
• Can download the Windows Phone Software
Development Kit (SDK)
– Microsoft provides an SDK for both platforms
http://dev.windowsphone.com/en-us/downloadsdk
C# Programming: From Problem Analysis to Program Design
102
Windows Phone SDK
• Includes a phone-based design surface, a code
editor, Windows Phone project templates, and a
Toolbox that contains Windows Phone controls
• Enables you to debug your applications on a
Windows Phone emulator or an actual Windows
Phone device
– Emulator provides a virtualized environment
• Functioning Windows Phone is displayed
C# Programming: From Problem Analysis to Program Design
103
Windows 7.x Phone
• SDK for Windows 7.x enables you to design
applications for Windows 7.5 and 7.0 devices.
• Template for developing applications for
Windows Phone 7.x targets Silverlight
– Web application framework that enables you to
integrate multimedia-like graphics, sounds, and
animations into applications
C# Programming: From Problem Analysis to Program Design
104
Silverlight
• Uses a subset of the framework
– Graphical user interfaces are less sophisticated
• Fewer controls and events
• User interfaces that are declared in Extensible
Application Markup Language (XAML)
– XAML file contains a Canvas object, which acts as
placeholder for other elements
C# Programming: From Problem Analysis to Program Design
105
Creating a Smart Device Application
for Windows 7.x Phones
• With Windows 7.x Phone SDK installed, create
mobile apps much same as other types of
applications
• Select File, New, Project, Visual C#, Silverlight
for Windows Phone
– Select Windows Phone Application
• Blank miniature phone is displayed with a left
arrow, Windows logo, and a search tool
– ContentGrid is placed on the phone
C# Programming: From Problem Analysis to Program Design
106
Creating a Smart Device Application
(continued)
Figure 15-33 Windows phone application
C# Programming: From Problem Analysis to Program Design
107
Create Smart Device Application
(continued)
Figure 15-34 Adding controls to the smart device application
C# Programming: From Problem Analysis to Program Design
108
Create Smart Device
Application (continued)
• To illustrate developing for
smart device application, metric
calculator designed
• Use WYSIWYG approach;
controls dragged and dropped
onto phone
• Properties are set like other apps
• Format alignment tools
• Double-click on controls to
register default event-handler
Figure 15-35 Metric/English
methods
Converter final design
C# Programming: From Problem Analysis to Program Design
109
Creating a Smart Device
Application (continued)
• Two RadioButton objects provide functionality for
the app
– GroupName property was set to Convert (same
name for both RadioButtons)
• To make sure only one button checked at a time
• Only programming statements added were those
included in the event-handler methods
– Statements placed in code behind file
• .xaml.cs file
C# Programming: From Problem Analysis to Program Design
110
Creating a Smart Device
Application (continued)
private void radBtns_Checked (object sender, System.EventArgs e)
{
if (rdBtnInches.IsChecked == true)
txtBlkOutput.Text = "Result: "
+ (double.Parse(txtBxInput.Text) * 0.3937008).ToString("F2");
else
txtBlkOutput.Text = "Result: "
+ (double.Parse(txtBxInput.Text) * 2.54).ToString("F2");
}
private void menuExit_Click (object sender, System.EventArgs e)
{
this.Close( );
}
C# Programming: From Problem Analysis to Program Design
111
Building and
Running the
Smart Device
Application
• Click Start Without
Debugging on the Debug
• Takes a couple minutes to
load emulator
• Smart device app complete
with Web browser
Figure 15-36 Phone emulator
Review PhoneApplication Example
C# Programming: From Problem Analysis to Program Design
112
Creating a Smart Device Application
(continued)
Figure 15-37 WinPhone
App running
C# Programming: From Problem Analysis to Program Design
Figure 15-38 Smart device
application output
113
Windows 8 Phone Apps
• New user interface, featuring Metro
– Flat colored live tiles
• New SDK integrates Expression Blend into Visual
Studio
• Limitations for developing Windows 8 Phone apps
– Must be developed and run under the Windows 8
os on 64 bit machines with 4 GB RAM and 8 GB
disk space
• Install Windows Phone SDK
C# Programming: From Problem Analysis to Program Design
114
Windows 8 Phone Apps (continued)
Figure 15-39 Install Windows Phone SDK 8
C# Programming: From Problem Analysis to Program Design
115
Creating a Windows 8 Phone
App
• To illustrate developing app for Windows 8
phone, PhoneBrowser app designed
– Controls dragged and dropped onto phone
• WebBrowser control placed on ContentPanel
– Values changed in Properties window
• Document Outline window
– Useful for selecting control
C# Programming: From Problem Analysis to Program Design
116
XML
• .xaml file
– Stores XHTML tags…. telling browser how to
display data
• Comments enclosed between <!-- and -->
• One comment automatically added that
recommends “Uncomment out alignment grid
code”
• Click event is registered for the Go button
– Click="btnGo_Click" tag is added to the .xaml file
C# Programming: From Problem Analysis to Program Design
117
XAML Code
• Grid controls used to place items on page
– Top layer Grid named LayoutRoot → has a
StackPanel
• StackPanel is named TitlePanel → has a tag
Grid.Row="0"
• Another Grid, ContentPanel placed at
Grid.Row="1"
• Grids added by default when Windows Phone App
template selected
C# Programming: From Problem Analysis to Program Design
118
Code-Behind File
• MainPage.xaml.cs file stores code-behind file
• Only program statements added to this application
was btnGo_Click( ) event-handler method
private void btnGo_Click(object sender, RoutedEventArgs e)
{
string site = txtBxURL.Text;
webWindow.Navigate(new Uri(site, UriKind.Absolute));
}
Review PhoneBrowser Example
C# Programming: From Problem Analysis to Program Design
119
Running the App
• Launch app like other Visual Studio applications
– Before launching, determine where output will be
displayed
• Deploy to a Windows 8 Phone device
• Deploy to Windows 8 Phone emulator
• Requirements for emulator
– Must be running Windows 8 os on 64-bit machine
that supports SLAT
– Hyper-V must be enabled
C# Programming: From Problem Analysis to Program Design
120
Running the App (continued)
Figure 15-40 Phone Browser deployed to Emulator
C# Programming: From Problem Analysis to Program Design
121
Running the App (continued)
Figure 15-41 PhoneBrowser loaded on Emulator
C# Programming: From Problem Analysis to Program Design
122
Running the App (continued)
• Change phone settings on
emulator, move or resize
tiles, and execute other apps
• Can use PC keyboard to
enter text
– PageUp/PageDown (on PC)
switches between
emulator/PC
Figure 15-42 Emulator running application
C# Programming: From Problem Analysis to Program Design
123
Deploying to a Device
• Can deploy, or send, app to Windows 8 Phone
– Limited to 10 apps on your phone at one time
• Phone must be unlocked for debugging and testing
• Must have Windows Phone Developer Account
http://dev.windowsphone.com
• Must register phone or device as a developer
device
C# Programming: From Problem Analysis to Program Design
124
Deploying to a Device (continued)
Figure 15-43 Device selected for deployment
C# Programming: From Problem Analysis to Program Design
125
Deploying to a Device (continued)
Figure 15-42 Emulator running application
C# Programming: From Problem Analysis to Program Design
126
Coding Standards
• Use an appropriate classification suffix to
differentiate between the control objects
• Code-behind files should contain the
programming logic for the event handler
• Name controls that will be used in programming
statements…before they are placed in the codebehind file
C# Programming: From Problem Analysis to Program Design
127
Resources
Official Microsoft ASP.NET site –
http://www.asp.net/
Jump Start with ASP.NET Starter Kit –
http://msdn.microsoft.com/en-us/magazine/cc164097.aspx
Windows Communication Foundation –
http://msdn.microsoft.com/en-us/library/dd936243.aspx
Downloads at Microsoft –
http://www.microsoft.com/downloads
C# Programming: From Problem Analysis to Program Design
128
Resources (continued)
Windows Phone Development –
http://msdn.microsoft.com/enus/library/ff402535%28v=VS.92%29.aspx
Channel 9 - Windows Phone 7 Development –
http://channel9.msdn.com/Series/Windows-Phone-7Development-for-Absolute-Beginners
Which server-side technology should I choose? –
http://www.adobe.com/devnet/dreamweaver/articles/which_s
erverside_technology.html
C# Programming: From Problem Analysis to Program Design
129
Resources (continued)
Web Services @ W3C –
http://www.w3.org/2002/ws/
DreamSpark –
https://www.dreamspark.com
Windows Phone Developer Account –
http://dev.windowsphone.com
C# Programming: From Problem Analysis to Program Design
130
Chapter Summary
• Web site
– Static versus dynamic pages
• Protocols
HTML, HTTP, XHTML
•
•
•
•
ASP.NET
MVC
Master Pages
Web Forms page
– Creating Web page
C# Programming: From Problem Analysis to Program Design
131
Chapter Summary (continued)
• Web-based versus Windows applications
• Cascading Style Sheets
• Controls
– HTML, HTML server, Standard controls
• Validation, navigation, login, data
• Calendar
– Postback
• Connect to database tables
– Programmatically
– Use visual configuration tools
C# Programming: From Problem Analysis to Program Design
132
Chapter Summary (continued)
• Web services
– Windows Communication Foundation for service
oriented applications
• Smart device applications (optional)
– Windows 7.x Phone
– Windows 8 Phone
C# Programming: From Problem Analysis to Program Design
133