More ASP.NET Database In a properly organized application, your data access code is never embedded directly in the code-behind for a page. Instead, it’s.

Slides:



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

Database Connections with ASP.Net
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
A Guide to SQL, Seventh Edition. Objectives Understand the concepts and terminology associated with relational databases Create and run SQL commands in.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Chapter 14: Advanced Topics: DBMS, SQL, and ASP.NET
A Guide to MySQL 3. 2 Objectives Start MySQL and learn how to use the MySQL Reference Manual Create a database Change (activate) a database Create tables.
Managing Concurrency in Web Applications. DBI 2007 HUJI-CS 2 Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses.
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
Introduction to the Enterprise Library. Sounds familiar? Writing a component to encapsulate data access Building a component that allows you to log errors.
CHAPTER 9 DATABASE MANAGEMENT © Prepared By: Razif Razali.
Programming with Visual Basic.NET An Object-Oriented Approach  Chapter 8 Introduction to Database Processing.
Cursor and Exception Handling By Nidhi Bhatnagar.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
Concepts of Database Management, Fifth Edition Chapter 4: The Relational Model 3: Advanced Topics.
11 Updating a Database Table Textbook Chapter 14.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
ADO.NET A2 Teacher Up skilling LECTURE 3. What’s to come today? ADO.NET What is ADO.NET? ADO.NET Objects SqlConnection SqlCommand SqlDataReader DataSet.
1 ASP.NET ASP.NET Rina Zviel-Girshin Lecture 4. 2 Overview Data Binding Data Providers Data Connection Data Manipulations.
PHP meets MySQL.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
PART 1 CREATING THE PRODUCT CATALOG. ROADMAP FOR THIS CHAPTER To implement the departments list, you’ll start with the database and make your way to the.
Stored Procedures, Transactions, and Error-Handling
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.
Neal Stublen Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating.
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.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
Programming using C# Joins SQL Injection Stored Procedures
Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
PHP MySQL Introduction. MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database.
NMED 3850 A Advanced Online Design January 12, 2010 V. Mahadevan.
Access 2013 Microsoft Access 2013 is a database application that is ideal for gathering and understanding data that’s been collected on just about anything.
1cs Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses by multiple users Concurrent accesses intersect.
Module 3: Working with Components. Overview An Introduction to Key.NET Framework Development Technologies Creating a Simple.NET Framework Component Creating.
11 Using ADO.NET II Textbook Chapter Getting Started Last class we started a simple example of using ADO.NET operations to access the Addresses.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
JDBC Java and Databases. RHS – SOC 2 JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
ASP.NET Rina Zviel-Girshin Lecture 5
Views Lesson 7.
ADO.NET Data Access. Page  2 SQL  When we interact with the datasource through ADO.NET we use the SQL language to retrieve,modify,update information.
Christopher M. Pascucci.NET Programming: Databases & ADO.NET.
M1G Introduction to Database Development 5. Doing more with queries.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Transactions and Locks A Quick Reference and Summary BIT 275.
DT228/3 Web Development Databases. Querying a database: Partial info Search engines, on-line catalogues often need to allow user to search a database.
Creating competitive advantage Copyright © 2003 Enterprise Java Beans Presenter: Wickramanayake HMKSK Version:0.1 Last Updated:
1 Avoiding Hacker Attacks. 2 Objectives You will be able to Avoid certain hacker attacks and crashes due to bad inputs from users.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
Task #1 Create a relational database on computers in computer classroom 308, using MySQL server and any client. Create the same database, using MS Access.
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
ADO.NET FUNDAMENTALS BEGINNING ASP.NET 3.5 IN C#.
1 Database Programming with ADO.NET Kashef Mughal.
1.NET Web Forms Applications: Main Form © 2002 by Jerry Post.
Manipulating Data Lesson 3. Objectives Queries The SELECT query to retrieve or extract data from one table, how to retrieve or extract data by using.
1 A Very Brief Introduction to Relational Databases.
1 Low Level ADO.NET Operations II Microsoft Visual C# 2008 Step by Step Chapter 25.
SQL Triggers, Functions & Stored Procedures Programming Operations.
SQL IMPLEMENTATION & ADMINISTRATION Indexing & Views.
ASP.NET Programming with C# and SQL Server First Edition
Fundamentals of DBMS Notes-1.
Trigger used in PosgreSQL
COMP 430 Intro. to Database Systems
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Developing a Model-View-Controller Component for Joomla Part 3
E-commerce Applications Development
Manipulating Data Lesson 3.
M S COLLEGE OF ART’S, COMM., SCI. & BMS Advance Web Programming
Presentation transcript:

