Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to ASP.NET, Second Edition2 Chapter Objectives.

Similar presentations


Presentation on theme: "Introduction to ASP.NET, Second Edition2 Chapter Objectives."— Presentation transcript:

1

2 Introduction to ASP.NET, Second Edition2 Chapter Objectives

3 Introduction to ASP.NET, Second Edition3 Using Data Sources in Visual Studio.NET The process of binding the data is the same regardless of the data source – DataReader - provides a read-only, direct connection to the data source – DataSet - accesses data as multiple DataTables – DataTables - can have relationships defined between the DataTable Objects – DataView - subset of one of the DataTables within the DataSet

4 Introduction to ASP.NET, Second Edition4 The DataReader Object Retrieve a read-only, non-buffered stream of data from a database – One record at any one time is stored in memory – When the new record is read, the old record is removed from memory first – Stream of data, retrieved sequentially – SqlDataReader - SQL Server – OledbDataReader - other OLE DB databases

5 Introduction to ASP.NET, Second Edition5 Using a DataReader Object with an Access Database 1.Create connection string, Connection object, open Connection 2.Create a variable - SQL command or stored procedure 3.Create Command object - SQL and Connection object 4.Declare variable - DataReader Object 5.ExecuteReader of Command object - retrieve data and place data in DataReader 6.Read data from DataReader object, and write column values to the Web page 7.Close the DataReader object and connection

6 Introduction to ASP.NET, Second Edition6 Using the DataReader to Retrieve Data from a Database DataReader.aspx (Page 382) Dim CS As String = "Provider=Microsoft.Jet.OLEDB.4.0;  Data Source=C:\Inetpub\wwwroot\Chapter8\data\  TaraStore.mdb;" Dim objCN As New OleDb.OleDbConnection(CS) objCN.Open() Dim mySQL As String = _ "SELECT CategoryName FROM Categories" Dim objCM As New OleDb.OleDbCommand(mySQL, objCN) Dim objDR As OleDb.OleDbDataReader objDR = objCM.ExecuteReader() Dim MyCat As String While objDR.Read() MyCat = MyCat + (objDR("CategoryName") & " ") End While objDR.Close() objCN.Close() lblCat.Text = MyCat

7 Introduction to ASP.NET, Second Edition7 DataReader.aspx (continued)

8 Introduction to ASP.NET, Second Edition8 Building Advanced Queries Using SQL Retrieve a select group of records using a criterion that is used to filter the records A search condition evaluates to True or False – Strings are case-sensitive – WHERE keyword identify search condition – “AND” - conditions must resolve to True – “OR” - one condition needs to resolve to True WHERE user = ' katie ' ANDS pwd = ' pass ' WHERE lastVisit>#11/12/2003# OR member= ' new '

9 Introduction to ASP.NET, Second Edition9 Building Advanced Queries Using SQL (continued) Search condition expression – Keyword NULL to search for empty fields – Valid comparison operators include +,, <>, IS, and ISNOT SELECT CategoryName, CategoryID, CatImage, Thumbnail, Description FROM Categories WHERE (CategoryName='Jewelry') OR (CategoryID>3) ORDER BY CategoryName ASC

10 Introduction to ASP.NET, Second Edition10 Building SQL Queries to Insert, Modify, and Delete Data Insert record INSERT INTO Products(name, price) VALUES('chair',153.00) Concatenate the statement into a String SQL = "UPDATE Products SET " & _ " ProductName='Claddagh Ring'," & _ " UnitCost='25.45' WHERE ProductID=353"

11 Introduction to ASP.NET, Second Edition11 Securing SQL Databases SQL injection – attach SQL statements to an existing SQL query to run additional commands – Use stored procedures – Verify data entry – Strong passwords – combination of numbers and special characters to make it more difficult to guess

12 Introduction to ASP.NET, Second Edition12 Using the DataReader Object with a SQL Server Database Use different objects - SqlConnection, SqlCommand, and SqlDataReader – Steps same for both the OleDb and SqlClient DataReader.aspx – Rewritten to support a SQL Server database using the SqlDataReader

13 Introduction to ASP.NET, Second Edition13 Upsizing an Access Database to SQL Server Ch8TaraStoreSQL (Page 391) Better security, performance, user management Print or save Upsize Report TSUpsizeReport.html Tools menu, Database Utilities – IUSR_MachineName – read permission to display data – User account – write permission to upsize – SA user have CREATE DATABASE privileges Create a page to display your data

