WEB325 Building Data-Driven Web Sites in ASP.NET 2.0 Rob Howard Telligent Corporation.

Slides:



Advertisements
Similar presentations
17. Data Access ADO.Net Architecture New Features of ADO.NET
Advertisements

Internetteknologi (ITNET2) Presentation 21: ASP.NET Advanced.
Chapter 10 Database Applications Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
User Controls, Master Pages, GridView. Content User Controls Styles, Themes, Master Pages Working with Data GridView Muzaffer DOĞAN - Anadolu University2.
Chapter 9 Customizing Data with Web Controls. ASP.NET 2.0, Third Edition2.
Unit 5: Building Presentation Layer Applications with ASP.NET 2.0.
ASP.NET Data Binding. Slide 2 Lecture Overview Understanding the ASP.NET data binding model.
1 Chapter 12 Working With Access 2000 on the Internet.
Chapter 12: ADO.NET and ASP.NET Programming with Microsoft Visual Basic.NET, Second Edition.
ASP.NET Database Connectivity I. 2 © UW Business School, University of Washington 2004 Outline Database Concepts SQL ASP.NET Database Connectivity.
Performed by:Gidi Getter Svetlana Klinovsky Supervised by:Viktor Kulikov 08/03/2009.
ASP.NET Programming with C# and SQL Server First Edition
Chapter 14: Advanced Topics: DBMS, SQL, and ASP.NET
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
From VS C# 2010 Programming, John Allwork 1 VS2010 C# Programming - DB intro 1 Topics – Database Relational - linked tables SQL ADO.NET objects Referencing.
Philip Wolfe Senior Consultant Sogeti Session 3 - Leveraging Data in ASP.NET 2.0 (Level 200)
Chapter 8 Binding Data to Web Controls. ASP.NET 2.0, Third Edition2.
CHAPTER 9 DATABASE MANAGEMENT © Prepared By: Razif Razali.
Chapter 9 Using the SqlDataSource Control. References aspx.
Chapter 11 Introduction to Database Processing. Class 11: Database Processing Use a Visual Studio Wizard to establish a database connection used to load.
Programming with Visual Basic.NET An Object-Oriented Approach  Chapter 8 Introduction to Database Processing.
Chapter 10 Managing Data with ASP.NET. ASP.NET 2.0, Third Edition2.
Overview of Previous Lesson(s) Over View  ASP.NET Pages  Modular in nature and divided into the core sections  Page directives  Code Section  Page.
ASP.NET Part 4 Instructor: Charles Moen CSCI/CINF 4230.
10-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
ASP.Net Web Applications. Characteristics of a typical data driven web application Web Server HTML Graphics Active-X Java Applets HTTP Request ADO / JDBC.
Developing Web Applications Using Microsoft ® Visual Studio ® 2008.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
CIS 375—Web App Dev II ASP.NET 10 Database 2. 2 Introduction to Server-Side Data Server-side data access is unique in that Web pages are basically ___________.
Needs for Accessing Database To make your web site more dynamic and maintainable, you can display information on your web pages that are retrieved from.
1 Data Bound Controls II Chapter Objectives You will be able to Use a Data Source control to get data from a SQL database and make it available.
Malek Kemmou Technology Architect, Application Platform Microsoft Middle East and Africa Using Visual Studio 2005 to Build Data- Driven.
Ventsislav Popov Crossroad Ltd.. 1. ASP.NET Data Source Controls  SqlDataSource  EntityDataSource  ObjectDataSource 2. Entity Data Model and ADO.NET.
Delivering Excellence in Software Engineering ® EPAM Systems. All rights reserved. Data Binding in ASP.NET.
CSCI 6962: Server-side Design and Programming Database Manipulation in ASP.
Chapter 8 Working With Databases in ASP.NET. Listing 8.1 – ShowListControls Uses The SqlDataSource control for estabishing database connectivity and.
ASP.NET OPTIMIZATION. Why Optimize? $$$ Whether you build applications for customers or not, enhanced applications save money.
Data Access in ASP.NET 2.0 Bradley Millington Program Manager Web Platform and Tools.
Windows Forms in Visual Studio 2005 Mike Pelton Systems Engineer Microsoft Ltd
Name Microsoft Student Partner Overview of the Visual Studio 2005 Express Products.
State Management. Agenda View state Application cache Session state ProfilesCookies.
Data-Driven - 1 © Minder Chen, Building Data-Driven Web Sites in ASP.NET 2.0.
TRAINING SESSIONS.NET Controls.  Standard Controls  Label  Textbox  Checkbox  Button, Image Button, Image control  Radio Button  Literal  Hyperlink.
11 The Repeater Control. 22 Objectives You will be able to use a Repeater Control to display data obtained with a SQL query with custom formatting.
Reference: “ASP.NET 2.0 Illustrated” by Alex Homer and Dave Sussman. -ch3 illustrated book
Ventsislav Popov Crossroad Ltd.. 1. ASP.NET Data Source Controls  SqlDataSource  EntityDataSource  ObjectDataSource 2. Entity Data Model and ADO.NET.
Making the Most of WinForms 2.0 Data Binding Rajiv Sodhi Microsoft India.
DEV383 The ADO.NET DataSet and You Jackie Goldstein General Manager Renaissance Computer Systems
BlackBerry Applications using Microsoft Visual Studio and Database Handling.
How to Build an IT Portal with Oracle Application Server Allan L Haensgen Senior Principal Instructor Oracle Corporation Session id:
State Management. Agenda View state Application cache Session state ProfilesCookies.
Module 3: Working with Local Data. Overview Using DataSets Using XML Using SQL Server CE.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Preface IIntroduction Objectives I-2 Course Overview I-3 1Oracle Application Development Framework Objectives 1-2 J2EE Platform 1-3 Benefits of the J2EE.
1 CS 3870/CS 5870: Note07 Prog 4. Master Pages Creating a master page based on another master page MainMasterPage –For all Progs and Tests Prog4MasterPage.
A Lap Around New Enhancements for Web Developers in Visual Studio 2005 Alexander Holy Developer Evangelist, Microsoft EMEA
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Address Book Application Introducing Database Programming.
DEV414 Black-belt ASP.NET Tips And Tricks For Your ASP.NET Applications Rob Howard Program Manager Web Platform and Tools Team.
Module 10: Data Access in ASP.NET. Overview Overview of the ASP.NET Data Access What is Data Access List of Data Source Control What is Data Bound How.
DAT 390 Advanced ADO.NET Programming Techniques Jackie Goldstein Renaissance Computer Systems
Displaying and Updating Data
Introduction to Database Processing with ADO.NET
PROG Advanced Web Apps 5/23/2018 Notes on ADO.NET (1) Wendi Jollymore, ACES.
Active Data Objects Binding ASP.NET Controls to Data
Listing 9.1 ShowLocalConnection.aspx
Web Development Using ASP .NET
Chapter 10 Accessing Database Files
Visual Studio + SQL Server Is Better
Active Data Objects Binding ASP.NET Controls to Data
Windows Forms in Visual Studio 2005: An in-depth look at key features
Presentation transcript:

