Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

ASP.NET 2.0 Instant Results

.pdf
Скачиваний:
67
Добавлен:
17.08.2013
Размер:
11.03 Mб
Скачать

2

Wrox File Share

If you have ever tried to send a large e-mail attachment and failed, you’re not alone. The idea that you can attach a file or document to an e-mail message and send it over the Internet is a revolutionary concept in the history of computer technology. But not so fast! In order to send a document over the Internet, your Internet connection has to be fast enough to upload the file. In addition, the file has to be small enough to pass through the Internet connection before a timeout event occurs. If an Internet service provider decides that there is a limit on the size of files that can be transferred over the connection they provide, your e-mail capabilities may be greatly hindered. Furthermore, e-mail attachments can take up space on the server where they reside, and must be treated carefully. Some of the popular e-mail providers have to balance millions of e-mail users, and must create file storage policies that are fair and reasonable. Most of the time, there are limits to the size of e-mail attachments allowed to be sent through the e-mail server. Some providers allow for e-mail attachments up to 10MB; other providers allow for files even larger. This phenomenon has caused problems over the years because users are not able to send large files to their coworkers and friends over an Internet connection. What’s a user to do?

A solution to the conundrum of sending large e-mail attachments is to use a go-between web site — commonly known as a file share — that acts as an online file repository. The web site can send out a notification as to the file being sent to the server and provide a clickable link for the user to click and prompt to download the file. In this way, you’re not actually sending an e-mail message, but rather uploading a file tool web site for propagation. This solution has been copied many times over by many different web sites. This chapter, then, uses the file share as an opportunity to demonstrate some of the new and powerful features in ASP.NET 2.0.

The essential features of the Wrox File Share include the following:

The capability to upload a file to the web site, specifying which e-mail address to send the file to via an e-mail hyperlink for downloading the file.

Sending an e-mail automatically to the recipient, with the custom message and hyperlink to the download file.

The option to change the text content of the automatically sent e-mail, using specific variables for the values of the sender, recipient, hyperlink, and a custom message to the recipient.

Chapter 2

The capability to specify SMTP server information and e-mail account information as a configuration entry rather than a hard-coded value.

The capability to change the look and feel of the entire web site by simply modifying one entry in a configuration file.

This chapter also analyzes the various components that make up the web site, including the specific controls that ship with the ASP.NET 2.0 development environments. These controls include the following:

Login control

PasswordRecovery control

LoginStatus control

Menu control

SiteMapDataSource control

Themes

FileUpload control

The section “File Share Design” explores the design of the application in great detail. This includes the essential elements of involvement with regard to the technology and structure of the web site, as well as the various classes involved, a detailed look at all of the members of each class, and an explanation regarding the database tables and their relationships and values.

The section titled “Code and Code Explanation” focuses on the code of each class or module of importance. Some areas of focus include the WebForms used to upload files to the system, inserting data into the database tables.

The final section reviews how to extract and customize the Wrox File Share in a development environment, and how to install it to production.

Using the Wrox File Share

Using the Wrox File Share is extremely easy and naturally intuitive. The web site has only a few functional areas, because its purpose in life is simply to upload files and send e-mails.

If the Wrox File Share web site has been successfully installed (refer to the section “Setting up the Project” later in this chapter), you can browse to view the site by going to http://localhost/fileshare. The screen shown in Figure 2-1 appears.

At the top of the menu are several links to choose from:

Home

About

Contact Us

Admin

38

Wrox File Share

Figure 2-1

On the homepage, a total of three steps are required to send a large file to the site. The steps are to capture the recipient’s e-mail address, the actual file, a comment or message to the recipient, and, optionally, the e-mail address of the sender. Once these fields have been completed, clicking the Send button performs the upload and sends the e-mail.

An example of an e-mail sent to a recipient is shown in Figure 2-2.

This e-mail contains a hyperlink that streams via HTTP the file originally sent to the recipient.

Upon clicking the hyperlink, the dialog box depicted in Figure 2-3 appears.

Clicking Save opens the window’s Save As dialog box, prompting you to select a location and filename. This completes the task of sending a very large file to an e-mail recipient through a file share.

When you click the Admin link in the main menu, you are brought to the login screen if you have not already logged in to the web site and created a session. This page contains a Login control and a passwordRecovery control for you to use. Enter in Admin for the username and password# for the password, then click the Log In button.

39

Chapter 2

Figure 2-2

Figure 2-3

Once you log in to the site, you are brought to the administration section landing page, displayed in Figure 2-4.

