1
CS 3870/CS 5870: Note05
Prog3
Web Application with Database
2
Master Page
• All Web pages will be similar
• Should be created before other web pages
• Add New Items
• Master Page
• Name: Prog3MasterPage.master
• Check “Place code in separate file”
• Uncheck “Select master page”– Could create a master page based on another master page
• May be incomplete and need to come back later
3
Elements on the Master page
• External CSS file<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
• Form– All controls should be inside Form for dynamic pages
• Two ContentPlaceHolder controls: could change id
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
<asp:ContentPlaceHolder id="ContentPlaceHolder1"
runat="server">
</asp:ContentPlaceHolder>
4
Elements on the Master page
• Leave ContentPlaceHolder empty
• Add all common elements before/after ContentPlaceHolder– Title and Names
– Adding navbar: incomplete
Content Pages• Create the three pages using the master page
– Add New Item
– Web Form
– Place code in separate file
– Select master page
– Add
– Select folder
– Select Master page
• The second web form
– Add
– Web Form (with master)5
Content Pages• No Form control on content pages
– The form control on the master page will be combined with the controls on the content page
• Two Content controls
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> </asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Prog3Body" Runat="Server">
</asp:Content>
• Type it if not there6
7
Complete the Navbar on Master Page
<ul class="navbar">
<li> <a href="Default.aspx"> All Products </a></li>
<li> <a href="Updating.aspx"> Updating Products </a></li>
<li> <a href="Shopping.aspx"> Shopping </a></li>
</ul>
Type and select the pages.
8
Adding Elements
• Type “All Products”, “Updating” and “Shopping” on the three pages
• Run IE to see the pages
9
The Database
• UWPCS3870
• SQL Server on Alpha
• User: MSCS
(not case sensitive)
• Password: MasterInCS
(case sensitive)
Table Product
Four Columns
ProductID : nchar(4), primary key,
not updatable
ProductNmae: nvarchar(50)
UnitPrice : smallmoney
Description : nvarchar(MAX), allow nulls
10
11
Accessing Database
• Data Source Controls– SqlDataSource
– AccessDataSource
– . . .
• Code class– Connection
– Command
– DataAdpater
– AdapterBuilder
• Prog3– Use Code class
ASP.NET Folders
• Solution Explorer
• Right click Web site
• Add ASP.NET Folder
• App_Code
• (App_Data)
• . . .
12
SQLDataClass
• Code class in folder App_Code
• No code module
• All variables and procedures should be
Shared (Static in C#, Java and C++)
• Otherwise, need to create object
13
Variables
Public Class SQLDataClass
Private Const ConStr As String = "Data Source=Alpha;” &
“Initial Catalog=UWPCS3870;Persist Security Info=True;” &
“User ID=MSCS;Password=MasterInCS"
Private Shared prodAdapter As System.Data.SqlClient.SqlDataAdapter
Private Shared prodBuilder As System.Data.SqlClient.SqlDataAdapter
Private Shared prodCmd As New Data.SqlClient.SqlCommand
Private Shared con As New Data.SqlClient.SqlConnection
Public Shared tblProduct As New Data.DataTable("Product")
. . .
End Class
The objects are available all the times.
14
Setup Command and Adapter
‘ Sets up the connection, command and adapter
Public Shared Sub setupProdAdapter()
con.ConnectionString = ConStr
prodCmd.Connection = con
prodCmd.CommandType = Data.CommandType.Text
prodCmd.CommandText = "Select * from Product order by ProductID"
prodAdapter = New System.Data.SqlClient.SqlDataAdapter(prodCmd)
prodAdapter.FillSchema(tblProduct, Data.SchemaType.Source)
End Sub
15
Retrieve Data Records‘ Gets the table records and the table schema
Public Shared Sub getAllProducts()
‘ Need to reset the command
prodCmd.CommandText = "Select * from Product order by ProductID"
Try
If Not tblProduct Is Nothing Then
tblProduct.Clear()
End If
prodAdapter.Fill(tblProduct)
Catch ex As Exception
Throw ex
Finally
con.Close()
End Try
End Sub 16
Setting up the Adapter
‘ Global.asax
Sub Application_Start(. . .)
SQLDataClass.setupProdAdapter()
End Sub
Do it just once for the application for all sessions of all users.
17
Setting up the AdapterPublic Shared Sub getAllProdcts()
If prodAdapter Is Nothing Then
setupProdAdapter()
End If
prodCmd.CommandText = "Select * from Product order by ProductID"
Try
. . .
End Try
End Sub
18
Binding Gridview
‘ Add a GridView on page Default.aspx
‘ GridView: ToolBox – Data
Protected Sub Page_Load(. . .) Handles Me.Load
SQLDataClass.getAllProducts()
GridView1.DataSource = SQLDataClass.tblProduct
GridView1.DataBind()
End Sub
Refill the data table for each page request.
19
Formatting GridView<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="False"
style="z-index: 1; position: relative; width: 50%; margin-left:25%;
align-items: center; height: 176px" >
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="Product ID" >
<ItemStyle HorizontalAlign="Center" Width="10%"></ItemStyle></asp:BoundField>
<asp:BoundField DataField="ProductName" HeaderText="Product Name" >
<ItemStyle HorizontalAlign="Left" Width="20%"></ItemStyle></asp:BoundField>
<asp:BoundField DataField="UnitPrice" HeaderText="Unit Price"
DataFormatString="{0:c}" HtmlEncode="False" >
<ItemStyle HorizontalAlign="Right" Width="10%"></ItemStyle></asp:BoundField>
<asp:BoundField DataField="Description" HeaderText="Description">
<ItemStyle HorizontalAlign="right" Width="10%"></ItemStyle></asp:BoundField>
</Columns>
</asp:GridView>
20
Page Updating
• Display record one at a time
• Display the first record for the first visit
• Display the same record for return visit
• Need Session variable
• Begin with “Prog3_”
21
Session Variables
Sub Session_Start(. . .)
Session(“Prog3_Index”) = 0
End Sub
Protected Sub Page_Load(…) Handles Me.Load
DisplayRow(Session("Prog3_Index"))
End Sub
22
Display RecordProtected Sub Page_Load(…) Handles Me.Load
DisplayRow(Session(“Prog3_Index”))
End Sub
Private Sub DisplayRow(Index As Integer)
Dim row As Data.DataRow
row = SQLDataClass.tblProduct.Rows(index)
‘ May need formatting
txtID.Text = row(0)
txtName.Text = row(1)
txtPrice.Text = row(2)
txtDescription.Text = row(3)
End Sub
23
Navigation Buttons
Partial Class Prog3_Updating
Protected Sub Button6_Click(…) Handles btnNext.Click
Session(“Prog3_Index”) += 1
DisplayRow(Session(“Prog3_Index”))
End Sub
Protected Sub Button6_Click(…) Handles btnPrevious.Click
Session(“Prog3_Index”) -= 1
DisplayRow(Session(“Prog3_Index”))
End Sub
24
Enable/Disable Buttons
Could make a private Sub.
Your choice.
25
Navigation Buttons
Partial Class Prog3_Updating
Protected Sub Button6_Click(…) Handles btnNext.Click
Session(“Prog3_Index”) += 1
DisplayRow(Session(“Prog3_Index”))
EnableDisableButtons()
End Sub
Protected Sub Button6_Click(…) Handles btnPrevious.Click
Session(“Prog3_Index”) -= 1
DisplayRow(Session(“Prog3_Index”))
EnableDisableButtons()
End Sub
26
Enable/Disable Buttons
Sub EnableDisableButtons()
if Session(“Prog3_Index”) = 0 Then
ElseIf Session(“Prog3_Index") =
SQLDataClass.tblProduct.Rows.Count - 1 Then
Else
End If
End Sub
27
SQL Statements
Update Product
Set ProductName = ‘NewName’,
UnitPrice = newPrice
Description = ‘NewDescription’,
Where ProductID = ‘theID’;
Insert Into Product
Values(‘ID’, ‘Name’, Price, ‘Description’);
Delete From Product
Where ProductID = ‘theID’;
28
Button Update
‘ Page Updating.Aspx
‘ID not to be modified
Protected Sub Button6_Click(…) Handles btnUpdate.Click
‘Dim theID As String = txtID.Text
Dim oldID As String =
SQLDataClass.tblProduct.Rows(Session(“Prog3_Index"))(0)
Dim newName As String = txtName.Text
Dim newPrice As Double = txtPrice.Text
Dim newDesc As String = txtDesc.Text
SQLDataClass.UpdateProduct(theID, newName,
newPrice, newDesc)
End Sub
29
UpdateProduct
‘ SQLDataClass
Public Shared Sub UpdateProduct(theID As String,
newName As String, newPrice As Double, newDesc As String)
‘ Building SQL statement with variables
prodCmd.CommandText = ". . ."
Try
con.Open()
prodCmd.ExecuteNonQuery()
Catch ex
Throw ex
Finally
con.Close()
End Try
End Sub 30
UpdateProduct
‘ SQLDataClass
Public Shared Sub UpdateProduct(theID As String,
newName As String, newPrice As Double, newDesc As String)
prodCmd.CommandText =
" Update Product" & _
" Set ProductName = ‘newName', " & _
" UnitPrice = newPrice, " & _
" Description = ‘newDesc'" & _
" Where ProductID = 'theID‘”
Try
. . .
End Try
End Sub
Incorrect! 31
UpdateProduct
‘ SQLDataClass
Public Shared Sub UpdateProduct(theID As String,
newName As String, newPrice As Double)
‘ Building SQL statement with variables
prodCmd.CommandText =
" Update Product " & _
" Set ProductName = " & newName & “, " & _
" UnitPrice = " & newPrice & ", " & _
" Description = " & newDesc & _
" Where ProductID = " & theID
Try
. . .
End Try
End Sub
Incorrect! 32
UpdateProduct
‘ SQLDataClass
Public Shared Sub UpdateProduct(theID As String,
newName As String, newPrice As Double)
‘ Building SQL statement with variables
prodCmd.CommandText =
" Update Product " & _
" Set ProductName = '" & newName & "'," & _
" UnitPrice = " & newPrice & ", " & _
" Description = '" & newDesc & "'" & _
" Where ProductID = '" & theID & "'“
Try
. . .
End Try
End Sub
Correct! 33
Try-Catch-FinallyPublic Shared Sub UpdateProduct(oldID As String,
newID As String, newName As String, newPrice As Double)
prodCmd.CommandText = ". . ."
Try
con.Open()
prodCmd.ExecuteNonQuery() ‘ update database
Catch ex
Throw new Exception(ex.Message & “ ” &
prodCmd.CommandText)
Finally
con.Close() ‘ always close it
End Try
End Sub
34
Button Update
‘ Page Updating.Aspx
Protected Sub Button6_Click(…) Handles btnUpdate.Click
Dim . . .
Try
DataClass.UpdateProduct(theID, newName,
newPrice, newDesc)
txtMsg.Text = "Record updated“
‘ must update tblProducts
SQLDataClass.getAllProduct()
Catch ex
txtMsg.Text = ex.Message ‘including myCmd.CommandText
End Try
End Sub 35
36
Updating
‘ Page Updating.Aspx
Partial Class Prog3_Updating
Inherits System.Web.UI.Page
Protected Sub Page_Load(. . .) Handles Me.Load
txtMsg.Text = ""
DisplayRow(Session(“Prog3_Index"))
End Sub
Cannot Update Correctly!
37
Updating
Partial Class Prog3_Updating
Inherits System.Web.UI.Page
Protected Sub Page_Load(. . .) Handles Me.Load
txtMsg.Text = ""
DisplayRow(Session(“Prog3_Index"))
End Sub
Cannot Update Correctly!
Post Back!
38
PostBack
Partial Class Prog3_Updating
Inherits System.Web.UI.Page
Protected Sub Page_Load(. . .) Handles Me.Load
txtMsg.Text = “”
If Not IsPostBack Then
DisplayRow(Session(“Prog3_Index"))
Else
‘ Do not do anything
‘ Textboxes keep their values from client
End If
End Sub
39
PostBack
Partial Class Prog3_Updating
Inherits System.Web.UI.Page
Protected Sub Page_Load(. . .) Handles Me.Load
txtMsg.Text = “”
‘ Else is not needed
If Not IsPostBack Then
DisplayRow(Session(“Prog3_Index"))
End If
End Sub
Buttons
• btnNew– New– Save New
• btnDelete– Delete– Cancel
• Enabled/Disabled
40