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

ASP.NET 2.0 Instant Results

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

3

Modifying the Wrox

Chat Ser ver

Some possible enhancements to the Wrox Chat Server could include:

Management Capabilities: The ability to see which chat sessions are used and how often they are used

Automated Responses: Automatic messages to respond to a user if no administrative personnel are available to enter their chat requests.

Chat Content Filters: The ability to track and alert administrative personnel when certain vulgarities or unacceptable terminology is used within chat sessions.

The following steps would be required to implement automated responses:

1.Open the Web.config file, and scroll down to the appSettings section. Add two entries for the hour in the morning that the site opens and the hour that it closes, (using military hours from 0 to 24). You also will need to add an entry to specify the administrator’s email address, and the message to send out to the chat user during off-hours. So if you want to open at 8am and close at 6pm, the following four entries would be added (using military time, 8am is the number 8, and 6pm is the number 18):

<configuration xmlns=”http://schemas.microsoft.com/.NetConfiguration/v2.0”> <appSettings>

<add key=”HourOpen” value=”8”/> <add key=”HourClose” value=”18”/>

<add key=”AdminEmail” value=”Admin@MyDomain.com”/>

<add key=”ClosedMessage” value=”We are sorry, but nobody is here to assist you right now. Please try again between 8 am and 6 pm PST. For online assistance, visit our Help page.”/>

2.Expand the ContentFiles folder, then open the ChatRoom.aspx.vb WebForm’s codebehind page to view its contents. Within this file is the RaiseCallbackEvent event, where you will add a conditional message based on the time of the chatted message. The text of this function is below:

Chapter 3

‘’’ <summary>

‘’’ the RaiseCallbackEvent captures the content from the ‘’’ chat message from the window...

‘’’ </summary>

Public Sub RaiseCallbackEvent(ByVal eventArgument As String) _ Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent

If eventArgument.Length > 0 Then ChatRoom.SaveMessage(Request.QueryString(“chatRoomID”), _

eventArgument, Session(“Email”))

End If End Sub

Enter the following code just below the SaveMessage method call, and before the end of the IF statement:

Dim mHour As Integer = System.DateTime.Now.Hour

If Config.HourOpen <= mHour And Config.HourClose >= mHour Then

ChatRoom.SaveMessage(Request.QueryString(“chatRoomID”), _

Config.ClosedMessage, Config.AdminEmail)

End If

The entire function would be:

‘’’ <summary>

‘’’ the RaiseCallbackEvent captures the content from the ‘’’ chat message from the window...

‘’’ </summary>

Public Sub RaiseCallbackEvent(ByVal eventArgument As String) _ Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent

If eventArgument.Length > 0 Then ChatRoom.SaveMessage(Request.QueryString(“chatRoomID”), _

eventArgument, Session(“Email”))

Dim mHour As Integer = System.DateTime.Now.Hour

If Config.HourOpen <= mHour And Config.HourClose >= mHour Then ChatRoom.SaveMessage(Request.QueryString(“chatRoomID”), _

Config.ClosedMessage, Config.AdminEmail)

End If End If

End Sub

3.In the App_Code folder, open the config.vb class file. Add the four entries needed for the HourOpen and HourClose variables to be available to the rest of the application logic. Since the properties are public shared, they can be accessed from the class directly via dot-notation. Add the following code to this file to expose these four variable values from the Web.config file:

‘’’ <summary>

‘’’ The hour to open in the morning ‘’’ </summary>

Public Shared ReadOnly Property HourOpen() As String Get

Return ConfigurationManager.AppSettings(“HourOpen”).ToString() End Get

8

Modifying the Wrox Chat Server

End Property ‘’’ <summary>

‘’’ The hour to close in the evening ‘’’ </summary>

Public Shared ReadOnly Property HourClose() As String Get

Return ConfigurationManager.AppSettings(“HourClose”).ToString() End Get

End Property ‘’’ <summary>

‘’’ The administrator’s email address ‘’’ </summary>

Public Shared ReadOnly Property AdminEmail() As String Get

Return ConfigurationManager.AppSettings(“AdminEmail”).ToString() End Get

End Property ‘’’ <summary>

‘’’ The message to be sent back to the user ‘’’ </summary>

Public Shared ReadOnly Property ClosedMessage() As String Get

Return ConfigurationManager.AppSettings(“ClosedMessage”).ToString() End Get

End Property

4.That’s it! Press F5 to run the application and test it out. If a chat message comes into the system that is outside of the stated work hours of 8am to 6pm, then the preconfigured chat textual message will be posted immediately following the user’s message.

Now that you have constructed a basic enhancement, you should have a much better grasp of the application’s simplistic file structure and layered approach, and you can move quicker to add more functionality to the application, or write a new feature of your own.

9

4

Modifying the Wrox

Sur vey Engine