This interface provides a way to customize the e-mails being sent out to file download recipients. The variables in use are the hyperlink, message, sender’s e-mail, and recipient’s e-mail. These variables are replaced as text in the body of the e-mail message, providing a customized e-mail experience.

This chapter covers the essential areas of the development that comprise the application. It walks through the class files in detail, explaining the methods and properties they expose. In addition, you will gain insight into the database, data model, and database objects.

The next section addresses the design of the Wrox File Share application, walking through the classes and database objects.

40

Wrox File Share

Figure 2-4

Wrox File Share Design

The Wrox File Share design is based on a few abstractions, including the following:

The file saved to the server is considered as a Resource class.

The methods used to save and get e-mail content are stored within the EmailContent class.

For each business class object there is a data class object that retrieves data from the database or performs inserts into the database.

The design provides visibility to the existence of business and data layers for the logical separation to occur.

In the sections that follow, you learn how to upload files and send e-mails; discern the Wrox File Share’s structure; and understand the data model and database objects, site themes, and the security model. You also learn about the classes involved and their scope of impact within the web site’s architecture.

Uploading Files

The FileUpload control is used to upload a file to the server. It displays a simple TextBox control next to a Browse button, which together allow users to select a file from their local machine to upload to the server. The fileupload1 instance of the FileUpload control exposes properties such as filename or

41

Chapter 2

filebytes, which prior to ASP.NET 2.0 were very difficult to expose. Also, the FileUpload control does not automatically save a file to the server once the user chooses it and submits the form that contains the control. The logic in the submitted form must explicitly save the specified file to disk. This code to save the file simply called the SaveAs method, which saves the file to a stated path on the local server file system.

Sending E-Mails

To send e-mails in ASP.NET 2.0, there are numerous areas to consider in the planning and development process. The first area to be certain of is the use of a valid SMTP mail server, with a valid e-mail account. The e-mail account to be used must allow permissions to relay mail.

The classes provided by ASP.NET 2.0 are maintained out of the System.Net.Mail class, providing the essential properties and contents of a mail message. The SmtpClient subclass sends the e-mail to the SMTP server that you designate.

The Web.config file provides the e-mail settings necessary for the configuration of the SMTP server. These settings are as follows:

EmailFrom

EmailSubject

SmtpServer

MailUser

MailPassword

MailPort

EmailFormatSelected

These are accessed from the Utilities class, formulating the contents of a struct variable. This struct variable is declared toward the top of the Utilities class, displayed here:

‘’’ <summary>

‘’’ MailSettings is a struct used to define the mail server information ‘’’ </summary>

Public Structure MailSettings Public MailServer As String

Public MailPort As Integer

Public MailFrom As String

Public MailUser As String

Public MailPassword As String

End Structure

The actual sending of the e-mail is performed in the Utilities class, within the following function:

‘’’ <summary>

‘’’ SendEmail is used to send an email, with the established settings

‘’’ </summary>

Public Shared Sub SendEmail(ByVal MsgTo As String, ByVal MsgFrom As String, _

42

Wrox File Share

ByVal MsgSubject As String, ByVal MsgText As String)

Dim SmtpSettings As MailSettings

SmtpSettings = GetSmtpSettings()

Dim SmptCl As New SmtpClient(SmtpSettings.MailServer, _

SmtpSettings.MailPort)

SmptCl.Credentials = GetCredentials(SmtpSettings)

Dim MailMsg As New MailMessage(MsgFrom, MsgTo)

MailMsg.Subject = MsgSubject

MailMsg.Body = MsgText

SmptCl.Send(MailMsg)

End Sub

This concludes the design and usage of the e-mail classes built into ASP.NET 2.0, and how the Wrox File Share implements the e-mail functionality.

Structure of the Site

The ASP.NET 2.0 web site file structure has been standardized a bit since its predecessor versions. These standardizations have to do with the naming conventions given to the folders within the site. The sections of the project are listed in the following table:

Section

Description

 

 

App_Code

Houses the business layer class (resource.vb) and the data layer class

 

(resourceDB.vb).

App_Data

The standard .NET folder for database files.

App_Themes

The themes folder, containing two themes for use within the site.

ContentFiles

The standard ASPX WebForm files for displaying content.

Controls

Stores all user controls.

FileStorage

The folder for storing uploaded files to be e-mailed to a recipient.

Images

Stores images for the header or any other pages.

Management

Stores the secured administrative WebForm pages.

[miscellaneous files]

These include the login page, config file, sitemap file, and master

 