More ASP.NET Database In a properly organized application, your data access code is never embedded directly in the code-behind for a page. Instead, it’s separated into a dedicated data component. Create a simple data access class, adding a separate method for each data task you need to perform. Disconnected data—the ADO.NET features that revolve around the DataSet and allow you to interact with data long after you’ve closed the connection to the datasource. The DataSet isn’t required in ASP.NET pages. However, it gives you more flexibility for navigating, filtering, and sorting your data.

Building a Data Access Component In professional applications, database code is not embedded directly in the client but encapsulated in a dedicated class. To perform a database operation, the client creates an instance of this class and calls the appropriate method.

Open and close connections quickly: Open the database connection in every method call, and close it before the method ends. Connections should never be held open between client requests, and the client should have no control over how connections are acquired or when they are released. If the client does have this ability, it introduces the possibility that a connection might not be closed as quickly as possible or might be inadvertently left open, which hampers scalability.

Implement error handling: Use error handling to make sure the connection is closed even if the SQL command generates an exception. Remember, connections are a finite resource, and using them for even a few extra seconds can have a major overall effect on performance.

Follow stateless design practices: Accept all the information needed for a method in its parameters, and return all the retrieved data through the return value. If you create a class that maintains state, it cannot be easily implemented as a web service or used in a load-balancing scenario. Also, if the database component is hosted out of the process, each method call has a measurable overhead, and using multiple calls to set properties will take much longer than invoking a single method with all the information as parameters.

Don’t let the client specify connection string information: This poses security risks, raises the possibility that an out-of-date client will fail, and compromises the ability of connection pooling, which requires matching connection strings.

Don’t connect with the client’s user ID: Introducing any variability into the connection string will thwart connection pooling. Instead, rely on rolebased security or a ticket- based system whereby you authenticate users and prevent them from attempting to perform a restricted operation. This model is also faster than trying to perform a database query under an invalid security account and waiting for an error.

Don’t let the client use wide- open queries: Every query should judiciously select only the columns it needs. Also, you should restrict the results with a WHERE clause whenever possible. A good, straightforward design for a database component uses a separate class for every database table (or logically related group of tables). The common database access methods such as inserting, deleting, and modifying a record are all wrapped in separate stateless methods. Finally, every database call uses a dedicated stored procedure.

The following example demonstrates a simple database component. Rather than placing the database code in the web page, it follows a much better design practice of separating the code into a distinct class that can be used in multiple pages. This class can then be compiled as part of a separate component if needed. Additionally, the connection string is retrieved from the section of the web.config file, rather than being hard-coded. The data component actually consists of two classes—a data package class that wraps a single record of information and a database utility class that performs the actual database operations with ADO.NET code.