14 Introduction to ASP.NET, Second Edition14 Using the DataReader Object to Display Data DataReaderSQL.aspx (Page 394) Add Connection object SqlConnection1.Open() Dim mySQL As String = _ "SELECT CategoryName FROM Categories" Dim objCM As New _ SqlClient.SqlCommand(mySQL, SqlConnection1) Dim objDR As SqlClient.SqlDataReader objDR = objCM.ExecuteReader() Dim MyCat As String While objDR.Read() MyCat = MyCat + (objDR("CategoryName") & " ") End While objDR.Close() SqlConnection1.Close() lblCat.Text = MyCat

15 Introduction to ASP.NET, Second Edition15 Using the DataReader Object with Stored Procedures DataReaderStoredProc.aspx (Page 396) Create stored procedure CREATE PROCEDURE dbo.CategoryList AS SELECT * FROM Categories ORDER BY CategoryID ASC RETURN Create Connection object

16 Introduction to ASP.NET, Second Edition16 DataReaderStoredProc.aspx (continued) SqlConnection1.Open() Dim objCM As SqlClient.SqlCommand objCM = New _ SqlClient.SqlCommand("CategoryList", _ SqlConnection1) objCM.CommandType = CommandType.StoredProcedure Dim objDR As SqlClient.SqlDataReader objDR = _ objCM.ExecuteReader(CommandBehavior.CloseConnection) MyList.DataSource = objDR MyList.DataBind()

17 Introduction to ASP.NET, Second Edition17 Using the DataReader Object with Parameters DataReaderDisplay.aspx (Page 398) Delete Connection object and replace with new Create stored procedures CREATE PROCEDURE dbo.SubCategoryByCategory @CategoryID int AS SELECT * FROM SubCategories WHERE CategoryID = @CategoryID ORDER BY SubCategoryID RETURN

18 Introduction to ASP.NET, Second Edition18 DataReaderDisplay.aspx (continued) CREATE PROCEDURE dbo.ProductsBySubCategory @SubCategoryID int AS SELECT * FROM Products WHERE SubCategoryID = @SubCategoryID ORDER BY ModelName RETURN CREATE PROCEDURE dbo.SingleProductByProductID @ProductID int AS SELECT * FROM Products WHERE ProductID = @ProductID ORDER BY ModelName RETURN

19 Introduction to ASP.NET, Second Edition19 How the QueryString Passes Data from the Database DataReaderProducts.aspx – 4 functions - data bound to DataList control – Pass parameters Show - set ImageUrl selItem - selected item CatID, SubCatID, ProdID Creates Categegory List – GetCat() -> CategoryList

20 Introduction to ASP.NET, Second Edition20 DataReaderDisplay.aspx (continued) Click on category – DataReaderProducts.aspx ?CatID=21&selItem=0 &Show=cat GetSubCats(CatID) SubCategoryByCategory – SubCategories list bound to MySubCatList LargeImage Show = cat – ImageUrl = "images/CatPics/" & CatID & ".jpg"

21 Introduction to ASP.NET, Second Edition21 DataReaderDisplay.aspx (continued) Click on subcategory – ?CatID=21&SubCatID=1 &selItem=0& Show=prodlist GetProducts(SubCatID) ProductsBySubCategory – Products list bound to MyProdList LargeImage Show = prodlist – "images/SubCatPics/" & SubCatID & ".jpg"

22 Introduction to ASP.NET, Second Edition22 DataReaderDisplay.aspx (continued) Click on subcategory – ?ProdID=548&CatID=21 &SubCatID=1 &selItem=0&Show=prod GetProduct (ProdID ) SingleProductByProductID – Products list bound to MyProduct LargeImage Show = prod – "images/ProductPics/" & ProdID & ".jpg"

23 Introduction to ASP.NET, Second Edition23 DataReaderProducts.aspx (Page 401) Delete Connection and replace with new Insert code to pass parameter to stored procedure Dim paramCatID As SqlParameter paramCatID = New SqlParameter("@CategoryID", SqlDbType.Int, 4) paramCatID.Value = CatID objCM2.Parameters.Add(paramCatID)

