- •Table of Contents
- •Preface
- •What is ASP.NET?
- •Installing the Required Software
- •Installing the Web Server
- •Installing Internet Information Services (IIS)
- •Installing Cassini
- •Installing the .NET Framework and the SDK
- •Installing the .NET Framework
- •Installing the SDK
- •Configuring the Web Server
- •Configuring IIS
- •Configuring Cassini
- •Where do I Put my Files?
- •Using localhost
- •Virtual Directories
- •Using Cassini
- •Installing SQL Server 2005 Express Edition
- •Installing SQL Server Management Studio Express
- •Installing Visual Web Developer 2005
- •Writing your First ASP.NET Page
- •Getting Help
- •Summary
- •ASP.NET Basics
- •ASP.NET Page Structure
- •Directives
- •Code Declaration Blocks
- •Comments in VB and C# Code
- •Code Render Blocks
- •ASP.NET Server Controls
- •Server-side Comments
- •Literal Text and HTML Tags
- •View State
- •Working with Directives
- •ASP.NET Languages
- •Visual Basic
- •Summary
- •VB and C# Programming Basics
- •Programming Basics
- •Control Events and Subroutines
- •Page Events
- •Variables and Variable Declaration
- •Arrays
- •Functions
- •Operators
- •Breaking Long Lines of Code
- •Conditional Logic
- •Loops
- •Object Oriented Programming Concepts
- •Objects and Classes
- •Properties
- •Methods
- •Classes
- •Constructors
- •Scope
- •Events
- •Understanding Inheritance
- •Objects In .NET
- •Namespaces
- •Using Code-behind Files
- •Summary
- •Constructing ASP.NET Web Pages
- •Web Forms
- •HTML Server Controls
- •Using the HTML Server Controls
- •Web Server Controls
- •Standard Web Server Controls
- •Label
- •Literal
- •TextBox
- •HiddenField
- •Button
- •ImageButton
- •LinkButton
- •HyperLink
- •CheckBox
- •RadioButton
- •Image
- •ImageMap
- •PlaceHolder
- •Panel
- •List Controls
- •DropDownList
- •ListBox
- •RadioButtonList
- •CheckBoxList
- •BulletedList
- •Advanced Controls
- •Calendar
- •AdRotator
- •TreeView
- •SiteMapPath
- •Menu
- •MultiView
- •Wizard
- •FileUpload
- •Web User Controls
- •Creating a Web User Control
- •Using the Web User Control
- •Master Pages
- •Using Cascading Style Sheets (CSS)
- •Types of Styles and Style Sheets
- •Style Properties
- •The CssClass Property
- •Summary
- •Building Web Applications
- •Introducing the Dorknozzle Project
- •Using Visual Web Developer
- •Meeting the Features
- •The Solution Explorer
- •The Web Forms Designer
- •The Code Editor
- •IntelliSense
- •The Toolbox
- •The Properties Window
- •Executing your Project
- •Using Visual Web Developer’s Built-in Web Server
- •Using IIS
- •Using IIS with Visual Web Developer
- •Core Web Application Features
- •Web.config
- •Global.asax
- •Using Application State
- •Working with User Sessions
- •Using the Cache Object
- •Using Cookies
- •Starting the Dorknozzle Project
- •Preparing the Sitemap
- •Using Themes, Skins, and Styles
- •Creating a New Theme Folder
- •Creating a New Style Sheet
- •Styling Web Server Controls
- •Adding a Skin
- •Applying the Theme
- •Building the Master Page
- •Using the Master Page
- •Extending Dorknozzle
- •Debugging and Error Handling
- •Debugging with Visual Web Developer
- •Other Kinds of Errors
- •Custom Errors
- •Handling Exceptions Locally
- •Summary
- •Using the Validation Controls
- •Enforcing Validation on the Server
- •Using Validation Controls
- •RequiredFieldValidator
- •CompareValidator
- •RangeValidator
- •ValidationSummary
- •RegularExpressionValidator
- •Some Useful Regular Expressions
- •CustomValidator
- •Validation Groups
- •Updating Dorknozzle
- •Summary
- •What is a Database?
- •Creating your First Database
- •Creating a New Database Using Visual Web Developer
- •Creating Database Tables
- •Data Types
- •Column Properties
- •Primary Keys
- •Creating the Employees Table
- •Creating the Remaining Tables
- •Executing SQL Scripts
- •Populating the Data Tables
- •Relational Database Design Concepts
- •Foreign Keys
- •Using Database Diagrams
- •Diagrams and Table Relationships
- •One-to-one Relationships
- •One-to-many Relationships
- •Many-to-many Relationships
- •Summary
- •Speaking SQL
- •Reading Data from a Single Table
- •Using the SELECT Statement
- •Selecting Certain Fields
- •Selecting Unique Data with DISTINCT
- •Row Filtering with WHERE
- •Selecting Ranges of Values with BETWEEN
- •Matching Patterns with LIKE
- •Using the IN Operator
- •Sorting Results Using ORDER BY
- •Limiting the Number of Results with TOP
- •Reading Data from Multiple Tables
- •Subqueries
- •Table Joins
- •Expressions and Operators
- •Transact-SQL Functions
- •Arithmetic Functions
- •String Functions
- •Date and Time Functions
- •Working with Groups of Values
- •The COUNT Function
- •Grouping Records Using GROUP BY
- •Filtering Groups Using HAVING
- •The SUM, AVG, MIN, and MAX Functions
- •Updating Existing Data
- •The INSERT Statement
- •The UPDATE Statement
- •The DELETE Statement
- •Stored Procedures
- •Summary
- •Introducing ADO.NET
- •Importing the SqlClient Namespace
- •Defining the Database Connection
- •Preparing the Command
- •Executing the Command
- •Setting up Database Authentication
- •Reading the Data
- •Using Parameters with Queries
- •Bulletproofing Data Access Code
- •Using the Repeater Control
- •More Data Binding
- •Inserting Records
- •Updating Records
- •Deleting Records
- •Using Stored Procedures
- •Summary
- •DataList Basics
- •Handling DataList Events
- •Editing DataList Items and Using Templates
- •DataList and Visual Web Developer
- •Styling the DataList
- •Summary
- •Using the GridView Control
- •Customizing the GridView Columns
- •Styling the GridView with Templates, Skins, and CSS
- •Selecting Grid Records
- •Using the DetailsView Control
- •Styling the DetailsView
- •GridView and DetailsView Events
- •Entering Edit Mode
- •Using Templates
- •Updating DetailsView Records
- •Summary
- •Advanced Data Access
- •Using Data Source Controls
- •Binding the GridView to a SqlDataSource
- •Binding the DetailsView to a SqlDataSource
- •Displaying Lists in DetailsView
- •More on SqlDataSource
- •Working with Data Sets and Data Tables
- •What is a Data Set Made From?
- •Binding DataSets to Controls
- •Implementing Paging
- •Storing Data Sets in View State
- •Implementing Sorting
- •Filtering Data
- •Updating a Database from a Modified DataSet
- •Summary
- •Security and User Authentication
- •Basic Security Guidelines
- •Securing ASP.NET 2.0 Applications
- •Working with Forms Authentication
- •Authenticating Users
- •Working with Hard-coded User Accounts
- •Configuring Forms Authentication
- •Configuring Forms Authorization
- •Storing Users in Web.config
- •Hashing Passwords
- •Logging Users Out
- •ASP.NET 2.0 Memberships and Roles
- •Creating the Membership Data Structures
- •Using your Database to Store Membership Data
- •Using the ASP.NET Web Site Configuration Tool
- •Creating Users and Roles
- •Changing Password Strength Requirements
- •Securing your Web Application
- •Using the ASP.NET Login Controls
- •Authenticating Users
- •Customizing User Display
- •Summary
- •Working with Files and Email
- •Writing and Reading Text Files
- •Setting Up Security
- •Writing Content to a Text File
- •Reading Content from a Text File
- •Accessing Directories and Directory Information
- •Working with Directory and File Paths
- •Uploading Files
- •Sending Email with ASP.NET
- •Configuring the SMTP Server
- •Sending a Test Email
- •Creating the Company Newsletter Page
- •Summary
- •The WebControl Class
- •Properties
- •Methods
- •Standard Web Controls
- •AdRotator
- •Properties
- •Events
- •BulletedList
- •Properties
- •Events
- •Button
- •Properties
- •Events
- •Calendar
- •Properties
- •Events
- •CheckBox
- •Properties
- •Events
- •CheckBoxList
- •Properties
- •Events
- •DropDownList
- •Properties
- •Events
- •FileUpload
- •Properties
- •Methods
- •HiddenField
- •Properties
- •HyperLink
- •Properties
- •Image
- •Properties
- •ImageButton
- •Properties
- •Events
- •ImageMap
- •Properties
- •Events
- •Label
- •Properties
- •LinkButton
- •Properties
- •Events
- •ListBox
- •Properties
- •Events
- •Literal
- •Properties
- •MultiView
- •Properties
- •Methods
- •Events
- •Panel
- •Properties
- •PlaceHolder
- •Properties
- •RadioButton
- •Properties
- •Events
- •RadioButtonList
- •Properties
- •Events
- •TextBox
- •Properties
- •Events
- •Properties
- •Validation Controls
- •CompareValidator
- •Properties
- •Methods
- •CustomValidator
- •Methods
- •Events
- •RangeValidator
- •Properties
- •Methods
- •RegularExpressionValidator
- •Properties
- •Methods
- •RequiredFieldValidator
- •Properties
- •Methods
- •ValidationSummary
- •Properties
- •Navigation Web Controls
- •SiteMapPath
- •Properties
- •Methods
- •Events
- •Menu
- •Properties
- •Methods
- •Events
- •TreeView
- •Properties
- •Methods
- •Events
- •HTML Server Controls
- •HtmlAnchor Control
- •Properties
- •Events
- •HtmlButton Control
- •Properties
- •Events
- •HtmlForm Control
- •Properties
- •HtmlGeneric Control
- •Properties
- •HtmlImage Control
- •Properties
- •HtmlInputButton Control
- •Properties
- •Events
- •HtmlInputCheckBox Control
- •Properties
- •Events
- •HtmlInputFile Control
- •Properties
- •HtmlInputHidden Control
- •Properties
- •HtmlInputImage Control
- •Properties
- •Events
- •HtmlInputRadioButton Control
- •Properties
- •Events
- •HtmlInputText Control
- •Properties
- •Events
- •HtmlSelect Control
- •Properties
- •Events
- •HtmlTable Control
- •Properties
- •HtmlTableCell Control
- •Properties
- •HtmlTableRow Control
- •Properties
- •HtmlTextArea Control
- •Properties
- •Events
- •Index
Creating the Company Newsletter Page
Figure 14.17. Viewing the email
Creating the Company Newsletter Page
Let’s now extend the Dorknozzle site structure by adding a Newsletters page. This page will be accessible only to the site administrator, and will provide tools with which a customized newsletter can be sent to a list of recipients.
Open the Dorknozzle project in Visual Web Developer, and add to it a new web form named AdminNewsletter.aspx, making sure both the Select master page and Create code in a separate file checkboxes are checked. When prompted, select the Dorknozzle.master master page.
Complete the generated code like this:
File: AdminNewsletter.aspx
<%@ Page Language="VB" MasterPageFile="~/DorkNozzle.master" AutoEventWireup="false" CodeFile="AdminNewsletter.aspx.vb" Inherits="AdminNewsletter" Title="Dorknozzle Admin Newsletter"
%>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<h1>Create Newsletter</h1>
<asp:Label ID="resultLabel" runat="server" ForeColor="Red"/> <br />To:<br />
<asp:TextBox ID="toTextBox" runat="server" /> <br />Subject:<br />
<asp:TextBox ID="subjectTextBox" runat="server" /> <br />Introduction:<br />
601
Chapter 14: Working with Files and Email
<asp:TextBox ID="introTextBox" runat="server" TextMode="MultiLine" Width="300" Height="100" />
<br />Employee Of The Month:<br />
<asp:TextBox ID="employeeTextBox" runat="server" /> <br />Featured Event:<br />
<asp:TextBox ID="eventTextBox" runat="server" /> <br />
<asp:Button ID="sendNewsletterButton" runat="server" Text="Send Newsletter" />
</asp:Content>
Switch to Design View. The form should look like the one shown in Figure 14.18.
As you can see, the form contains seven TextBox controls, plus a Button and a Label. The boxes will allow the administrator to specify who the email is to be sent to and what the subject is, enter a simple introduction, identify the employee of the month, and feature a company event and a store item. The Button control is used to submit the form, while the Label control will display a confirmation message once the email has been sent.
To ensure that only administrators can send email messages, add the code highlighted in bold below, which we discussed in detail in Chapter 13, to Web.config:
File: Web.config (excerpt)
<!-- Only administrators are allowed to access AdminTools.aspx -->
<location path="AdminTools.aspx"> <system.web>
<authorization>
<allow roles="Administrators" /> <deny users="*" />
</authorization>
</system.web>
</location>
<!-- Only administrators are allowed to send emails --> <location path="AdminNewsletter.aspx">
<system.web>
<authorization>
<allow roles="Administrators" /> <deny users="*" />
</authorization>
</system.web>
</location>
</configuration>
602
Creating the Company Newsletter Page
Figure 14.18. The Create Newsletter form
One hurdle that we need to overcome is that we want to include an image to be displayed as part of the HTML content of the message. We can use either of two approaches to solve this problem:
Host the image on our web server and reference it in an <img> tag in the HTML code of the message (e.g. <img src="http://www.dorknozzle.com/Images/Newsletter.jpg" …>).
Embed the image data in the email.
We’ll apply the first technique, as it has the benefit of simplicity, and keeps the message as small as possible. If you want readers to see the image even when they’re not connected to the Internet, you should look into the second option.
603
Chapter 14: Working with Files and Email
Developer Mike Pope explained image embedding, and provided sample code, in a post on his blog.3
All we need to do is handle the Send Newsletter button’s Click event. While in Design View, double-click the button to generate the event handler signature. In the code-behind file, we’ll need to import the System.Net.Mail namespace:
Visual Basic |
File: AdminNewsletter.aspx.vb (excerpt) |
Imports System.Net.Mail |
|
|
|
C# |
File: AdminNewsletter.aspx.cs (excerpt) |
|
|
using System.Net.Mail; |
|
Then, complete the code of sendNewsletterButton_Click to send your newsletter:
Visual Basic File: AdminNewsletter.aspx.vb (excerpt)
Protected Sub sendNewsletterButton_Click( _
ByVal sender As Object, ByVal e As System.EventArgs) _ Handles sendNewsletterButton.Click
Dim smtpClient As SmtpClient = New SmtpClient() Dim message As MailMessage = New MailMessage() ' Try to send the message
Try
' Prepare two email addresses
Dim fromAddress As New MailAddress( _ "newsletter@dorknozzle.com", "Your Friends at Dorknozzle")
Dim toAddress As New MailAddress(toTextBox.Text) ' Prepare the mail message
message.From = fromAddress message.To.Add(toAddress) message.Subject = subjectTextBox.Text message.IsBodyHtml = True message.Body = _
"<html><head><title>" & _ HttpUtility.HtmlEncode(subjectTextBox.Text) & _ "</title></head><body>" & _
"<img src=""http://www.cristiandarie.ro/Dorknozzle" & _ "/Images/newsletter_header.gif"" />" & _
"<p>" & _
HttpUtility.HtmlEncode(introTextBox.Text) & "</p>" & _ "<p>Employee of the month: " & _ HttpUtility.HtmlEncode(employeeTextBox.Text) & "</p>" & _
3 http://www.mikepope.com/blog/DisplayBlog.aspx?permalink=1264
604
Creating the Company Newsletter Page
"<p>This months featured event: " & _ HttpUtility.HtmlEncode(eventTextBox.Text) & "</p>" & _ "</body></html>"
' Set server details smtpClient.Host = "localhost" ' Send the email smtpClient.Send(message)
' Inform the user
resultLabel.Text = "Email sent!<br />" Catch ex As Exception
|
' Display error message |
|
resultLabel.Text = "Couldn't send the message!" |
|
End Try |
End Sub |
|
|
|
C# |
File: AdminNewsletter.aspx.cs (excerpt) |
|
|
protected void sendNewsletterButton_Click( |
|
|
object sender, EventArgs e) |
{ |
|
|
SmtpClient smtpClient = new SmtpClient(); |
|
MailMessage message = new MailMessage(); |
|
// Try to send the message |
|
try |
|
{ |
// Prepare two email addresses
MailAddress fromAddress = new MailAddress( "newsletter@dorknozzle.com", "Your Friends at Dorknozzle" );
MailAddress toAddress = new MailAddress(toTextBox.Text); // Prepare the mail message
message.From = fromAddress; message.To.Add(toAddress); message.Subject = subjectTextBox.Text; message.IsBodyHtml = true; message.Body =
"<html><head><title>" + HttpUtility.HtmlEncode(subjectTextBox.Text) + "</title></head><body>" +
"<img src=\"http://www.cristiandarie.ro/Dorknozzle" + "/Images/newsletter_header.gif\" />" +
"<p>" +
HttpUtility.HtmlEncode(introTextBox.Text) + "</p>" + "<p>Employee of the month: " + HttpUtility.HtmlEncode(employeeTextBox.Text) + "</p>" + "<p>This months featured event: " + HttpUtility.HtmlEncode(eventTextBox.Text) + "</p>" +
605
Chapter 14: Working with Files and Email
"</body></html>";
//Set server details smtpClient.Host = "localhost";
//Send the email smtpClient.Send(message);
//Inform the user
resultLabel.Text = "Email sent!<br />";
}
catch (Exception ex)
{
// Display error message
resultLabel.Text = "Couldn\'t send the message!";
}
}
That’s a pretty large chunk of code, so let’s break it down. Initially, we create a new instance of the MailMessage class, called message:
Visual Basic |
File: AdminNewsletter.aspx.vb (excerpt) |
Dim message As MailMessage = New MailMessage()
C# |
File: AdminNewsletter.aspx.cs (excerpt) |
MailMessage message = new MailMessage();
Next, we begin to define the email message by setting some of the properties that the MailMessage class exposes:
Visual Basic File: AdminNewsletter.aspx.vb (excerpt)
' Prepare two email addresses
Dim fromAddress As New MailAddress( _ "newsletter@dorknozzle.com", "Your Friends at Dorknozzle")
|
Dim toAddress As New MailAddress(toTextBox.Text) |
|
' Prepare the mail message |
|
message.From = fromAddress |
|
message.To.Add(toAddress) |
|
message.Subject = subjectTextBox.Text |
|
message.IsBodyHtml = True |
|
|
C# |
File: AdminNewsletter.aspx.cs (excerpt) |
|
|
|
// Prepare two email addresses |
|
MailAddress fromAddress = new MailAddress( |
|
"newsletter@dorknozzle.com", "Your Friends at Dorknozzle" |
|
); |
|
MailAddress toAddress = new MailAddress(toTextBox.Text); |
|
// Prepare the mail message |
606
Creating the Company Newsletter Page
message.From = fromAddress; message.To.Add(toAddress); message.Subject = subjectTextBox.Text; message.IsBodyHtml = true;
You’ll notice we’ve set the IsBodyHtml property to True because we’re creating an HTML email message. By default, this property is set to False.
Next, we need to create the body of the message, which, essentially, will be an HTML document:
Visual Basic |
File: AdminNewsletter.aspx.vb (excerpt) |
|
|
message.Body = _ |
|
|
"<html><head><title>" & _ |
|
HttpUtility.HtmlEncode(subjectTextBox.Text) & _ |
|
"</title></head><body>" & _ |
|
"<img src=""http://www.cristiandarie.ro/Dorknozzle" & _ |
|
"/Images/newsletter_header.gif"" />" & _ |
|
"<p>" & _ |
|
HttpUtility.HtmlEncode(introTextBox.Text) & "</p>" & _ |
|
"<p>Employee of the month: " & _ |
|
HttpUtility.HtmlEncode(employeeTextBox.Text) & "</p>" & _ |
|
"<p>This month's featured event: " & _ |
|
HttpUtility.HtmlEncode(eventTextBox.Text) & "</p>" & _ |
|
"</body></html>" |
|
|
C# |
File: AdminNewsletter.aspx.cs (excerpt) |
message.Body = "<html><head><title>" +
HttpUtility.HtmlEncode(subjectTextBox.Text) + "</title></head><body>" +
"<img src=\"http://www.cristiandarie.ro/Dorknozzle" + "/Images/newsletter_header.gif\" />" +
"<p>" +
HttpUtility.HtmlEncode(introTextBox.Text) + "</p>" + "<p>Employee of the month: " + HttpUtility.HtmlEncode(employeeTextBox.Text) + "</p>" + "<p>This month's featured event: " + HttpUtility.HtmlEncode(eventTextBox.Text) + "</p>" + "</body></html>";
As we’re building an HTML document, we need to take care to convert special characters (including <, >, and &) into their character entity equivalents (<, >, &, and so on). The HtmlEncode method of the HttpUtility class does this for us.
607
Chapter 14: Working with Files and Email
Also note that the image we’ll use in the email has to be hosted on a site somewhere. In the code above, I’ve used an example URL. To get this example to work properly, you’ll need to host the image on your web site, and use the appropriate URL in your code.
We set the Host property of the smtpClient object to localhost, indicating that the computer that’s acting as our ASP.NET server should also act as our outgoing mail server—you’ll need to change this if you’re using another SMTP server. Finally, we call the Send method, pass in the message object, and display a confirmation message to the user within the resultLabel control:
File: AdminNewsletter.aspx (excerpt)
'Set server details smtpClient.Host = "localhost"
'Send the email smtpClient.Send(message)
'Inform the user
resultLabel.Text = "Email sent!<br />"
File: AdminNewsletter.aspx (excerpt)
//Set server details smtpClient.Host = "localhost";
//Send the email smtpClient.Send(message);
//Inform the user
resultLabel.Text = "Email sent!<br />";
Save your work and run the page in your browser. Enter all the necessary information into the newsletter page and click the Send Newsletter button, as shown in
Figure 14.19.
608
Creating the Company Newsletter Page
Figure 14.19. Sending the newsletter
609