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

ASP.NET 2.0 Instant Results

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

Wrox Chat Server

End Sub

Public Function GetCallbackResult() As String Implements _

System.Web.UI.ICallbackEventHandler.GetCallbackResult

End Function

The RaiseCallbackEvent() accepts the call from the client, allowing the server to process business logic as needed, and the GetCallbackResult() function sends a response back to the client, allowing the client to display the update in the browser via JavaScript (keep reading, it will make sense in a moment).

3.Next, provide the client-side script, which provides the Callback Manager script’s entry point and exit point as embedded JavaScript functions on the client side. This script’s functions are named CallServer and ReceiveServerData:

Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim cm As ClientScriptManager = Page.ClientScript

Dim cbReference As String

cbReference = cm.GetCallbackEventReference(Me, “arg”, _ “ReceiveServerData”, “”)

Dim callbackScript As String = “”

callbackScript &= “function CallServer(arg, context)” & _ “{“ & cbReference & “; }”

cm.RegisterClientScriptBlock(Me.GetType(), “CallServer”, _ callbackScript, True)

End Sub

4.Add a standard HTML text box to the HTML markup on the form. This will be named txtMessage. This provides the mechanism of input from the user to the server:

<input id=”txtMessage” style=”width: 218px; height: 55px” type=”text” />

5.Then, with the following code, add a browser-side button that contains a special onclick event call to the Callback Manager entry point (for which you embedded the name of CallServer in step 3). This onclick event accepts an argument of the txtMessage control’s text value. This is how the local client-side scripting captures the user input and sends it off to the server:

<input type=”button” value=”Send” onclick=”CallServer(document.getElementById(‘txtMessage’).value, null)” style=”width: 57px; height: 60px” id=”Button1”/><br />

6.Add a JavaScript routine called ReceiveServerData() to the HTML markup on the form. This routine accepts the arguments of arg and context. Don’t worry about context, but arg provides the response of data back from the server, once it is done processing the call. This is the actual implementation of the Callback Manager’s exit point. Any code can go here, but it is the Wrox Chat Server’s primary way of updating the user as the result of the behind-the-scenes callback event. In this case, an HTML element’s contents are updated with a string value from the server:

<script type=”text/javascript”> function ReceiveServerData(arg, context)

{

//send txt to a different html control, or process the info via javascript...

var obj = document.getElementById(“MyOtherHTMLcontrol”);

77

Chapter 3

obj.innerHTML += arg;

}

</script>

Now you have a working callback routine. The client has the necessary JavaScript routines, and the server provides the necessary references to the Callback Manager classes and events. Not bad for 10 minutes of work and a little bit of elbow grease!

Structure of the Site

The sections of the web site project are listed in the following table:

Section

Description

 

 

App_Code

The folder that houses the business layer class (chatroom.vb) and

 

the data layer class (chatroomDB.vb).

App_Data

The standard .NET folder for database files.

App_Themes

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

ContentFiles

The standard ASPX WebForm files for displaying content.

Controls

Stores all user controls.

Images

Stores images for the header or any other pages.

[miscellaneous files]

These include the Web.config file, sitemap file, and Master Page

 

file at the root of the site.

 

 

Data Model

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

Chat Room Categories

Chat Rooms

Messages

Users

Each chat room is classified under a single chat room category. There is no limit to the number of chat rooms and categories you can create, although it must be done manually at the database level for now. Each message is posted under exactly one chat room and is tracked by the user ID who sent it. All messages for all chat rooms are stored on the server, but only the chat messages for the last hour are sent back to the users. You can change the number of hours to keep messages active in the Web.config file of the site.

The diagram of the database tables involved is displayed in Figure 3-4.

A detailed view of each of the four tables is given in the following sections.

78

Wrox Chat Server

Figure 3-4

The Category Table

The Category table stores all of the categories to which each chat room is assigned. It contains three fields, defined as follows:

Field Name

Data Type

Description

 

 

 

ID

Int

The unique identifier for this record.

Name

varchar(MAX)

The name of the category that the user sees when viewing

 

 