WEB325 Building Data-Driven Web Sites in ASP.NET 2.0 Rob Howard Telligent Corporation

Contact and Slides Rob Howard Software Development Company Builds Community Server (communityserver.org) Download Slides & Demos Will be posted ASAP

Review: ASP.NET 1.X ASP.NET 1.X Introduced data controls Introduced data binding concepts Working with data in ASP.NET 1.X Easy and simple Too much code still required though ASP.NET 2.0 Specifically addresses common scenarios Makes working with data even easier

Agenda Safer connection string storage Data binding gets easier Declarative data binding Working with the new data controls Caching data

Connection String Storage Persistence and declarative referencing Stored in *.config Avoid hard-coding within pages/code Can be optionally encrypted Built-in design time support Promote use for best practices Enable optional encrypting of values in config Admin Support MMC Admin Tool Support Configuration API Support

Config Connection Strings <connectionStrings> <add name="pubs“ ProviderName=“…” <add name="pubs“ ProviderName=“…” connectionString=“…” /> connectionString=“…” /></connectionStrings> ” SelectCommand=“select au_id from authors” runat=“server”/> ” SelectCommand=“select au_id from authors” runat=“server”/> Web.config: Page.aspx: Dim connstr As String = ConfigurationSettings.ConnectionStrings(“pubs”) Code.vb:

Connection Strings

Data Binding Gets Easier Expressions are cleaner Support hierarchical (XML) data binding

Declarative Data Binding Controls bound at appropriate time Wire-up done through properties Page lifecycle knowledge not required NameDescription SqlDataSourceConnects data-binding controls to SQL databases AccessDataSourceConnects data-binding controls to Access databases XmlDataSourceConnects data-binding controls to XML data ObjectDataSourceConnects data-binding controls to data components SiteMapDataSourceConnects site navigation controls to site map data