page file at the root of the site.

 

 

One of the essential pieces of the Wrox File Share web site is the database. This database is made up of a SQL Server 2005 Express file, which contains a full representation of the database objects within it. The next section highlights the areas of focus within the database file, namely the stored procedures and tables.

43

Chapter 2

Data Model and Database Objects

The data model is very simple in nature; it only needs to store three basic data elements:

Email

Resource

Contact

Each resource contains references to the Email contact table, with the e-mail addresses of the contacts that have sent and received the e-mails from files uploaded to the system. Figure 2-5 displays the diagram of the database tables involved.

Figure 2-5

Following is a detailed view of each of the three tables.

The Email Table

Field Name

Data Type

Description

 

 

 

id

Int

The unique identifier for this record.

text

varchar(MAX)

The actual e-mail content stored as text, which the user

 

 

can edit in the administrative section of the web site.

 

 

 

The Contact Table

Field Name

Data Type

Description

 

 

 

id

Int

The unique identifier for this record.

email

Varchar(200)

The e-mail address of the contact.

44

 

 

 

Wrox File Share

The Resource Table

 

 

 

 

 

 

Field Name

Data Type

Description

 

 

 

 

 

id

Int

The unique identifier for this record.

 

filename

varchar(300)

The question ID to which this response applies.

 

fromContactID

Int

The ID of the contact record that sent the file.

 

toContactID

Int

The ID of the contact record that received the file.

 

message

Varchar(1000)

The message that the sender provided with the file

 

 

 

being uploaded.

 

datesent

Datetime

The datetime stamp at the time the file is uploaded.

In addition to these three tables, a number of stored procedures are in use. They follow a consistent naming pattern with the other chapters, as shown here:

sprocTableNameSelectList

sprocTableNameSelectSingleItem

sprocTableNameInsertUpdateItem

In such fashion, the following stored procedures are used in the application:

sprocEmailInsertUpdateItem

sprocEmailSelectSingleItem

sprocResourceInsertUpdateItem

sprocResourceSelectSingleItem

The naming convention allows you to easily and quickly find the stored procedures that apply to a specific table, and whether they are selects, inserts, updates, or deletes.

There are a few stored procedures that you need to walk through. The first stored procedure, sproc ResourceSelectSingleItem, is a basic SELECT statement based on the ID parameter, which selects a single resource record from the database and returns it to the caller:

ALTER PROCEDURE dbo.sprocResourceSelectSingleItem

/*

‘===============================================================

NAME:

sprocResourceSelectSingleItem

DATE CREATED:

October 19, 2005

CREATED BY:

Shawn Livermore (shawnlivermore.blogspot.com)

CREATED FOR:

ASP.NET 2.0 - Instant Results

FUNCTION:

Gets a specific resource from the DB

‘===============================================================

45

Chapter 2

*/

(@id int)

as

select * from Resource where id = @id

The preceding stored procedure is called from the ResourceDB.vb data layer, in the

GetResourceFileName function.

In similar fashion, the next stored procedure, sprocEmailSelectSingleItem, is used to select a single record from the Email table. There is no ID parameter in this one, because it assumes you will be storing only one record in this table for now. If you choose to add different e-mail versions or types in the system at a later time, this is the place to manage that information:

ALTER PROCEDURE dbo.sprocEmailSelectSingleItem

/*

‘===============================================================

NAME:

sprocEmailSelectSingleItem

DATE CREATED:

October 19, 2005

CREATED BY:

Shawn Livermore (shawnlivermore.blogspot.com)

CREATED FOR:

ASP.NET 2.0 - Instant Results

FUNCTION:

Gets the html and text message body from the DB

‘===============================================================

*/

as

select top 1 * from Email

Moving into the other two stored procedures, the level of complexity increases slightly. The following is the next stored procedure, sprocEmailInsertUpdateItem, which is used to update the e-mail text in the Email table’s one record. It accepts one parameter, @text, which is simply the text content of the template e-mail that is used to send e-mails to recipients:

ALTER PROCEDURE dbo.sprocEmailInsertUpdateItem

/*

‘===============================================================

NAME:

sprocEmailInsertUpdateItem

DATE CREATED:

October 21, 2005

CREATED BY:

Shawn Livermore (shawnlivermore.blogspot.com)

CREATED FOR:

ASP.NET 2.0 - Instant Results

FUNCTION:

Inserts or Updates the email content to the DB

‘===============================================================

*/

(@text varchar(MAX))

AS

UPDATE

Email

SET

[text] = @text

46