all of the chat rooms by category in the tree view of the

 

 

homepage.

Description

varchar(MAX)

The textual description of the category, which can be dis-

 

 

played at will within the application.

 

 

 

The next table houses the data for the chat rooms themselves.

The Room Table

The Room table is essentially a basic entity containing what you would need to describe a chat room; that is, the category of the room, a name for the room, and a textual description.

Field Name

Data Type

Description

 

 

 

ID

Int

The unique identifier for this record.

CategoryID

Int

The foreign key that identifies under which category this

 

 

chat room is classified.

Name

varchar(MAX)

The name of the chat room.

Description

varchar(MAX)

The textual description of the chat room, which can be

 

 

displayed at will within the application.

 

 

 

79

Chapter 3

Now that you have an idea of where the categories and chat rooms fit into the data model, you will be able to understand where and how the actual messages are stored and used within the same model.

The Message Table

The Message table contains the text messages for each and every chat room by all of the users. Although all of the visible messages provided to the chat users are filtered to show only the messages sent within a certain number of hours, all of the messages are maintained here until a database administrator determines it is time to delete or archive the data. Following are the columns for this Message table, and their respective type and description information:

Field Name

Data Type

Description

 

 

 

ID

Int

The unique identifier for this record.

RoomID

Int

The foreign key that identifies to which chat room this

 

 

message is posted.

UserID

Int

The foreign key that identifies which user posted this

 

 

message.

Text

varchar(MAX)

The actual chatted message text.

Timestamp

Datetime

The automatically generated date and time of the message

 

 

as it was entered into the database.

The messages have a foreign key of the UserID, which is a reference to the User table, explained next.

The User Table

The User table provides specific information about the chat users, allowing their presence and usage to be customized, secured, tracked, and reported on. The following is a depiction of the columns within the User table:

Field Name

Data Type

Description

 

 

 

ID

Int

The unique identifier for this record.

Email

varchar(MAX)

The e-mail address of the user.

 

 

 

The data model seems to meet the essential element needs, and provides a level of simplistic design you would hope for.

Next, you dive into the visual customization techniques with the use of themes and skins.

Themes and Skins

The project provides a simple way to apply themes and skins to each page of the site, without modifying any HTML markup sections on any page (even the master page is safe from special control-based HTML markup). You can apply a theme to the entire web site by modifying the Web.config file to point to the name of your theme (assuming the theme exists in your project under the App_Themes folder). This is

80

Wrox Chat Server

carried out within each ASP.NET form by using the following code in each of the form’s pre-initialization events:

‘’’ <summary>

‘’’ this preinit event fires to initialize the page. It allows for the ‘’’ theme and title to be set for this page, which actually pulls from

‘’’ the web.config setting via the shared Config class’s exposed properties. ‘’’ </summary>

Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit

Page.Theme = Config.CurrentTheme Page.Title = Config.PageTitle

End Sub

This basically accesses the config class’s properties (pulled from the Web.config file), and sets the page’s theme member to be the current theme value. In this way, you can maintain a consistent experience throughout the web site, with only one change needed to Web.config in order to change the look and feel of the entire user experience! You are probably glad to hear that — I know I am. The exact place where you would change the theme for the site is in the appSettings section of Web.config, as displayed here:

<!--

<add key=”CurrentTheme” value=”CleanBlue” />

-->

<add key=”CurrentTheme” value=”CleanRed” />

This code displays one of the theme entries as commented out, and one of them as active. Simply swap the two values in order to make the change.

Classes Involved

The Wrox Chat Server contains some essential classes that represent the business and data layers of the application. In these basic class structures, you will find methods and properties that provide the bulk of the features in the application.

The ChatRoom Class

The ChatRoom class (see Figure 3-5) is essentially the class that allows for the actual saving and retrieving of the chat room’s textual messages to and from the database. The ChatRoom class is used to perform the bulk of the object and contextual user interface provisioning as a business layer for the application. Its methods are accessible as public and shared for ease of use within the various forms and controls