SqlDataSource Data binding to SQL Database Microsoft SQL Server, Oracle, DB2, etc. Two-way data binding supported SelectCommand InsertCommand, UpdateCommand, and DeleteCommand Optional caching of query results Parameterized operation

Using SqlDataSource <asp:SqlDataSource ID="Titles" ConnectionString=" " RunAt="server“ SelectCommand="select title_id, title, price from titles" /> ID="Titles" ConnectionString=" " RunAt="server“ SelectCommand="select title_id, title, price from titles" /><asp:DataGridDataSourceID="Titles" RunAt="server" />

SqlDataSource Properties NameDescription ConnectionStringConnection string used to connect to data source SelectCommandCommand used to perform queries InsertCommandCommand used to perform inserts UpdateCommandCommand used to perform updates DeleteCommandCommand used to perform deletes DataSourceModeSpecifies whether DataSet or DataReader is used (default = DataSet) ProviderNameSpecifies provider (default = SQL Server.NET provider)

SQL Data Binding

SqlDataSource and Caching Support declarative caching NameDescription EnableCachingSpecifies whether caching is enabled (default = false) CacheDurationLength of time in seconds results should be cached CacheExpirationPolicySpecifies whether cache duration is sliding or absolute CacheKeyDependencyCreates dependency on specified cache key SqlCacheDependencyCreates dependency on specified database entity

<asp:SqlDataSourceID="Countries"RunAt="server" SelectCommand="select..." EnableCaching="true" CacheDuration="60" /> <asp:DropDownListID="MyDropDownList"DataSourceID="Countries“DataTextField="country"AutoPostBack="true" RunAt="server" /> Caching Query Results

Parameterized Commands Parameter properties Parameterized database commands Example: Get value for WHERE clause in SelectCommand from query string parameter or item selected in drop-down list Example: Get value for WHERE clause in DeleteCommand from GridView

Parameters Properties NameDescription SelectParametersSpecifies parameters for SelectCommand InsertParameters UpdateParameters DeleteParameters FilterParametersSpecifies parameters for FilterExpression Specifies parameters for InsertCommand Specifies parameters for UpdateCommand Specifies parameters for DeleteCommand

Parameter Types NameDescription ControlParameterBinds a replaceable parameter to a control property CookieParameterBinds a replaceable parameter to a cookie value FormParameterBinds a replaceable parameter to a form field ProfileParameterBinds a replaceable parameter to a profile property QueryStringParameterBinds a replaceable parameter to a query string parameter ParameterBinds a replaceable parameter to a data field SessionParameterBinds a replaceable parameter to a session variable

Using ControlParameter <asp:SqlDataSource ID="Countries" RunAt="server" SelectCommand="select distinct..." /> <asp:SqlDataSource ID="Customers" RunAt="server" SelectCommand="select * from customers where <SelectParameters> <asp:ControlParameter Name="Country" <asp:ControlParameter Name="Country"ControlID="MyDropDownList" PropertyName="SelectedValue" /> </SelectParameters></asp:SqlDataSource><asp:DropDownList ID="MyDropDownList" DataSourceID="Countries" DataTextField="country" AutoPostBack="true" RunAt="server" /> DataTextField="country" AutoPostBack="true" RunAt="server" />

Calling Stored Procedures <asp:SqlDataSource ID="Countries" RunAt="server" ConnectionString="server=localhost;database=northwind;..." ConnectionString="server=localhost;database=northwind;..." SelectCommand="proc_GetCountries" /> SelectCommand="proc_GetCountries" /> <asp:SqlDataSource ID="Customers" RunAt="server" ConnectionString="server=localhost;database=northwind;..." ConnectionString="server=localhost;database=northwind;..." SelectCommand="proc_GetCustomers"> SelectCommand="proc_GetCustomers"> <asp:ControlParameter Name="Country" ControlID="MyDropDownList" <asp:ControlParameter Name="Country" ControlID="MyDropDownList" PropertyName="SelectedValue" /> PropertyName="SelectedValue" /> </asp:SqlDataSource> <asp:DropDownList ID="MyDropDownList" DataSourceID="Countries" DataTextField="country" AutoPostBack="true" RunAt="server" /> DataTextField="country" AutoPostBack="true" RunAt="server" /> CREATE PROCEDURE nvarchar (32) AS SELECT * FROM Customers SELECT * FROM Customers WHERE Country WHERE Country CREATE PROCEDURE nvarchar (32) AS SELECT * FROM Customers SELECT * FROM Customers WHERE Country WHERE Country CREATE PROCEDURE proc_GetCountries AS SELECT DISTINCT Country SELECT DISTINCT Country FROM Customers FROM Customers ORDER BY Country ORDER BY CountryGO CREATE PROCEDURE proc_GetCountries AS SELECT DISTINCT Country SELECT DISTINCT Country FROM Customers FROM Customers ORDER BY Country ORDER BY CountryGO