24 Introduction to ASP.NET, Second Edition24 The DataAdapter, DataSet, and DataView Objects Summary of Steps 1.DataAdapter (Connection and SQL) 2.Generate DataSet from the Data menu 3.DataView object 4.Assign Table to the DataView 5.Assign DataSource to DataView 6.DataAdapter.Fill(DataSet) 7.Bind the controls to data source Page.DataBind() or Control.DataBind()

25 Introduction to ASP.NET, Second Edition25 The DataAdapter, DataSet, and DataView Objects (continued) Assign Table to DataView in code SqlDataAdapter1.Fill(MyDS) Dim MyDV As DataView =  New DataView(MyDS, "Categories") MyDG.DataSource = MyDV MyDG.DataBind() Table Collection – use index position Dim objDV As New DataView() objDV = DS11.Tables(0).DefaultView MyDG.DataSource = objDV MyDG.DataBind()

26 Introduction to ASP.NET, Second Edition26 The DataAdapter, DataSet, and DataView Objects (continued) Create objects manually Dim CN As New SqlConnection(CS) Dim MySQL As String =  "Select * From Categories" MyDS = New DataSet() MyDA = New SqlDataAdapter(MySQL, CN) MyDA.Fill(MyDS, "Categories")

27 Introduction to ASP.NET, Second Edition27 Using the DataView to Retrieve Data from a Database DataViewProducts.aspx (Page 406) DataAdapter, DataSet, DataView Products table Filter DataView – Set RowFilter to SubCategoryID=19 Add data binding code SqlDataAdapter1.Fill(DS_DataViewProducts1) Page.DataBind()

28 Introduction to ASP.NET, Second Edition28 Customizing the DataGrid Control Code behind the page, or visual tools Data Columns – Bound columns - data that is bound to a column display the data, use the data in an expression, – Unbound columns - display content – buttons Supports Sorting, Paging, and Filtering data

29 Introduction to ASP.NET, Second Edition29 Paging and Sorting Data with the DataGrid Control PageSortProducts.aspx (Page 409) Link Button control top of the column – Sorted by that column DataGrid does not actually sort the rows – Raises a SortCommand event – Data rebound to the DataSource – Add code to sort the data if the event occurs – Sort expression passed Represented as e.SortExpression – Get value selected as the sort key – Rebind the DataGrid to DataView

30 Introduction to ASP.NET, Second Edition30 PageSortProducts.aspx (continued) Displays a subset of records across Web pages – Navigation bar page (LinkButtons) – Default number of records - 10 – Turned off by default Paging property of the DataGrid (AllowPaging) – Raises PageIndexChanged event – Add code to handle the event – Set CurrentPageIndex to NewPageIndex – Rebind the data

31 Introduction to ASP.NET, Second Edition31 PageSortProducts.aspx (continued) DataAdapter, DataSet, DataView Set DataGrid Properties – Set to True ShowFooter, ShowHeader, AllowSorting, AllowPaging – PageSize – 3 – Change NextPrevText to Next; PrevPageText to Previous; Position to TopAndBottom Fill DataSet and bind DataGrid

32 Introduction to ASP.NET, Second Edition32 PageSortProducts.aspx (continued) SortCommand DataView1.Sort = e.SortExpression MyDG.DataBind() PageIndexChanged MyDG.CurrentPageIndex = e.NewPageIndex MyDG.DataBind()

33 Introduction to ASP.NET, Second Edition33 Filtering Data with the DataGrid Control DataSetSearch.aspx (Page 412) Temporarily select a subset of records Does not remove the data from the database RowFilter property of DataView When the filter is removed, the records are redisplayed within the Web page

34 Introduction to ASP.NET, Second Edition34 DataSetSearch.aspx (continued) Dim MySearch As String If Not Page.IsPostBack Then txtSearch.Text = "" MyDG.Visible=False Else BindMyDG() End If MySearch = "ModelName LIKE '*" &  txtSearch.Text & "*'" objDV.RowFilter = MySearch RecNum = objDV.Count.ToString MyDG.DataSource = objDV Page.DataBind()

35 Introduction to ASP.NET, Second Edition35 DataSetSearch.aspx (continued)

36 Introduction to ASP.NET, Second Edition36 DataSetSearch.aspx (continued)