of the application. This means that you do not have to instantiate an instance of the resource class in order to call its methods. Instead, simply use the syntax of ChatRoom.MethodName() in any VB.NET WebForm or control of the application to execute the function.

The ChatRoom class’s methods are detailed in the following table:

Method

Return Type

Description

 

 

 

SaveMessage()

n/a

Saves the chat message, passing it off to the

 

 

ChatRoomDB class.

 

 

Table continued on following page

81

Chapter 3

Method

Return Type

Description

 

 

 

GetMessagesForChatRoom()

String

Retrieves the chat room’s HTML string from

 

 

the database, via the ChatRoomDB class.

GetChatRoomList()

String

Retrieves an HTML string listing of

 

 

chat rooms, grouped by category as an

 

 

HTML string from the database, via the

 

 

ChatRoomDB class.

 

 

 

Figure 3-5

This ChatRoom class acts as the business layer, providing an interface to the data access layer, the

ChatRoomDB class.

The ChatRoomDB Class

The ChatRoomDB class (see Figure 3-6) acts as a data layer for the application, because it is the sole entity responsible for selecting data from or inserting data into the database. This is a typical way of consolidating commonly used data execution logic into a single managed class.

Figure 3-6

82

Wrox Chat Server

The following table displays the accessible members of the ChatRoomDB class:

Method

Return Type

Description

 

 

 

SaveMessage()

n/a

Saves the chat message into the database.

GetMessagesForChatRoom()

String

Retrieves the chat room’s HTML string of

 

 

messages out of the database.

GetChatRoomList()

String

Retrieves an HTML string listing of chat

 

 

rooms, grouped by category as an HTML

 

 

string from the database.

 

 

 

This wraps up the essential classes of the application. The next class stores references to the configuration variables of the application, which are stored in the Web.config file.

The Config Class

The Config class, depicted in Figure 3-7, is used as the configuration manager of the application. It is essentially the main access point for all configuration settings that any of the application tiers may require access to.

Figure 3-7

The following table displays the accessible members of the Config class:

Property

Return Type

Description

 

 

 

ConnectionString()

String

The connection string property that pulls

 

 

from Web.config.

CurrentTheme()

String

The current theme of the web site as

 

 

defined in the Web.config file.

PageTitle()

String

The HTML title value that each page

 

 

displays, as defined here from the

 

 

Web.config file.

HoursToShow()

Integer

The number of hours for the recent chat

 

 

room messages to keep showing.

 

 

 

Now you have seen the classes involved and their applicable method calls. The next section walks you through each of the code sections of interest.

83

Chapter 3

Code and Code Explanation

This section explains each of the essential code files in the Wrox Chat Server project. It looks in detail at the files in the each of the different folders and explains how they interact and are used across the project.

Root Files

The root of the Wrox Chat Server contains several important files, including the main ASPX shell-pages, and the configuration and formatting pages.

Web.config

The Web.config stores vital configuration entries used within the application. One entry, named the SqlServerConnectionString, controls the connection to the SQL Server 2005 Express database file ChatServerDB.mdf, as seen here:

<connectionStrings>

<add name=”ConnectionString”

connectionString=”Data Source=(local)\SqlExpress;AttachDbFilename=

|DataDirectory|\ChatServerDB.mdf;Integrated Security=True;User Instance=True” providerName=”System.Data.SqlClient”/>

</connectionStrings>

It also contains the other entries for showing chat messages, the page title, and the currently used theme, as displayed here:

<appSettings>

<add key=”HoursToShow” value=”1”/>

<add key=”PageTitle” value=”Wrox Chat Server”/> <!--

<add key=”CurrentTheme” value=”CleanBlue” /> -->

<add key=”CurrentTheme” value=”CleanRed”/> </appSettings>

This is where the easy modification can take place for changing which theme is used for each page of the site. You can find more information on this in the “Themes and Skins” section earlier in the chapter.

Config.vb

The Config class is used as an available business object for values and settings through visibility of some static members. Its members are listed as properties in order to abstract the location in which these values are stored. All of the values for the properties are stored in the Web.config file, with this Config class retrieving them when they are needed:

Imports Microsoft.VisualBasic

Public Class Config

‘’’ <summary>

‘’’ The connection string property that pulls from the web.config ‘’’ </summary>

Public Shared ReadOnly Property ConnectionString() As String Get

84

Wrox Chat Server

Return ConfigurationManager.ConnectionStrings( _ “ConnectionString”).ConnectionString

End Get End Property ‘’’ <summary>

‘’’ The current theme of the website as defined in the web.config ‘’’ </summary>

Public Shared ReadOnly Property CurrentTheme() As String Get

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

End Property ‘’’ <summary>

‘’’ The HTML title value that each page displays, as defined ‘’’ here from the web.config file

‘’’ </summary>

Public Shared ReadOnly Property PageTitle() As String Get

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

End Property

‘’’ <summary>

‘’’ The number of hours back in time from the current time ‘’’ that each chat room displays, as defined here from the ‘’’ web.config file

‘’’ </summary>

Public Shared ReadOnly Property HoursToShow() As String Get

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

End Property End Class

As the Config class displays, the properties are marked as Public Shared ReadOnly, which allows them to be accessed from anywhere in the project by the config-dot notation. An example of this would be config.ConnectionString(). This would return the connection string from the Config class, without instantiating a Config class object first.

ChatRoom.vb

The ChatRoom class is used to retrieve and save the chat messages being passed between the web site and the client browsers. The class acts as a business layer and provides a level of abstraction between the requests for database records and the user interface.

One of the more important method calls of the resource is the SaveResource method. The code for this is as follows:

‘’’ <summary>

‘’’ Saves a Message to the ChatRoom in the database ‘’’ </summary>

Public Shared Function SaveMessage(ByVal ChatRoomID As Integer, _ ByVal Text As String, ByVal Email As String) As Boolean Return ChatRoomDB.SaveMessage(ChatRoomID, Text, Email)

End Function

85

Chapter 3

It accepts the following three parameters:

ChatRoomID

Text

Email

These represent the necessary pieces of information to save the message into the database. The SaveResource method provides the means by which to hand off a Resource class object to the data tier for processing. Thus, the ChatRoomDB.SaveMessage call is made to pass on the heavy lifting to the data layer (the ChatRoomDB class).

ChatRoomDB.vb

The ChatRoomDB class is essentially the data layer for the application. It provides method calls to retrieve information from the database and insert or update data within the database. This class serves as the only file or object that will have access to the database files. In so doing, you can isolate data-specific operations outside of the business logic layer. This technique protects a developer from writing duplicate data access code and helps to maintain organized and structured data access logic. This also supports the application from being logically separated into tiers, or layers, with the deliberate feasibility of migrating and expanding the application onto separate servers at any point in time.

The ChatRoomDB class contains a SaveMessage() method, as displayed here:

‘’’ <summary>

‘’’ Saves a Message to the ChatRoom in the database ‘’’ </summary>

Public Shared Function SaveMessage(ByVal ChatRoomID As Integer, _ ByVal Text As String, ByVal Email As String) As Boolean

Using mConnection As New SqlConnection(Config.ConnectionString) ‘Create a command object

Dim mCommand As SqlCommand = New SqlCommand( _ “sprocMessageInsertUpdateItem”, mConnection)

‘set it to the type of ‘stored procedure’ mCommand.CommandType = CommandType.StoredProcedure ‘parameters: the ChatRoomID, the Message text, and the UserID mCommand.Parameters.AddWithValue(“@roomID”, ChatRoomID) mCommand.Parameters.AddWithValue(“@Email”, Email) mCommand.Parameters.AddWithValue(“@text”, Text)

‘open the connection and execute the stored procedure mConnection.Open()

Dim result As Integer = mCommand.ExecuteNonQuery() ‘close the connection and dispose of the command mConnection.Close()

mCommand.Dispose() Return True

End Using End Function

Another method of interest is the GetChatRoomList() method, returning a DataSet containing the chat rooms entered into the database, along with their assigned categories.

86