The Data Package To make it easier to shuffle information to the Northwind database and back, it makes sense to create an EmployeeDetails class that provides all the fields as public properties. Here’s the full code for this class: public class EmployeeDetails { private int employeeID; public int EmployeeID { get {return employeeID;} set {employeeID = value;} } private string firstName;

The Data Package public string FirstName { get {return firstName;} set {firstName = value;} } private string lastName; public string LastName { get {return lastName;} set {lastName = value;} }

The Data Package private string titleOfCourtesy; public string TitleOfCourtesy { get {return titleOfCourtesy;} set {titleOfCourtesy = value;} } public EmployeeDetails(int employeeID, string firstName, string lastName, string titleOfCourtesy) { this.employeeID = employeeID; this.firstName = firstName; this.lastName = lastName; this.titleOfCourtesy = titleOfCourtesy; }

The Stored Procedures Before you can start coding the data access logic, you need to make sure you have the set of stored procedures you need in order to retrieve, insert, and update information. The following code shows the five stored procedures that are needed:

The Stored Procedures CREATE PROCEDURE int varchar(25) AS INSERT INTO Employees (TitleOfCourtesy, LastName, FirstName, GETDATE()); = GO

The Stored Procedures CREATE PROCEDURE int AS DELETE FROM Employees WHERE EmployeeID GO

The Stored Procedures CREATE PROCEDURE varchar(10) AS UPDATE Employees SET TitleOfCourtesy LastName FirstName WHERE EmployeeID GO

The Stored Procedures CREATE PROCEDURE GetAllEmployees AS SELECT EmployeeID, FirstName, LastName, TitleOfCourtesy FROM Employees GO

The Stored Procedures CREATE PROCEDURE CountEmployees AS SELECT COUNT(EmployeeID) FROM Employees GO

The Stored Procedures CREATE PROCEDURE int AS SELECT FirstName, LastName, TitleOfCourtesy FROM Employees WHERE EmployeeID GO

The Data Utility Class Finally, you need the utility class that performs the actual database operations. This class uses the stored procedures that were shown previously. In this example, the data utility class is named EmployeeDB. It encapsulates all the data access code and database-specific details.

The Data Utility Class public class EmployeeDB { private string connectionString; public EmployeeDB() { // Get default connection string. connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString; } public EmployeeDB(string connectionStringName) { // Get the specified connection string. connectionString = WebConfigurationManager.ConnectionStrings[ "connectionStringName"].ConnectionString; }

The Data Utility Class public int InsertEmployee(EmployeeDetails emp) {... } public void DeleteEmployee(int employeeID) {... } public void UpdateEmployee(EmployeeDetails emp) {... } public EmployeeDetails GetEmployee() {... } public EmployeeDetails[] GetEmployees() {... } public int CountEmployees() {... } }

The Data Utility Class Here’s the code for inserting a record: public int InsertEmployee(EmployeeDetails emp) { SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("InsertEmployee", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlDbType.NVarChar, 10)); = emp.FirstName; cmd.Parameters.Add(new SqlDbType.NVarChar, 20)); = emp.LastName; cmd.Parameters.Add(new SqlDbType.NVarChar, 25)); = emp.TitleOfCourtesy;