37 Introduction to ASP.NET, Second Edition37 DataSetSearch.aspx (continued) CREATE PROCEDURE dbo.FilterDataGrid @MySearchTerm nvarchar(20) AS SELECT * FROM Products WHERE (ModelName LIKE @MySearchTerm ) ORDER BY ModelName RETURN

38 Introduction to ASP.NET, Second Edition38 DataSetSearch.aspx (continued)

39 Introduction to ASP.NET, Second Edition39 Inserting, Modifying, and Deleting Records Create new records, modify existing records, and delete records Use SQL commands Methods built into Data controls ItemCommand and CommandBuilder – to build your own methods

40 Introduction to ASP.NET, Second Edition40 Using the DataGrid Control to Maintain a Database Style Properties – AlternatingItemStyle – alternating rows – EditItemStyle – row being edited – FooterStyle – footer row – HeaderStyle – header row – ItemStyle – individual items within list or control – PagerStyle – page selection controls – SelectedItemStyle – currently selected item

41 Introduction to ASP.NET, Second Edition41 Using the DataGrid Control to Maintain a Database (continued) HeaderText, HeaderImageURL, and FooterText – top and bottom of TemplateColumn – contain HTML elements and controls Visible property – show or hide column SortExpression property – identify the column used when sorting the column DataField property – data column bound DataFormatString property – formatting rules ReadOnly property – stop editing a column

42 Introduction to ASP.NET, Second Edition42 Using the DataGrid Control to Maintain a Database (continued) ItemTemplate – HTML elements and controls TemplateColumn – additional content, HTML – EditCommandColumn (cover later) – DeleteCommandColumn (cover later) EditItemTemplate – edit mode HyperLinkColumn – bind a hyperlink to data ButtonColumn – insert a user defined button – ButtonType – LinkButton (hyperlink) or PushButton (button)

43 Introduction to ASP.NET, Second Edition43 Using the DataGrid Control to Maintain a Database (continued) Retrieve data in TextBox control Sub UpdateItem(ByVal sender As Object, ByVal e As DataGridCommandEventArgs) Dim MyData As String Dim MyTB As TextBox MyTB = CType(e.Item.Cells(1).Controls(0), TextBox) MyData = MyTB.Text End Sub 

44 Introduction to ASP.NET, Second Edition44 Using the DataGrid Control to Maintain a Database (continued) E.Item and FindControl to locate column Sub UpdateItem(ByVal sender As Object, ByVal e As DataGridCommandEventArgs) Dim MyData As String Dim box As TextBox MyTB = CType(e.Item.Cells(1).FindControl("FirstName"), TextBox) MyData = MyTB.text End Sub  

45 Introduction to ASP.NET, Second Edition45 Inserting a New Record with the DataReader Control and with Stored Procedures and Parameters Create stored procedure CREATE Procedure AddCatSQL ( @CatName nvarchar(50), @CatImage nvarchar(50), @CatThumb nvarchar(50), @CatDesc ntext, @CatID int OUTPUT ) AS INSERT INTO Categories (CategoryName, CatImage, Thumbnail, Description) VALUES (@CatName, @CatImage, @CatThumb, @CatDesc) SELECT @CatID = @@Identity

46 Introduction to ASP.NET, Second Edition46 InsertCat.aspx (Page 420) btnAdd event handler Dim CatDesc As String = tCatDesc.Text Create parameters – returns CatID Dim pCatID As SqlClient.SqlParameter pCatID = New SqlClient.SqlParameter("@CatID", SqlDbType.Int, 4) pCatID.Direction = ParameterDirection.Output oCM.Parameters.Add(pCatID) 

47 Introduction to ASP.NET, Second Edition47 InsertCat.aspx (continued) Create parameters Dim pCatDesc As SqlClient.SqlParameter pCatDesc = New SqlClient.SqlParameter("@CatDesc", SqlDbType.NText) pCatDesc.Value = CatDesc oCM.Parameters.Add(pCatDesc) 

48 Introduction to ASP.NET, Second Edition48 InsertCat.aspx (continued) Run command Preview page SqlConnection1.Open() oCM.ExecuteNonQuery() SqlConnection1.Close()

