Download presentation
Presentation is loading. Please wait.
1
Web/Database Connectivity with ASP.NET
David Henson
2
Class Logistics Class Hours Classroom Setup Class Format
3
Course Outline Module 1 - Web Overview Module 2 - ASP.NET Overview
Module 3 - ASP.NET Webform Module 4 – Debugging/Tracing Module 5 - .NET Controls Module 6 – ADO.NET
4
Course Outline, Contd. Module 7 – Advanced Data Topics
Module 8 - Security Module 9 – ASP.NET /File Integration Module 10 – XML and Web Services
5
Module 1 – Web Services Overview
6
Definitions HTML ASP ASP.NET HTTP IIS Virtual Directory Browser MSIL
CLR ASP-Active Server Pages. A predecessor to ASP.NET, the ASP object model allows for dynamic content to be generated server side in an easy to use scripting language. VBScript and Jscript are built in. ASP pages are text files that are interpreted at runtime by the web server. ASP.NET-The newest version of ASP. ASP.NET represents a radical departure from ASP, following a more object oriented approach that generally leads to better programming practices and better performance. ASP.NET pages are compiled which allows for “early binding” of components, smaller memory overhead, better performance, and improved security. HTTP-Hypertext Transfer Protocol: The text based communication protocol between a browser and a web server. Usually travels over port 80. IIS-Internet Information Server: Microsoft’s free web server products. Windows 2000/XP Pro ship with version 5, Windows 2003 has version 6. Virtual Directory: An arbitrary location on the web server hard drive that is accessible from the web. Browser: Any consumer of a web application. MSIL-Microsoft Intermediate Language: The MSIL is an intermediate step between the source code in Visual Basic, C#, or any other .NET compliant language. The MSIL comes from the output of the language compiler, such as C#. The MSIL is compiled to form the binary executable code for that machine. MSIL allows anyone to create a language and a compiler usable by the .NET platform, as long as that compiler produces MSIL. CLR-Common Language Runtime: The component in the .NET architecture that compiles/executes/caches the MSIL. The CLR also deals with memory cleanup, called “garbage collection.” HTML-Hyper Text Markup Language: A text based document, often delivered by a web server across the HTTP protocol, that will be rendered in a browser.
7
Web Server/Client Interaction
Web browsers use a disconnected paradigm to interact with web servers. Often the challenge is to emulate a persistent connection for a seamless user experience. The most common technique today is to set a “cookie” on the client machine…a small piece of text that identifies the browser if it happens to come back to the site. The server maintains a database of cookies that have been set. Each time the browser visits the site, it is built to send with the request any cookies that apply to that site. If the server finds that cookie in the database, it can load other variables from memory or a database that apply to that client.
8
HTTP Protocol Header Body
The HTTP protocol is a text based protocol which is highly flexible and extensible, yet simple at the same time. The HTTP packet is broken up into two parts: Header and Body. A request is sent from a browser to the server with certain information in the header section of the request, for example any form parameters in a GET request or a string which identifies the browser software and version. A response is sent back to the browser, typically with a header and a body section. The header contains a status code (for example: 200 OK) and other information, such as cookies to be set. The body typically contains the text that makes up the html of the page.
9
Lab 1A – Viewing HTTP Traffic
Things to look for: Header Body Server Response Code In this lab, we will use two utilities to view the HTTP head and body data. Network Monitor, known as a “sniffer”, allows network packet analysis at a very low level. Telnet is a command line application that can be used to directly interact with a web server.
10
Methods For Dynamic Server-Based Content
CGI – Opens separate executable ASP – Interpreted each page load, Windows Only JSP – Portable, fast familiar to Java Programmers PHP – Cross Platform, C & Perl Like ASP.NET – Compiled, integrated into framework There are many technologies that allow for dynamic generation of content server side. Each has their unique advantages and disadvantages. When considering a technology to use, look at it in terms of performance, maintainability, supported platforms, and capabilities.
11
HTML Protocol End result of any dynamic server side product- dictates rendering of page Tags: <html> <body> <table><tr><td> <form> <a href=“…”> <br> <input type=“…”> The HTML Protocol is a “markup language” with pre-defined tags controlling the display format in a browser. Each tag has a start and and end. As an example, the body section of an HTML document should be enclosed within the: <body> </body> tags. Graphical applications like Hotdog, Frontpage, or Visual Studio .NET often shield you from the details of the HTML in the backend. A good understanding of HTML will be vital to longterm management, performance, and control over a web application. In this class, we will use just a small number of tags to accomplish our goals.
12
Lab 01B – Creating an E-Commerce Website Framework
In this lab, we will use HTML to create the format of our E-Commerce website. The page we generate here will be used as a template for pages that are added to our site. This technique allows web developers to create a consistent look and feel throughout their website.
13
Module 2 – ASP.NET Overview
14
.NET Framework Under Microsoft .NET, applications are created using one or more high-level programming languages, such as VB.NET and C#. Each .NET-compliant language goes through an initial compilation step that takes it from source-level code to the lowest common denominator language for .NET, Microsoft Intermediate Language (MSIL). MSIL is itself a full-fledged, object-aware language, and it's possible to build applications using nothing but MSIL. An application stays in MSIL form until it's executed, at which time it is just-in-time (JIT) compiled into native code. The native code is optimized for the machine it is running on and the exact running conditions at the moment of startup.
15
What is ASP.NET Not a programming language but a delivery mechanism
Can leverage any .NET programming language, like built-in VB.NET, C#, and third party like Delphi
16
.NET Features Multiple Language Support Increased Performance
Compiled code Cache Server Controls Web Services Improved Security Greater Scalability Cookie-less Sessions Easy Configuration and Deployment As a server side web technology, ASP.NET has an advantage over interpreted languages such as ASP. The first time a page is visited, it is compiled and added to the global cache. Every visit after that, the page runs as an application, compiled for that server at that time. The application will be recompiled if there is a change detected in the source code, or if the web server or web service is restarted.
17
Classic ASP Programming Model
Procedural, Top to Bottom Approach HTML/ASP Code Mixed
18
Classic ASP Example The time is:<%=now()%> <%
set conn = server.createobject(“ADODB.Connection”) conn.open “PROVIDER=SQLOLEDB;SERVER=instructor;UID=sa;PWD=;” set rs = server.createobject(“ADODB.Recordset”) sql = “SELECT * FROM Northwind..Products” rs.open sql, conn do while not rs.eof response.write(rs(“ProductID”) & “ “ & rs(“ProductName”) & “<br>”) rs.movenext loop %>
19
Classic Windows Programming Model
Create a Form Drop Controls On Form Write Event Handlers User activity generates messages which are handled by the event handlers
20
Demonstration – Spy++ What to look for: Event Driven Model of Windows
When Windows was first created, one of the greatist challenges was taking a procedural language, such as assembly or C, and making an operating system that responded to various events, such as a mouse click or typing on the keyboard. In the background, all Windows programs have what is called a “message loop.” This procedure is continally scanning for messages from the interface that might have to be handled. The Windows OS itself handles most messages, so if the application is not explicitly written to deal with a certain message, it simply passes that message down to the operating system. Spy++ is a utility that allows the developer to view these messages.
21
ASP.NET Programming Model
Process Same as Windows Programming Connectivity/State is emulated In earlier times, the programmer was responsible for coding the message loop for their own application. Besides being tedious and error-prone, programming in this way did not really model the way that Windows presented itself to the outside world. Newer development tools take care of the process in the backend, so the developer can focus on the problem at hand in an object oriented manner. Typically, this means starting with a form, draggin controls onto the form, then programming event handlers for any message that the programmer wanted to leverage. With Visual Studio .NET, ASP.NET pages can now be programmed in exactly this fashion. There are very few differences now creating an application in Visual Basic for the desktop or ASP.NET for the web. For developers not using the Visual Studio .NET utility, there are still advantages to the ASP.NET methodology. In ASP.NET, the code is separated from the HTML, leading to better manageablility, better performance, and more re-usable code.
22
ASP.NET Example This simple example shows the ASP.NET code in a separate section from the HTML. In examples later in the class, we will place the code in a separate file for further distinction. Visual Studio .NET places the code in separate files by default. <script language=“VB” runat=“Server”> Sub Page_Load() themessage.text = “Hello World” End Sub </script> <html> <body> <asp:label id=themessage runat=“server”/> </body> </html>
23
ASP.NET Configuration Files
Web.config IIS Settings Application Defined The web.config file at the root of the application is an important xml file with options covering many behaviors of the application, lncluding security, custom error messages, authentication and debugging/tracing. For web.config to be recognized, it must be placed at the root of the virtual directory for any particular application.
24
Solution Files Solution contains 1 or more projects
.sln file created in: My documents\Visual Studio Projects\*.* To Change Defaults: Tools/Options/Environment/Projects & Solutions New Solution Created With New Project
25
Project Files Project maps to web application
Web Application Created in: c:\inetpub\wwwroot\projectname Project Configuration File: (.vbproj or .csproj) New Virtual Directory Created W/ Project Each Application can have its own web.config
26
Other Files Webforms: .aspx Web Services: .asmx Styles.css
IIS Prevents Execution of Pre-Defined Extensions Code Behind Files: .vb & .cs Discovery Files: .disco, .vsdisco ASP.NET Application File: Global.asax Resource Files: .resx Web.Config A number of file extensions are registered in IIS to be sent to the .NET ISAPI.Dll. Here are a few of them: .aspx, .asmx, .vb, .cs., .disco, .vsdisco, .asax, .resx, web.config In some cases, the server prevents the execution or reading of the file from the web, for example the .vb code behind file. Important Note: Any files not registered with the .NET ISAPI .dll are NOT subject to the settings in the web.config or machine.config files. Examples would be: .htm, .zip, .jpg, .gif, .asp, etc.
27
Demonstration – Visual Studio .NET Quick Tour
28
Lab 2A – ASP.NET Redirection
In this lab, you will familiarize yourself with the Visual Studio .NET application
29
Module 3 – ASP.NET Webforms
The following topics are covered in this module: WebForms defined Events Creating Custom Event Handlers Form Validation
30
Webforms Defined aspx extension @Page Directive
Framework Is an Object Model Denoted by the runat="server" Attribute Contain Client-side and Server-side Code Contain HTML and .NET Server Controls Page Language="vb" %> <Form runat="server"> </Form> The directive is no longer valid. It has been replaced with directive, which has many attributes available. The webform is the key to interactivity in an ASP.NET application. The webform is based on the Page class.
31
Events User requests dbdemo.aspx Page_Load event detected
Sub Page_Load() executed All event handlers are called in a single flow of motion, before the user ever gets to see the page. All events occur in order, including Page_Unload, then the data is sent to the client. The client is disconnected before it gets a chance to respond.
32
WebForm Main Events Events Occur Each Time the Page is Accessed
Page_Init Page_Load Controls(only when form is posted back…Button1_Click for example) Page_Unload Page_Init() runs before controls are displayed on the page. Page_Load() runs after the controls have been rendered. Control Events are dealt with, but only when the form is posted back. Page_Unload() runs once the rest of the page has been dealt with. Close database connections here.
33
Other Supported Webform Events
Error – whenever the page generates one CommitTransaction AbortTransaction
34
Defining Server Control Event Handlers
<asp:button id=“Button1” onclick=“MyHandler”/> You may also double-click the control in design view to get into the “default” event handler for that control with a pre-defined event handler name.
35
Webform Validation Page.IsValid will be false if any control has failed validation Asp:ValidationSummary Control Set Display property of any validation control to None ValidationSummary Control will display msg from all controls Client Side Validation Setting: Set BaseValidator.EnableClientSideScript for any contol
36
Manual Validation Add form submit button with CausesValidation set to False, then call Page.Validate yourself. Take action based upon page.IsValid property
37
Lab 03A – Working with Web Forms
38
Module 4 – Debugging/Tracing
Error/Exception Handling
39
To Compile in Debug Mode
1. Add a "Debug=true" directive at the top of the file that generated the error. Example: Page Language="C#" Debug="true" %> or: 2) Add the following section to the configuration file of your application: <configuration> <system.web> <compilation debug="true"/> </system.web> </configuration>
40
Using the Debugger Setting Breakpoints Debug shortcut keys:
41
Logging Exceptions Try …some code Catch err AS Exception
Dim log as New EventLog() Log.Source = “MyPage” Log.WriteEntry(err.Message, EventLogEntryType.Error) End Try
42
Viewing Eventlogs
43
Display of Errors Error Modes:
RemoteOnly – Default, hides details if not local client Off – Shows all details and source…good for development, not production On – Displays custom error page if any, or generic error message
44
Custom Error Pages <configuration> <system.web> <customerErrors defaultRedirect=“MyError.aspx”> <error statusCode=“404” redirect=“My404.aspx”> </customErrors> </system.web> </configuration> Only works if ASP.NET is handling the request(.aspx extension)
45
Lab 04A – Debugging/Tracing
Enabling Tracing Exception Handling Debugging Writing to the Windows Eventlog Custom Error Messages
46
Module 5 – .NET Controls
47
The ASP.NET Server Controls
HTML Server Controls ASP.NET Web Form Controls ASP.NET List Controls ASP.NET Templated Controls ASP.NET Rich Controls ASP.NET Validation Controls ASP.NET Mobile Controls HTML Server Controls mirror standard HTML tags, but have the runat=“server” attribute added in. Based on HtmlControl base class. ASP.NET Controls have the <asp:...> tag. Based on WebControl base class. These native controls have a richer object model with more properties and events, and their use also more closely mirror standard Windows software development. ASP.NET List Controls can be bound to a datasource, or programmatically have their members created. Templated controls allow you to provide blocks of HTML that specify portions of the rendering of the control. The DataList, DataGrid, and Repeater controls fall into this category. The DataGrid and DataList controls will render a certain amount of HTML by default, while it is up to you to provide the entire HTML contents for a Repeater control.
48
User Controls .ascx file Replaces the #include file from ASP
Provides re-usuable code within your application Contained within a Webform User controls are essentially webforms with an extension of .ascx, and are perfect for re-usable blocks of code or HTML, for example a header on every page in the site. As an example, to use the .ascx file in a webform, you would place code similar to the following into the .aspx file: TagPrefix=“UserControl” TagName=“Header” Src=“Header.ascx” %> … <UserControl:Header id=“MyHeader” runat=“Server” />
49
Custom Server Controls
Based on System.Web.UI.Control Generates its own HTML (unlike a business logic assembly) .NET assemblies are .dll files that contain a collection of classes, and are re-distributable even to other machines. They are ideal for containing business logic and calculations. Custom controls differ in their design from a standard assembly in that they contain their own interface generation.
50
Key Concept - Rendering
Controls are responsible for rendering themselves You can override the Render() function on your own controls
51
HTML Controls Best for “Converting” from ASP to ASP.NET
Add the runat=“server” attribute to existing controls
52
ASP.NET Controls Mirror HTML Controls
More Consistent Properties/Naming Across Control Types
53
Common ASP.NET Webform Control Properties
ID Text
54
Control Validation
55
Data Binding Controls Easily bound to a datasource (database, file, XML doc) Default HTML easily modified
56
Templated Controls You supply the HTML
57
Lab 05A – Working with .NET Controls
58
Module 6 – ADO.NET
59
Components of ADO.NET SqlDataAdapter SqlDataSet SqlDataTable
SqlDataReader SqlCommand
60
Required Namespaces Namespace Defined Two In Use This Class:
System.Data – Provider Independent Like DataSet System.Data.SqlClient – Provider Dependent Like SqlConnection ASP.NET Syntax: Import Namespace=“System.Data” %> The classes, enums, structs and types associated with each provider are defined in the namespace. Namespaces allow objects of the same name defined in different namespaces not to collide in the same project.
61
Providers Providers Available: SQL Server .NET Provider
OleDB .NET Provider Example-AllRecordsBasicOleDB.aspx ODBC .NET Provider SQL XML .NET Provider
62
Connections Connection Defined Where to Store the Connection String
Connection Syntax Examples Connection Pooling Security Close Your Connections! Monitoring Connections A Connection defines the options needed to gain access to a database and related tables. It is generally defined by a string which varies depending upon the type of database you will access and the options required. Other options include transaction and pooling behavior.
63
Where to Store the Connection String
Options Available: Front End App (.aspx file) Web.Config UDL File (OleDB Only) Registry Custom File COM+ Catalog Using Connection Strings Evaluation Terms: Security, Convenience, Performance You can use “Persist Security Info = false” in your connection string to prevent programmatic access to login/password information from the ConnectionString property of SQLConnection or OleDBConnection Objects
64
Two Connection String Syntax Examples
In the .aspx file: ConnString = “server= ;UID=sa;PWD=;” Dim Conn As New SqlConnection(ConnString) In Web.Config XML file: <configuration> <appSettings> <add key=“ConnString” value=“server= ;UID=sa;PWD=;”/> </appSettings> </configuration>
65
Connection Pooling Defined
Controlling Min/Max-Example6ShowConnectionStatePoolControl.aspx Importance of “Exact String Match” Pooling for SqlClient vs. OleDBClient Effects of pooling on SQL security Close Your Connections! Deployed through “Exact Match” Reduce default max (100) during development to detect errors during development Pools are transaction specific, unless you are not in a transaction OleDB resource pooling is discouraged in favor of COM+ object pooling because of configuration options and performance. Monitor pooling through Profiler or through System Monitor Windows authentication is slightly slower for pooled connections than standard authentication
66
Performance Issues Choose Providers Wisely DataReader vs. DataAdapter
Repeater Control vs. DataGrid Control Connection Pooling Embedding SQL vs. Stored Procedures Controlling The HTML Typed Accessor Methods-Example7AdapterVsReaderUsingTypedAccessorMethods.asp
67
DataReader Vs. DataAdapter
Forward Only Only One Record At A Time In Memory “Firehose” Functionality Typed Accessor Methods Avoid Conversions DataAdapter More Overhead More Flexible Note that while the DataReader is open, the connection used is exclusive to that DataReader and cannot be used for anything else If the command contains output params or return values, these will not be available until the Reader is closed
68
Repeater Control vs. DataGrid(or DataList) Control
Repeat Control Simply Repeats Low overhead You Have To Do Everything You Can Do It Better Than Microsoft Did! DataGrid Default HTML Behaviour Higher Overhead, Most Functionality
69
Embedding SQL vs. Stored Procedures
Stored Proc Advantages: Procedure Cache Separate Security Model Potentially Less Network Traffic Output Params, Error Code & Result Set Can Do Anything Server Side Abstracts the Front End from Changes – Possible Disadvantage with Xcopy Deployment
70
Controlling the HTML Use Stylesheets if Possible!
Make Sure The Page Fails Gracefully If Needed With DataGrids, Use TemplateColumns
71
Final Recommendations
Use DataGrids Only When Updates Are Needed Embed Connection In Code Behind File Only “Select” What You Need Call StoredProcs For Ultimate Performance When “Paging”
72
References Book: “Programming Data-Driven Web Applications with ASP.NET” Web:
73
Comparing ADO/ADO.NET
74
Lab 6A – Exploring ADO.NET
75
Module 7 – Advanced Database Topics
Paging Inserts/Updates/Deletes Using Stored Procedures Dynamic SQL Server HTML Generation Index Tuning Wizard
76
Paging Methods for paging: Data Grid Manual Stored Procedures
77
Inserts INSERT table1 VALUES(‘Smith’,’Joe’,)
78
Updates UPDATE Table1 SET Unitprice = Unitprice * 1.1
79
Deletes DELETE Table1 WHERE CustomerID = 10
80
Using Stored Procedures
CREATE PROC FinalSales @Region int AS BEGIN SELECT * FROM sales WHERE RegionID END
81
Dynamic HTML Generation
Triggers are procedures that fire on insert, update or delete Through triggers, you can create HTML files when data changes
82
Index Tuning Wizard Used to optimized SQL Server through indexing
83
Lab 7A – Advanced Database Topics
Add Paging to a Data Grid Controlling Output-Templated Repeater Using Stored Procedures
84
Module 8 – Security
85
IIS Security Configuration
86
ASP.Net Security Related Configuration
87
Authentication/Encryption
88
Setup of SSL
89
Lab 8A – Setup of SSL
90
Module 9 – ASP.NET Email and File Integration
91
SMTP Protocol
92
Sending Email SMTP is now built into .NET
System.Web.Mail.SmtpMail.Send( from, to, subject, body )
93
Reading/Writing Files
Dim w As IO.StreamWriter w = IO.File.CreateText("C:\somefile.txt") w.WriteLine(Request("textbox1")) w.Close()
94
Lab 9A – and Files
95
Module 10 – XML
96
What is XML?
97
XML Document Well formed if: Valid if:
Doc has a root element Every tag has an end(case sensitive) No special characters are used Valid if: Doc format agrees with specification
98
XML Document Example
99
Formatting Issues Use .css to separate data from the formatting
<?xml:stylesheet href="test.css" type="text/css" ?>
100
Web Services .asmx file Inherits from System.Web.Services.WebService
Web Service method marked with the WebMethodAttribute Allows client to discover its methods Interacts w/ client through SOAP
101
Web Service Example TimeServer web service returns the current time
102
Implementation Plumbing is built into the classes…you focus on the business needs Web Service consumer adds the web reference, then uses the class like any other
103
Lab 10A – XML
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.