The Data Utility Class cmd.Parameters.Add(new SqlDbType.Int, 4)); = ParameterDirection.Output; try { con.Open(); cmd.ExecuteNonQuery(); return } catch (SqlException err) { // Replace the error with something less specific. // You could also log the error now. throw new ApplicationException("Data error."); } finally { con.Close(); }

The Data Utility Class The method accepts data using the EmployeeDetails package. Any errors are caught, and the sensitive internal details are not returned to the web-page code. This prevents the web page from providing information that could lead to possible exploits. This would also be an ideal place to call another method in a logging component to report the full information in an event log or another database.

The Data Utility Class The GetEmployee() and GetEmployees() methods return the data using the EmployeeDetails package: public EmployeeDetails GetEmployee(int employeeID) { SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("GetEmployee", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlDbType.Int, 4)); = employeeID; try { con.Open(); SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow);

The Data Utility Class // Get the first row. reader.Read(); EmployeeDetails emp = new EmployeeDetails( (int)reader["EmployeeID"], (string)reader["FirstName"], (string)reader["LastName"], (string)reader["TitleOfCourtesy"]); reader.Close(); return emp; } catch (SqlException err) { throw new ApplicationException("Data error."); } finally { con.Close(); }

The Data Utility Class public List GetEmployees() { SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("GetAllEmployees", con); cmd.CommandType = CommandType.StoredProcedure; // Create a collection for all the employee records. List employees = new List (); try { con.Open(); SqlDataReader reader = cmd.ExecuteReader();

The Data Utility Class while (reader.Read()) { EmployeeDetails emp = new EmployeeDetails( (int)reader["EmployeeID"], (string)reader["FirstName"], (string)reader["LastName"], (string)reader["TitleOfCourtesy"]); employees.Add(emp); } reader.Close(); return employees; } catch (SqlException err) { throw new ApplicationException("Data error."); } finally { con.Close(); }

Concurrency Strategies In any multiuser application, including web applications, there’s the potential that more than oneuser will perform overlapping queries and updates. This can lead to a potentially confusing situation where two users, who are both in possession of the current state for a row, attempt to commit divergent updates. The first user’s update will always succeed. The success or failure of the second update is determined by your concurrency strategy.

Concurrency Strategies There are several broad approaches to concurrency management. The most important thing to understand is that you determine your concurrency strategy by the way you write your UPDATE commands (particularly the way you shape the WHERE clause). Here are the most common examples: Last-in-wins updating: This is a less restrictive form of concurrency control that always commits the update (unless the original row has been deleted). Every time an update is committed, all the values are applied. Last-in-wins makes sense if data collisions are rare. For example, you can safely use this approach if there is only one person responsible for updating a given group of records. Usually, you implement a last-in-wins by writing a WHERE clause that matches the record to update based on its primary key. UPDATE Employees SET... WHERE

Concurrency Strategies Match-all updating: To implement this strategy, you add a WHERE clause that tries to match the current values of every field in the record to your UPDATE statement. That way, if even a single field has been modified, the record won’t be matched and the change will not succeed. One problem with this approach is that compatible changes are not allowed. For example, if two users are attempting to modify different parts of the same record, the second user’s change will be rejected, even though it doesn’t conflict. Another, more significant, problem with the match-all updating strategy is that it leads to large, inefficient SQL statements. You can implement the same strategy more effectively with timestamps. UPDATE Employees SET... WHERE AND AND

Concurrency Strategies Timestamp-based updating: Most database systems support a timestamp column, which the data source updates automatically every time a change is performed. You do not need to modify the timestamp column manually. However, you can examine it for changes and thereby determine if another user has recently applied an update. If you write an UPDATE statement with a WHERE clause that incorporates the primary key and the current timestamp, you’re guaranteed to update the record only if it hasn’t been modified, just like with match-all updating. UPDATE Employees SET... WHERE AND

Concurrency Strategies Changed-value updating: This approach attempts to apply just the changed values in an UPDATE command, thereby allowing two users to make changes at the same time if these changes are to different fields. The problem with this approach is it can be complex, because you need to keep track of what values have changed (in which case they should be incorporated in the WHERE clause) and what values haven’t.

Testing the Component Now that you've created the data component, you just need a simple test page to try it out. As with any other component, you must begin by adding a reference to the component assembly. Then you can import the namespace it uses to make it easier to implement the EmployeeDetails and EmployeeDB classes. The only step that remains is to write the code that interacts with the classes. In this example, the code takes place in the Page.Load event handler. First, the code retrieves and writes the number and the list of employees by using a private WriteEmployeesList() method that translates the details to HTML. Next, the code adds a record and lists the table content again. Finally, the code deletes the added record and shows the content of the Employees table one more time.

Testing the Component public partial class ComponentTest : System.Web.UI.Page { // Create the database component so it's available anywhere on the page. private EmployeeDB db = new EmployeeDB(); protected void Page_Load(object sender, System.EventArgs e) { WriteEmployeesList(); int empID = db.InsertEmployee( new EmployeeDetails(0, "Mr.", "Bellinaso", "Marco")); HtmlContent.Text += " Inserted 1 employee. "; WriteEmployeesList(); db.DeleteEmployee(empID); HtmlContent.Text += " Deleted 1 employee. "; WriteEmployeesList(); }

Testing the Component private void WriteEmployeesList() { StringBuilder htmlStr = new StringBuilder(""); int numEmployees = db.CountEmployees(); htmlStr.Append(" Total employees: "); htmlStr.Append(numEmployees.ToString()); htmlStr.Append(" "); List employees = db.GetEmployees();

Testing the Component foreach (EmployeeDetails emp in employees) { htmlStr.Append(" "); htmlStr.Append(emp.EmployeeID); htmlStr.Append(" "); htmlStr.Append(emp.TitleOfCourtesy); htmlStr.Append(" "); htmlStr.Append(emp.FirstName); htmlStr.Append(", "); htmlStr.Append(emp.LastName); htmlStr.Append(" "); } htmlStr.Append(" "); HtmlContent.Text += htmlStr.ToString(); }