Although the Wrox Survey Engine is a great starter application for utilizing ASP.NET 2.0, it likely does not contain all the features you might want to see. Some possible enhancements to the Wrox Survey Engine could include:

Survey Reviews: Let users make comments on what they think about the survey.

Number Counts: The ability to view the number of responses to each of the surveys from the Administration section.

Charting: The ability to view a pie chart or a bar chart next to the percentages of the survey results pages.

Email Invitations: An e-mail message-generation tool for sending an e-mail invitation to take the survey.

Final Report: A request area to view final survey results once a specified number of responses are received.

Reporting: Some prepared reports about surveys, their responses, and percentages for each response.

If you want to implement number counts, the following steps would be required:

1.In Visual Web Developer or Visual Studio 2005, open the website from its extracted location at C:\inetpub\wwwroot\SurveyEngine. Open the Database Explorer by selecting the View Database Explorer menu selection. Find your database under the Database Connections node of the tree view. If your database is not listed, right click the Data Connections node in the tree view, select the Add Connection option, select the Microsoft SQL Server File option, and browse to the PhotoDB.mdf file in the App_Data folder of the site. This should bring up your connection within the Database Explorer window. Now that you have a valid database tree, expand it to see the Views node, and drill down to the viewResponseCountBySurvey view. Right click the view and select the Open View Definition option.

Chapter 4

2.The query used for the view should be the following:

SELECT TOP (100) PERCENT dbo.viewResponseCountBySurvey.SurveyID, dbo.viewResponseCountBySurvey.NumberResponses / dbo.viewQuestionCountBySurvey.NumQuestions AS Responses

FROM dbo.viewQuestionCountBySurvey INNER JOIN dbo.viewResponseCountBySurvey

ON dbo.viewQuestionCountBySurvey.SurveyID = dbo.viewResponseCountBySurvey.SurveyID ORDER BY dbo.viewResponseCountBySurvey.SurveyID

The table design area, which corresponds to the SQL query, should appear similar to Figure 4-1.

Figure 4-1

In this view, the count for the survey responses is returned with the SurveyID. To obtain the survey records and the count of responses, you have to add the Survey table to the view designer, joining on the SurveyID. So in chronological steps, the query can be modified to provide all of the fields you need for the survey grid, along with its number of user responses.

You can modify this query by right clicking near the tables in the design area, and selecting the Add Table option.

3.On the Tables tab of the pop-up window, select the Survey table. Click OK to see the Survey table added to the designer window.

4.Then, click the ID column in the Survey table, and drag to the viewQuestionCountBySurvey table and release over the SurveyID field. The relationship of inner join between the surveyID and ID fields. Then check the box next to all of the column names (ID, Name, Description, Date, and IsCurrentSurvey). Next, uncheck the SurveyID column from the viewResponseCountBySurvey view within the same designer window. The results of this query will return the fields of the Survey table, and count the number of responses that the survey generated. Figure 4-2 displays the view design with the added Survey table.

Figure 4-2

The new Transact-SQL code for the query is below:

12

Modifying the Wrox Survey Engine

SELECT TOP (100) PERCENT dbo.viewResponseCountBySurvey.NumberResponses / dbo.viewQuestionCountBySurvey.NumQuestions AS Responses, dbo.Survey.Name, dbo.Survey.Description, dbo.Survey.Date, dbo.Survey.IsCurrentSurvey, dbo.Survey.ID

FROM dbo.viewQuestionCountBySurvey INNER JOIN dbo.viewResponseCountBySurvey ON dbo.viewQuestionCountBySurvey.SurveyID = dbo.viewResponseCountBySurvey.SurveyID INNER JOIN

dbo.Survey ON dbo.viewQuestionCountBySurvey.SurveyID = dbo.Survey.ID ORDER BY dbo.viewResponseCountBySurvey.SurveyID

Running the SQL query produces the results shown in Figure 4-3.

Figure 4-3

5.The resulting data provide a better view of a survey, and now you can provide this view to the user through modifying the stored procedure that is used to get the records for the user. Do this by opening the stored procedure entitled sprocSurveySelectList:

ALTER PROCEDURE dbo.sprocSurveySelectList

/*

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

NAME:

sprocSurveySelectList

DATE CREATED:

October 5, 2005

CREATED BY:

Shawn Livermore (shawnlivermore.blogspot.com)

CREATED FOR:

ASP.NET 2.0 - Instant Results

FUNCTION:

Returns a list of surveys from the database.

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

*/

as

select * from Survey

By modifying this stored procedure to select from the modified view, rather than the Survey table directly, you can obtain the fields needed to display the number of responses for the surveys.

6.Change the select statement to read, Select * from viewNumberResponsesBySurvey and click Save.

The new stored procedure should look exactly like the code excerpt below:

ALTER PROCEDURE dbo.sprocSurveySelectList