49 Introduction to ASP.NET, Second Edition49 Deleting a Record with the DataGrid Control Different methods Use a built-in TemplateColumn – DeleteCommand Built-in method of Delete Column Delete LinkButton – ItemCommand – create command functions ButtonColumn – trigger Delete function

50 Introduction to ASP.NET, Second Edition50 DeleteCat.aspx (Page 421) DataAdapter, DataSet, DataView Fill DataSet and bind DataGrid Preview Data

51 Introduction to ASP.NET, Second Edition51 DeleteCat.aspx (continued) Insert columns manually DataKeyField is CategoryID Modify template properties Insert code to call RemoveFromCat function <asp:LinkButton ID="RemoveButton" CommandName="RemoveFromCat" Text="Delete" ForeColor="blue" runat="server" />

52 Introduction to ASP.NET, Second Edition52 DeleteCat.aspx (continued) ItemCommand function If e.CommandSource.CommandName = "RemoveFromCat" Then... Else End If Page.DataBind() 

53 Introduction to ASP.NET, Second Edition53 DeleteCat.aspx (continued) Retrieve current row’s CatID and delete row Dim CatIDCell As TableCell = e.Item.Cells(1) Dim CatID As String = CatIDCell.Text Dim oCM As SqlClient.SqlCommand Dim MySQL As String MySQL = "DELETE FROM Categories WHERE CategoryID =" & CatID oCM = New SqlClient.SqlCommand(MySQL, SqlConnection1) SqlConnection1.Open() oCM.ExecuteNonQuery() SqlConnection1.Close() Page.DataBind() Response.Redirect("DeleteCat.aspx")  

54 Introduction to ASP.NET, Second Edition54 Using the DeleteCommand Property of the DataGrid Control to Delete Data DeleteCatDelCmd.aspx (Page 426 ) OnDeleteCommand property - assign Delete function... 

55 Introduction to ASP.NET, Second Edition55 DeleteCatDelCmd.aspx (continued) Function deletes records, rebinds data Sub MyDG_DeleteCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls. DataGridCommandEventArgs) Handles MyDG.DeleteCommand... MySQL = "DELETE FROM Categories WHERE CategoryID = @CatID" objCM = New SqlClient.SqlCommand(MySQL, objCN) objCM.Parameters.Add(New SqlParameter("@CatId", SqlDbType.Int)) objCM.Parameters("@CatId").Value = MyDG.DataKeys(CInt(e.Item.ItemIndex))... Delete code and rebind function End Sub     

56 Introduction to ASP.NET, Second Edition56 Updating the Database Using the DataGrid Control EditCat.aspx (page 427) Page 427 - Part 1 – Creates basic data objects, bind DataGrid – DataAdapter, DataSet, DataView, DataGrid SqlDataAdapter1.Fill(DS_EditCat1) If Not Page.IsPostBack Then Page.DataBind() End If Page 431 - Part 2 – Inserts the data-editing code

57 Introduction to ASP.NET, Second Edition57 EditCat.aspx (continued)

58 Introduction to ASP.NET, Second Edition58 EditCat.aspx (continued) EditCommandColumn – A special button column – LinkButtons labeled Edit, Update, and Cancel – Change text - EditText, UpdateText, CancelText Events when click on the buttons – EditCommand – UpdateCommand – CancelCommand Event handlers assigned in DataGrid using properties – onEditCommand, onCancelCommand, onUpdateCommand

59 Introduction to ASP.NET, Second Edition59 EditCat.aspx (continued) DataGrid – DataKeyField to CategoryID – DataMember to Categories Insert "Edit, Update, Cancel" column (EditCommandColumn) Import data namespaces Imports System.Data.SqlClient

60 Introduction to ASP.NET, Second Edition60 EditCat.aspx (continued) CancelCommand method – Display mode MyDG.EditItemIndex = -1 MyDG.DataBind() EditCommand function – Edit mode MyDG.EditItemIndex = e.Item.ItemIndex MyDG.DataBind()

61 Introduction to ASP.NET, Second Edition61 EditCat.aspx (continued) UpdateCommand – retrieve values from TextBoxes Dim key As String = _ MyDG.DataKeys(e.Item.ItemIndex).ToString Dim CatName, CatImage, CatThumb,CatDesc As String Dim tb As TextBox tb = CType(e.Item.Cells(2).Controls(0), TextBox) CatName = tb.Text tb = CType(e.Item.Cells(3).Controls(0), TextBox) CatImage = tb.Text tb = CType(e.Item.Cells(4).Controls(0), TextBox) CatThumb = tb.Text tb = CType(e.Item.Cells(5).Controls(0), TextBox) CatDesc = tb.Text