SqlDataSource

Data Source Capabilities Common data operations get easier Sorting and paging Selecting, updating, inserting, deleting Page developer Sets properties to enable operations Ex., UpdateCommand “Smart” data-bound controls Use these capabilities directly Ex.,, Ex.,,

Sorting, Paging, Updating

Data Source Paging Previous demo does paging in UI layer SqlDataSource returns all data rows Performs paging by rendering subset of rows Paging supported on data source interface Select (int startRowIndex, int maxRows) Requires user-defined procedure or custom code Data-bound controls Don’t need to page in the UI layer Useful (and required) for large amounts of data

Updates, Inserts, Deletes GridView Extracts values from input controls Keys from viewstate (DataKeyNames) Dictionaries passed to data source operation Update: Keys, Values, OldValues Delete: Keys, OldValues Data source applies parameters to command Relies on naming convention for parameters Keys, OldValues formatted with “original_” prefix OldValuesParameterFormatString defines prefix

Programmability Data source events Enable custom processing Use event to: Manipulate command and parameters Cancel operations Handle errors Retrieve return values and output params Rows affected Data-bound controls expose similar events

Data Source Events Sub MySource_Selecting(ByVal sender As Object, ByVal e As SqlDataSourceCommandEventArgs) Dim cmd As System.Data.SqlClient.SqlCommand = e.Command Dim cmd As System.Data.SqlClient.SqlCommand = e.Command cmd.Parameters(“UserId”).Value = User.Identity.Name cmd.Parameters(“UserId”).Value = User.Identity.Name End Sub Page.aspx.vb Page.aspx

ObjectDataSource Most applications encapsulate data logic Best practice and simplifies maintenance Embedding SQL code is not recommended ObjectDataSource Bind to custom business objects Visual Studio data components Parallels SqlDataSource in object model

Web Page DataSourceID = ObjectDataSource1 ObjectDataSourceObjectDataSource NorthwindDatabase OrdersComponent OrderItemsComponent CompaniesComponent <asp:ObjectDataSource ID = ObjectDataSource1 TypeName = OrdersComponent SelectMethod = GetOrders UpdateMethod = UpdateOrder DeleteMethod = DeleteOrder Returns IEnumerable of Orders Order.OrderID Order.OrderID Order.OrderName Order.OrderName Order.OrderDate Order.OrderDate

ObjectDataSource Select method can return any Object IEnumerable list Collection or array GetProducts() -> ProductCollection GetProductsDataSet() -> DataSet GetProduct (int productId) -> Product

ObjectDataSource Update, Insert, Delete methods Take individual fields or data item object For automatic updates/inserts/deletes Property or parameter names must match selected fields for GridView/DetailsView UpdateProduct (int id, String name, double price) UpdateProduct (Product p) // p.Name, p.Price, etc. DeleteProduct (int id)

Key Properties NameDescription TypeNameType name of data component SelectMethodMethod called on data component to perform queries InsertMethod UpdateMethod DeleteMethod EnableCachingSpecifies whether caching is enabled (default = false) Method called on data component to perform inserts Method called on data component to perform updates Method called on data component to perform deletes

Key Properties (cont’d) NameDescription InsertParametersSpecifies parameters for InsertMethod UpdateParametersSpecifies parameters for UpdateMethod DeleteParametersSpecifies parameters for DeleteMethod SelectParametersSpecifies parameters for SelectMethod CacheDurationLength of time in seconds data should be cached SqlCacheDependencyCreates dependency on specified database entity

Initialization and Clean-Up Data operation methods Can identify static methods Can identify instance methods If instance methods are used: New class instance on each call Must have public default constructor ObjectCreated and ObjectDisposing Events to initialize or clean-up