/*

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

NAME:

sprocSurveySelectList

DATE CREATED:

October 5, 2005

CREATED BY:

Shawn Livermore (shawnlivermore.blogspot.com)

CREATED FOR:

ASP.NET 2.0 - Instant Results

FUNCTION:

Returns a list of surveys from the database.

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

*/

as

select * from viewNumberResponsesBySurvey

13

Chapter 4

7.Next, modify the user interface to provide the visibility to the new information in the GridView. Double-click the webform Admin.aspx to open the form in Design View. Then, right click the GridView control and select Edit Columns. In the Edit Columns screen, add a bound column, with the HeaderText value of # Columns and the DataField property of Responses. Click OK, and save the form.

8.Run the project, log in to the site, and view the Administration grid. You should see the # Responses column with the number of responses listed for each survey, as displayed in Figure 4-4.

Figure 4-4

Now that you have walked through an example enhancement, there are plenty more ideas that may flow from this direction in conducting surveys online.

14

5

Modifying the Wrox CMS

This chapter has focused mainly on the database aspects of the CMS. That allowed you to focus on important concepts that are the basis of the CMS without being caught up with explaining loads of code that isn’t really important. So you surely noticed this is quite a bare-bones CMS without eye candy and cool features. However, you have a good foundation to build on, implementing those features that meet your own or you customer’s expectations. With the concepts and techniques you learned in this chapter, you should now able to expand this CMS with your own features. Some examples of possible extensions include:

1.Display extended information about the published content item. Instead of just showing the title and the body text, you could display information like the date the item was published and last updated, and the author that created the article.

2.Content rating. Let your visitors rate the item to show their opinion about it. You could collect the user’s rating with a simple user control and display the results (with a bar graph for example) with another user control.

3.User feedback. A common extension for a CMS-driven site like the one presented in this chapter is to allow visitors to respond on the content; this is a good way for you to get feedback from your visitors, while at the same time the contributions may add to the value of it, increasing the chance that others might read it.

Another important feature is a hit counter. It would be interesting to know how many people actually viewed your content item. This is interesting for you to find out how popular an article is. It can also be interesting to your visitors, as it might give an indication whether the content item is worth reading. The next walkthrough shows you how to implement the hit counter.

Design Considerations

There are a few ways to implement a hit counter for each content item in your site. In all cases, you need a way to store information about the ID of the content item and the number of times it has been viewed. Since the entire CMS is database-driven, it makes a lot of sense to store this information in the database as well. A simple table, called PageView, with a column that holds the content item’s ID and a counter that tracks the number of page views is more than enough.

Chapter 5

The next consideration is where you actually count the article. At first, the stored procedure that retrieves the content item from the database, sprocContentSelectSingleItem, seems like the most logical place. After all, when the article is retrieved from the database, you know it will be presented on the web site in some form. However, this same stored procedure is also used to retrieve a content item in the Management section. This means that whenever you want to edit the item, you also increase the counter, resulting in distorted statistics.

Taking that into account, the best place to track the page view is in the ContentDetail.aspx page itself. On that page, you know the content item that is being requested so it’s easy to update the page count in the database. To make things easy to manage, it’s best to create a separate class called Logging with a method like LogContentItemRead to update the database. Using a separate class enables you to add other logging capabilities, like keeping track of the visitor’s IP address, the date and time the content item was requested, and so on, at a later stage.

To implement this class, and the data access code that it requires, follow these steps:

1.Inside the BusinessLogic folder, found in the special App_Code folder in the root of the site, create a new class and call it Logging.

2.Add a shared Sub called LogContentItemRead that accepts an Integer (the ID of the content item in the database) and have it call a method in the data access layer with the same name and signature. You should end up with code like this:

Public Shared Sub LogContentItemRead(ByVal contentId As Integer)

ContentDB.LogContentItemRead(contentId)

End Sub

3.Inside the DataAccess folder, also located in the App_Code folder, create a new class and name it LoggingDB. At the top of the file, add an Imports statement for the System.Data and the System.Data.SqlClient namespaces and then create a Sub that has the same signature as the one in the business layer, like this:

Public Shared Sub LogContentItemRead(ByVal contentId As Integer)

End Sub

4.Inside the Sub, write code that sends the ID of the content item to a stored procedure called sprocPageViewUpdateSingleItem. You’ll need to create a connection and a command object, pass a single parameter and then use ExecuteNonQuery to send it to the database. You also need to add an Imports statement for System.Data and System.Data.SqlClient. The body for the method should end up like this:

Using myConnection As New SqlConnection(AppConfiguration.ConnectionString) Dim myCommand As SqlCommand = New SqlCommand _

(“sprocPageViewUpdateSingleItem”, myConnection)

myCommand.CommandType = CommandType.StoredProcedure

myCommand.Parameters.AddWithValue(“@contentId”, contentId) myConnection.Open()

myCommand.ExecuteNonQuery()

myConnection.Close() End Using

16