Intermediate ASP.NET Web Development with C# Instructor: Frank Stepanski Data Sources on the Web Many websites on the web today are just a thin user interface shell on top of sophisticated data-driven code that reads and writes information from a database. Often, website users aren t aware (or don t care) that the information displayed originates from a database. They just want to be able to search your product catalog, place an order or check their payment records, etc. E-commerce web sites, such as Amazon and ebay, use databases to provide customers with product information, recommendations, and wish lists and to store feedback and orders. Portal web sites use databases to store articles and user settings, so users don t need to reset them each time they visit the web site. Benefits of Data-Driven Web Sites: 1. Maintenance: Using a database makes it a lot easier to maintain your data and keep it up-to-date. A website driven by a database usually has fewer web pages than a static web site since a data-driven site has web pages that are primarily templates which are filled on-the-fly. 2. Reusability: Information in databases can easily be backed up and reused elsewhere as required. Compared to static web sites where information can t be easily retrieved from the surrounding HTML layout. 3. Data context: Databases allow you to define relationships and rules for the data in your database. For example, you can create a rule in your database that says if you store some information on a book, you must include an author and an ISBN, which in turn must be valid. This will allow for specific criteria for searches to be made as well as the order. 4. Quality and timeliness of content: Databases are optimized for storage and retrieval of data and nothing else. They allow you to use and update information on a live web site almost in real time something that isn t possible with static web pages. Intermediate ASP.NET Web Development 1 of 23 Author: Frank Stepanski
Of course there are a few downsides, such as development time to write the code to access the database and time to populate the database with the information you require. Likewise it may take some planning initially to accommodate a database in the architecture of a web site. How Does a Web Site Retrieve the Data? Aside from everything else that ASP.NET may be doing in a page, the task of a page communicating with a data source takes a few steps: 1. The page tries to open communication to a database. The code tells the page which database and where it can be found. 2. The page sends a query to the database. Usually, it s a request for some data, but it could also be to update data, to add some new data or even to delete some data. 3. The database sends back some information that the page must then handle accordingly. If it s information for display on the page, it s rendered on the page or it may be confirmation from the database that it updated, inserted or deleted some data as you requested. Introducing ADO.NET So you have a set of pages that needs information and a data source to provide to it. You know that the web server will use the information to provide the page content and influence the way the page displays. You need to tell the page how to retrieve the content from the data source and what to do with it afterward. ADO.NET works directly with the database. ADO.NET gives you the ability to work with a data source through a common set of methods and interfaces (classes), regardless of what type of database it is. This is achieved through a set of data providers. SQL Server has both an ODBC and an OLE DB interface, Microsoft Access has an OLE DB interface and MySQL has an ODBC interface. That s one of the beauties of Intermediate ASP.NET Web Development 2 of 23 Author: Frank Stepanski
ADO.NET, as long as you know which data provider to use, you need to learn only one set of calls and every data provider supports that (Figure 1). Figure 1 List of ADO.NET data providers Almost every data provider has the same objects, methods and properties (apart from a few changes): Connection object: Used to represent the connection between the page and the data source. Command object: Used to represent the query to be sent to the database. Queries are much like functions and may use parameters filled at runtime rather than hard-coded values at compile-time. This reduces the chance of any security issues due to SQL Injection. To represent the parameters in a query, a data provider also includes a Parameter object. DataReader object: Used to represent the data returned by the data source as a forwardonly, use-once result of a query. Intermediate ASP.NET Web Development 3 of 23 Author: Frank Stepanski
DataAdapter object: Used to populate a DataSet with the results of a query. Unlike with the DataReader, once the results are added to a DataSet, you can access it as many times as you like and however you want. A DataSet uses disconnected data on the web server; it never works directly with a data source. Exception object: Used to allow your page to fail gracefully if something unexpected happens and lets you know in detail what went wrong. SQL Server Express SQL Server Express is a free, slimmed down version of the commercial SQL Server database. The main capabilities excluded from the free version are mainly the enterprise features which of course we will not use in this class. Download and install SQL Server 2008 Express, since most webhosts will have that version. If you webhost has an older version (2005), then install that version instead. Note: To install SQL Server 2008 Express and Management Studio Express it is best to use the web platform installer: http://www.microsoft.com/web/downloads/platform.aspx Intermediate ASP.NET Web Development 4 of 23 Author: Frank Stepanski
SQL Server 2008 Express: SQL Server runs as a Windows service. So what is a service? A good example of a service is an antivirus software that runs continuously from when the user restarts a computer to the point that the computer shuts down. A program, on the other hand, is either loaded in memory and running, or not started. A service also has absolutely no user interface. There will be no form to display and no user input to deal with at run time. The only interaction with the process runs either through a separate user interface, which then links in to the service but is a totally separate unit of work. When installing SQL Server Express 2008: Server Configuration - Use the NT Authority\System account name Database Engine Configuration Use Windows authentication mode and add your Add Current User as server administrator SQL Server Management Studio Express Figure 2 - SQL Server Management Studio Express Intermediate ASP.NET Web Development 5 of 23 Author: Frank Stepanski
SSMS is the graphical user interface (GUI) you will use to run all of you queries and build your database solutions. SSMS helps you in the development of database solutions, including creating and modifying components of a database, amending the database itself, and dealing with security issues. It is an easy-to-use and intuitive tool, and before long, you will feel confident in using it to work with SQL Server quickly and efficiently. One of the useful tools within SSMS is the Query Editor. This tool allows program code to be written and executed, from objects, to commands that manipulate data, and even complete tasks such as backing up data. Query Editor is a tool within SSMS that allows you to programmatically build the same actions as dragging and dropping or using wizards. However, using T-SQL within Query Editor can give you more control over certain aspects of certain commands. Note that the name Query Editor comes from the fact that it sends queries to the database using T- SQL. Prebuilt Databases with SQL Server Express Several databases are installed and displayed when SQL Server is first installed Warning: Do not alter these databases! master The master database is at the heart of SQL Server, and if it should become corrupted, there is a very good chance that SQL Server will not work correctly. The master database contains the following crucial information: All logins, or roles, that the user IDs belong to Intermediate ASP.NET Web Development 6 of 23 Author: Frank Stepanski
Every system configuration setting (e.g., data sorting information, security implementation, default language) The names of and information about the databases within the server The location of databases How SQL Server is initialized A list of the available languages System error and warning messages tempdb The tempdb database is as its name suggests a temporary database whose lifetime is the duration of a SQL Server session; once SQL Server stops, the tempdb database is lost. When SQL Server starts up again, the tempdb database is re-created, fresh and new, and ready for use. model Whenever you create a database, it has to be modeled on a predefined set of criteria. For example, if you want all your databases to have a specific initial size or to have a specific set of information, you would place this information into the model database, which acts as a template database for further databases. If you want all databases to have a specific table within them, for example, then you would put this table in the model database. The model database is used as the basis of the tempdb database. msdb msdb is another crucial database within SQL Server, as it provides the necessary information to run jobs to SQL Server Agent. SQL Server Agent is a Windows service in Our Database: Players We will be using a small database throughout this class, so before we do anything we need to create it. Included in this week s files is a.sql file named CreateOurDatabase. This file is a SQL file that contains multiple SQL statements which will create our Players database. Intermediate ASP.NET Web Development 7 of 23 Author: Frank Stepanski
The easiest way to execute this file, is to first open Server Management Studio Express and then click the New Query button. This will open a new tabbed window (Figure 3) where you can copy and paste the entire contents of the CreateOurDatabase.sql file (you can open it up in notepad). Then all you need to do is click the Execute button. Then your Players database (Figure 4) will be created: Figure 3 Execute (CreateOurDatabase.sql) to create and populate the Players database Intermediate ASP.NET Web Development 8 of 23 Author: Frank Stepanski
Figure 4 Players database Note: To view the data in any one of the four tables in our Players database, all you have to do is rightclick a table, and select Edit Top 200 Rows. Intermediate ASP.NET Web Development 9 of 23 Author: Frank Stepanski
Tables: Manufacturer, Player, WhatPlaysWhatFormat and Format Quick Overview of a Relational Database Relational databases store all data as tables. Each of these tables represents a single, distinct subject: an object or an event. For example, a table may contain details of Manufacturing, fish or movies. In general, databases shouldn t store information about several types of objects or events (i.e. fish and movies) --- in the same table, unless the application of the database says otherwise. Every table contains a number of rows (records or tuples). Each row represents exactly one instance of the object event the table holds details about. Figure 5 Manufacturer table in Players database Intermediate ASP.NET Web Development 10 of 23 Author: Frank Stepanski
In Figure 5, each row in the Manufacturer table holds the details for exactly one Manufacturer. These details aren t duplicated or continued elsewhere in the table (i.e. normalization), so when you locate that particular row, it contains all the information you have on that Manufacturer. Every row contains a number of columns, also called attributes or fields. Each column contains a single piece of information indicated by the column s name. Like the name for a table, the name for a column should be as unambiguous as possible. Retrieving information from a table is reasonably simple, because every table must contain a column or a combination of columns that unique identifies any piece of data in the table. This means that it doesn t matter in what order you add rows to the table, because you ll still be able to identify them individually. When you re building a database table, you ll identify this column or combination of columns as the table s primary key. In Figure 5, the ManufacturerID column is the primary key to this table. Every table should have a primary key. It doesn t have to be an ID number (could be a social security number, etc.) but it does have to be unique and a required column for that database. Data-Bound Controls The data bound controls are a series of controls that allow the interactions with data sources to be handled without a single line of code. Instead of having to create Connection and Command objects in code, you can create an instance of the SQLDataSource control (by dragging it from the toolbox onto your page) and point it at a data source. Any data source can be accessed, as long as there s a data provider available for it. This control handles the interaction with the data source for you automatically. Intermediate ASP.NET Web Development 11 of 23 Author: Frank Stepanski
The GridView Control The GridView control can handle direct data source updates as long as the underlying data source object supports these capabilities. This virtually codeless two-way data binding is by far the most notable feature of the new GridView control, but other enhancements are numerous. The GridView control has the ability to define multiple primary key fields, new column types, and style and templating options. The GridView also has an extended eventing model that allows you to handle or cancel events such as inserting, deleting, updating, paging, and more. The ListView Control The ListView control is fully template-based and allows you to control all aspects of the user interface via templates and properties. The ListView control never creates any userinterface layout on its own. Every markup tag that the control emits is entirely under the developer s control, including header, footer, body, item, selected item, and so on. The FormView Control FormView can be considered the templated version of the DetailsView. It renders one record at a time, picked from the associated data source and, optionally, provides paging buttons to navigate between records. Unlike the DetailsView control, FormView doesn t use any internal generation of markup and requires the programmer to define the rendering of each item by using templates. The FormView can support any basic operation its data source provides. The FormView requires you to define everything through templates, not just the things you want to change. The FormView has no built-in rendering engine and is limited to printing out the user-defined templates. Intermediate ASP.NET Web Development 12 of 23 Author: Frank Stepanski
Foundation of the Data Binding Model ASP.NET data binding is built around a few properties that any data-bound control exposes. The actual data binding process starts when the page execution flow executes the method DataBind on the page or a particular control. For a control, performing a data binding action means updating its internal state to reflect the collection of values assigned to its bindable properties. Intermediate ASP.NET Web Development 13 of 23 Author: Frank Stepanski
The DataSource Property The DataSource property lets you specify the data source object the control is linked to. This link is logical and does not result in any overhead or underlying operation until you explicitly choose to bind the data to the control. This operation is triggered by calling the DataBind method. When the DataBind method executes, the control actually loads data from the associated data source, evaluates the data-bound properties (if any), and generates the markup to reflect changes. The DataSourceID Property The DataSourceID property gets or sets the ID of the data source component from which the data-bound control retrieves its data. This property is the point of contact between databound controls and a special family of controls the data source controls. The DataMember Property The DataMember property gets or sets the name of the data collection to extract when data binding to a data source. The DataTextField Property Typically used by list controls, the DataTextField property specifies which property of a data-bound item should be used to define the display text of the nth element in a list control. The DataValueField Property Similar to DataTextField, the DataValueField property specifies which property of a data-bound item should be used to identify the nth element in a list control: The DataKeyField Property The DataKeyField property gets or sets the key field in the specified data source. The property serves the need of some data list controls that allow item selection and master/detail views. Intermediate ASP.NET Web Development 14 of 23 Author: Frank Stepanski
Your First Data-Driven Page: Connecting Locally Drag the SQLDataSource control from the toolbox onto your ASP.NET page. This will allow you to connect to your SQL Server database. Once you configure this control, you can then use other data controls (GridView, DataList, DetailsView, ListView, etc) to render and format the data to the page Note: The Server Name, will be the server name created when you installed SQL Server Express 2008. The server name is displayed each time you open SQL Server Management Studio. Your server name will be different than mine. Intermediate ASP.NET Web Development 15 of 23 Author: Frank Stepanski
The SQLDataSource control creates a connection string for you. The connection string will tell your ASP.NET page information about your database (i.e. database type, the Provider and security information). The creation of this connection string is accomplished by just going through a few wizard-like steps in your control. Intermediate ASP.NET Web Development 16 of 23 Author: Frank Stepanski
SQL DataSource control: Select the Manufacturer table and all fields: Figure 6 Select all fields in the Manufacturers table Intermediate ASP.NET Web Development 17 of 23 Author: Frank Stepanski
SQL DataSource control: Test the query results Figure 7 Testing the SQLDataSource control results After you are finished the wizard has created this for you on your ASP.NET page: <asp:sqldatasource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=HOME-PC\SQLEXPRESS; Initial Catalog=Players; Integrated Security=True" ProviderName="System.Data.SqlClient" SelectCommand="SELECT [ManufacturerID], [ManufacturerName], [ManufacturerCountry], [ManufacturerEmail], [ManufacturerWebsite] FROM [Manufacturer]"></asp:SqlDataSource> Intermediate ASP.NET Web Development 18 of 23 Author: Frank Stepanski
Using a Data Control to Render Your Data Step 1: Take a GridView control and drag it to the page. Step 2: Click on the control and select SQLDataSource1 option Choose Data Source. You ll notice that the column names change to the columns retrieved in the generated SQL statement that was created by the SQLDataSource control. You can edit the names and other properties if you want by clicking edit columns. (Figure 9). Figure 8 Change column headings of GridView control Then you can test our your web page like you normally would do, and see the results: Intermediate ASP.NET Web Development 19 of 23 Author: Frank Stepanski
Figure 9 Viewing your web page data results of GridControl The Players Database on your Web Host When you create a database on your web host (every webhost is different - contact your host support if you are having issues), you will create a username and password for it. Figure 10 Web hosts database setup (mine is GoDaddy, but yours will be different) Note: If your web host allows for "direct access", it will allow you to access your database locally instead of only from your web host account. Intermediate ASP.NET Web Development 20 of 23 Author: Frank Stepanski
Populating the Players Database Online After you create your database online, you will need to execute the CreateOurDatabase_Online.sql to populate your online Players database (Figure 11). Figure 11a Web host SQL Server Admin (yours will be different) Figure 11b Executing the CreateOurDatabase_Online.sql Figure 11c Players database created online Intermediate ASP.NET Web Development 21 of 23 Author: Frank Stepanski
Updating the FirstPage.aspx for Remote Database Now, all you have to do is modify the results from your SQLDataSource control to your online database: <asp:sqldatasource ID="SqlDataSource1" runat="server" connectionstring="data Source=[Database hostname]; User ID=[database name];password=[password]" providername="system.data.sqlclient" SelectCommand="SELECT [ManufacturerID], [ManufacturerName], [ManufacturerCountry], [ManufacturerEmail], [ManufacturerWebsite] FROM [Manufacturer]"> </asp:sqldatasource> Or you can re-run the wizard and enter the new server name and username and password and have the generate the new code for you. Figure 12 Re-creating data source for remote database My version: http://dotnet-tutorials.org/database/lesson1/firstpage-remote.aspx Intermediate ASP.NET Web Development 22 of 23 Author: Frank Stepanski
Using Web.config to Store Database Connections A web.config is the main settings and configuration file for your ASP.NET web application. The file is an XML document that defines configuration information regarding the web application. The web.config file contains information that control module loading, security configuration, database connections, session state configuration, and application language and compilation settings. <?xml version="1.0"?> <configuration> <appsettings/> <connectionstrings> <add name="playersconnectionstring" connectionstring="data Source=[database hostname];initial Catalog=players; User ID=[database name;password=[password]" providername="system.data.sqlclient" /> </connectionstrings> <system.web> <!-- show errors --> <customerrors mode="off"/> <compilation debug="true" targetframework="4.0"/> </system.web> </configuration> Then we reference it in our SQLDataSource control like: <asp:sqldatasource ID="SqlDataSource1" runat="server" ConnectionString ="<%$ ConnectionStrings:playersConnectionString %>" SelectCommand ="SELECT [ManufacturerID], [ManufacturerName], [ManufacturerCountry], [ManufacturerWebsite], [ManufacturerEmail] FROM [Manufacturer]"> </asp:sqldatasource> My version: http://dotnet-tutorials.org/database/lesson1/usingwebconfig.aspx Copyrighted 2014 Frank Stepanski Used with Permission :: eclasses.org Lessons, files and content of these classes cannot be reproduced and/or published without the express written consent of the author. Intermediate ASP.NET Web Development 23 of 23 Author: Frank Stepanski