Using ObjectDataSource

What about DataSets? Works for both Web and client applications Created from DB schema Dynamic SQL Stored Procedures Exposes methods to “Fill” and “Fetch” Auto-generated Insert/Update/Delete “A middle tier data access layer for Web and client”

What about DataSets? Supports partial classes for custom logic Built in support for common tasks Select, Update, Insert, Delete Batch updates, Conflict resolution* Works with Web services and remoting DataTable can be standalone (XmlSerializable, ReadXml) Exposes “GetBy” for stateless calls Can be used with custom base classes

GridView Control Enhanced DataGrid control Renders sets of records as HTML tables Built-in sorting, paging, selecting, updating, and deleting support Supports rich assortment of field types, including CheckBoxFields Declared in element Highly customizable UI

GridView Example <asp:SqlDataSourceID="Employees"RunAt="server" SelectCommand="select lastname,.../> <asp:GridViewDataSourceID="Employees"Width="100%" RunAt="server" />

Rendered GridView

GridView Field Types NameDescription BoundFieldRenders columns of text from fields in data source ButtonFieldRenders columns of buttons (push button, image, or link) CheckBoxFieldRenders Booleans as check boxes HyperLinkFieldRenders columns of hyperlinks TemplateFieldRenders columns using HTML templates CommandFieldRenders controls for selecting and editing GridView data ImageFieldRenders columns of images from URL text

Specifying Field Types <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString="server=localhost;database=northwind;..." ConnectionString="server=localhost;database=northwind;..." SelectCommand="select photo, lastname, firstname, title from employees" /> SelectCommand="select photo, lastname, firstname, title from employees" /> <asp:GridView DataSourceID="Employees" Width="100%" RunAt="server" AutoGenerateColumns="false" > AutoGenerateColumns="false" > </asp:GridView>

Rendered Output

DetailsView Control Renders individual records Pair with GridView for master-detail views Or use without GridView to display individual records Built-in paging, inserting, updating, deleting Uses same field types as GridView Declared in element Highly customizable UI

DetailsView Example <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString="server=localhost;database=northwind;..." ConnectionString="server=localhost;database=northwind;..." SelectCommand="select employeeid, photo,... from employees" /> SelectCommand="select employeeid, photo,... from employees" /> <asp:DetailsView DataSourceID="Employees" RunAt="server" AllowPaging="true" AutoGenerateRows="false" AllowPaging="true" AutoGenerateRows="false" PagerSettings-Mode="NextPreviousFirstLast"> PagerSettings-Mode="NextPreviousFirstLast"> </asp:DetailsView>

Rendered Output

Master-Detail

SQL Cache Invalidation New cache dependency type Embodied in SqlCacheDependency class Configured through configuration section Links cached items to database entities ASP.NET application cache ASP.NET output cache Compatible with SQL Server 7, 2000, 2005

Using SqlCacheDependency with the Application Cache Cache.Insert ("Products", products, new SqlCacheDependency ("Northwind", "Products"); new SqlCacheDependency ("Northwind", "Products"); Database name Table name

Using SqlCacheDependency with the Output Cache OutputCache Duration="60" VaryByParam="None" SqlDependency="Northwind:Products" %> SqlDependency="Northwind:Products" %> Database name Table name

Using SqlCacheDependency with SqlDataSource <asp:SqlDataSource ID="Countries" RunAt="server" ConnectionString="server=localhost;database=northwind;..." ConnectionString="server=localhost;database=northwind;..." SelectCommand="select distinct country from customers order by country" SelectCommand="select distinct country from customers order by country" EnableCaching="true" CacheDuration="60000" EnableCaching="true" CacheDuration="60000" SqlCacheDependency="Northwind:Customers" /> <asp:DropDownList ID="MyDropDownList" DataSourceID="Countries" DataTextField="country" AutoPostBack="true" RunAt="server" /> DataTextField="country" AutoPostBack="true" RunAt="server" /> Database name Table name

Cache Configuration <cache> Enable/disable application cache Enable/disable item expiration and more,, Enable/disable output caching Enable/disable disk-based persistence Set maximum size per app and more <sqlCacheDependency>

SQL Cache Invalidation

Review Simplified data binding Data source controls Data controls GridView and DetailsView controls Editing with GridView and DetailsView Caching SQL Cache Invalidation Cache configuration

Your Feedback is Important! Please Fill Out a Survey for This Session on CommNet

© 2005 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.