62 Introduction to ASP.NET, Second Edition62 EditCat.aspx (continued) Value of key to locate row (r) and assign values Dim r As MyDS.CategoriesRow r = MyDS1.Categories.FindByCategoryID(key) r.CategoryName = CatName r.CatImage = CatImage r.Thumbnail = CatThumb r.Description = CatDesc Update method SqlDataAdapter1.Update(DS1) MyDG.EditItemIndex = -1 MyDG.DataBind()

63 Introduction to ASP.NET, Second Edition63 Building Reusable Visual Basic.NET Database Components Create reusable, compiled components that create objects, access stored procedures, and return data 3 Parts – Page 435 - Web.config Application variable stores connection string – Page 436 - Ch8Products.vb Component and class - 4 functions retrieve data – Page 438 - CatMenu.aspx Instantiate the object, call functions, retrieve data, bind data to DataList

64 Introduction to ASP.NET, Second Edition64 Creating a Global Variable in the Web Configuration File Web.Config - contains the connection string – Is an XML-based text file – Comments using HTML comment tags – appSettings tag indicates Web site settings – Add tag - create global application variables

65 Introduction to ASP.NET, Second Edition65 Creating a Global Variable in the Web Configuration File Web.config (Page 435) After tag <add key="CSTS" value="server=(local)\NetSDK; uid=sa;pwd=password; database=Ch8TaraStoreSQL" />  

66 Introduction to ASP.NET, Second Edition66 Creating a Visual Basic.NET Component Ch8Products.vb (Page 436) Create component, Add Connection Import namespaces Imports System.Data.SqlClient Imports System.Configuration Copy 4 functions from DataReaderDisplay.aspx

67 Introduction to ASP.NET, Second Edition67 Ch8Products.vb (continued)

68 Introduction to ASP.NET, Second Edition68 Calling the Component from the Web Page CatMenu.aspx (Page 438) Instantiating the class as a new object from Ch8ProductsDB class General process for each step – Create a variable named store each object created by Ch8Products class – Assign DataSource property of Data List to data returned by DataReader from function – Bind the data control.

69 Introduction to ASP.NET, Second Edition69 CatMenu.aspx (continued) Retrieves category list Dim CatList As Chapter8.Ch8Products CatList = New Chapter8.Ch8Products MyCatList.DataSource = CatList.GetCat() MyCatList.DataBind() Retrieves subcategory list Dim SubCatList As Chapter8.Ch8Products SubCatList = New Chapter8.Ch8Products MySubCatList.DataSource = SubCatList.GetSubCats(CatID) MySubCatList.DataBind()

70 Introduction to ASP.NET, Second Edition70 CatMenu.aspx (continued) Retrieves product list Dim ProductList As Chapter8.Ch8Products ProductList = New Chapter8.Ch8Products MyProdList.DataSource = ProductList.GetProducts(SubCatID) MyProdList.DataBind() Retrieves individual product information Dim Product As Chapter8.Ch8Products Product = New Chapter8.Ch8Products MyProduct.DataSource = Product.GetProduct(ProdID) MyProduct.DataBind()

71 Introduction to ASP.NET, Second Edition71 CatMenu.aspx (continued)

72 Introduction to ASP.NET, Second Edition72 Summary DataSet can be used to retrieve data from various sources Fill method of DataAdapter populates DataSet using SQL command or stored procedure DataSet consists of DataTables collection DataView retrieves subset of DataSet Can refer to DataTable by name or position within DataTables collection

73 Introduction to ASP.NET, Second Edition73 Summary (continued) DataGrid column types: EditCommandColumn, HyperLinkColumn, ButtonColumn, TemplateColumn EditCommandColumn uses LinkButtons and is used to update database Components allow you to separate business logic from presentation Create global variables in Web.config application configuration file located in root of the Web site


Download ppt "Introduction to ASP.NET, Second Edition2 Chapter Objectives."

Similar presentations


Ads by Google