• No results found

Object Binding and SQL Server Data Binding

In document Instant Results pdf (Page 133-141)

In an effort to develop an application rapidly and efficiently, there is always a tradeoff for developers to consider. Some project planning and design sessions may point toward the use of faster and lightweight GUI controls to perform the bulk of the work for the developer, saving countless hours of effort. A spe- cific example of lightweight GUI controls would be the GridViewand DataListcontrols. These allow you to drag and drop controls to a WebForm, set some properties in Design View, and run the applica- tion. Without writing one line of VB .NET or C# code, you can configure a data source and data-bound control to render completely on the WebForm. The new ASP.NET 2.0 control creates the ADO.NET Connection, Command, Dataset, or DataReaderobjects for you, providing everything you need to bind to the data at run time. It also properly handles the events used for data binding on the page — something that ASP.NET 1.1 did not do for you (Phew! Thank goodness!). These are in fact a great set of features to take advantage of. But even so, many programmers will read through this book to learn the more extensive and far-reaching features of ASP.NET 2.0, moving on as programmers in the new and improved .NET universe, and rightly so. But for those who are interested in larger-scale deployments with ASP.NET 2.0, it is a worthwhile effort to identify the reasons why the tradeoffs of using more scal- able architectures, and what you are losing or gaining with each methodology in ASP.NET 2.0 specifi- cally. The scalability of an architecture has a lot to do with the load it can carry in cases where a large volume of data is involved, or a heavy amount of processing is required. It also refers to the level of con- trol that exists in throttling or directing the processing, traffic, or data appropriately. ASP.NET 2.0 han- dles such cases with several intrinsic benefits that set it apart as a world class platform for development. Truly decoupled architectures in the industry are more often seen in larger corporate application devel- opment cycles and are usually designed as more generic and pattern-based. The decoupled approach tends to isolate user, business, and data layers of an application into specific sections, allowing each to function independently. This is the nature of distributed development, and has evolved into what is sometimes referred to as composite applications. The distributed design would tend to only provide data- base execution logic within a layer of code (classes) that are specifically positioned and designed to make such data calls. Only those classes are able to extract and handle data out of the database, acting as a go-between for the other application modules or classes. As such, the use of business objects (such as the Surveyclass) would allow a request for data to go out to other classes as a data layer (for example, the SurveyDBclass), returning data back to the client and binding to the data grid, list box, and so on. This approach is generally acceptable for most applications.

In this area of object and data binding, you will notice in this Wrox Survey Engine application we make use of the built-in ASP.NET ObjectDataSourcecontrols to bind data from business objects to GUI (graphical user interface) controls. This in many ways mimics a decoupled, object-based approach that has been held as a best practice in recent years, but by itself may not provide all of the custom and robust features that a corporate project’s requirements or design may mandate. Some class objects need to be serialized and transferred through an Internet connection between tiers, in order to allow for the separate server environments. Other class objects or modules are pooled and managed closely using process instrumentation (WMI) or ASP.NET performance monitors (PerfMon). These additional object- level requirements can be met using the ObjectDataSourcecontrols, but it may require additional development and is worthy of mentioning in the course of this book.

In addition to the ObjectDataSourcecontrols, the Wrox Survey Engine also uses the SQL Server DataSourcecontrols to extract data from the SQL Server Express 2005 database files and bind it to the GUI controls. Contrary to this line of thinking, the SqlDataSourcecontrols are typically designed as a quick and dirty way to select records from a database and bind them to a form. This process actually includes the SQL statements in the markup of your ASPX files. In direct opposition to a safer and more distributed approach of the decoupled tiers, this poses a risk to the application and management thereof. As more users access such pages, more database connections may be created (depending on the connec- tion strings used), thereby increasing the number of pooled or non-pooled connections to the database on the server. This can ultimately cause a loss of scalability, and speed, and if not used carefully could pose a risk to sites with heavy traffic. The use of the SqlDataSourcecontrols also requires updates to the source ASPX files of your site whenever database changes are made that affect your queries or stored procedures. This is not ideal for an application to maintain a predictable and manageable state. But as stated in other chapters, and expounded herein, such risks are overlooked, instead providing a meaning- ful experience with both the ObjectDataSourceand the SqlDataSourcecontrols.

Structure of the Site

The site has been structured in an organized fashion, with files contained within folders that make sense for maintaining the code in the most efficient manner. The Controls folder houses all of the user controls, and the ContentFiles folder contains the main ASPX WebForm files of the web site.

The different folder sections of the web application are listed in the following table:

Folder Description

App_Code Houses the business layer class (survey.vb) and the data layer class (surveyDB.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. Management Stores the secured administrative WebForm pages.

Miscellaneous files These include the Login page, the Web.config file, the sitemap file, and the master page file at the root of the site.

Figure 4-12 is a developer’s view of the project’s folders and files from within the Solution Explorer.

Figure 4-12

The next section explains the main database entities involved and how the various survey concepts are implemented within the database.

Data Model and Database Objects

The data model is very simple in nature, being comprised of essentially three basic data elements:

❑ Surveys

❑ Questions

❑ Responses

Each survey has questions, for which you or any web user can provide their own selections, which gen- erates the response values. As such, Figure 4-13 displays a diagram of the database tables involved.

Figure 4-13

The following table describes the contents of the Question table:

Field Name Data Type Description

ID Int The unique identifier for this record. SurveyID Int The survey to which this question belongs. Text varchar(1000) The actual question text.

OptionA varchar(1000) The first of four choices. OptionB varchar(1000) The second of four choices. OptionC varchar(1000) The third of four choices. OptionD varchar(1000) The fourth of four choices. The next table outlines the Survey table:

Field Name Data Type Description

ID Int The unique identifier for this record. Name varchar(200) The name given to the survey.

Description varchar(1000) The text description given to the survey.

Date Datetime The date and time stamp at the time that the survey was created.

IsCurrentSurvey Char(1) The 0 or 1 value indicating that the survey is the one used within the web site as the currently displayed survey. 1 represents that the record is the current survey, and 0 signifies the record is not the current survey.

The following table details the contents of the Response table:

Field Name Data Type Description

ID Int The unique identifier for this record.

QuestionID Int The question ID to which this response applies. Selection Char(1) The A, B, C, or D value corresponding to the user’s

selection for the question being responded to.

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

sprocTableNameSelectList

sprocTableNameSelectSingleItem

sprocTableNameInsertUpdateItem

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

❑ sprocQuestionDeleteSingleItem ❑ sprocQuestionInsertUpdateItem ❑ sprocQuestionSelectList ❑ sprocResponseInsertItem ❑ sprocSurveyInsertUpdateItem ❑ sprocSurveySaveSingleItemAsCurrent ❑ sprocSurveySelectList ❑ sprocSurveySelectSingleItem ❑ sprocSurveySelectSingleItemWhereCurrent

As you can see, 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.

Several noteworthy stored procedures should be reviewed. The first procedure selects a single survey record from the database to display in the CurrentSurveyuser control on the Default.aspx homepage:

ALTER PROCEDURE dbo.sprocSurveySelectSingleItemWhereCurrent /*’===============================================================

‘ NAME: sprocSurveySelectSingleItemWhereCurrent ‘ DATE CREATED: October 5, 2005

‘ CREATED BY: Shawn Livermore (shawnlivermore.blogspot.com) ‘ CREATED FOR: ASP.NET 2.0 - Instant Results

‘ FUNCTION: Returns the ‘current’ survey from the database. ‘=============================================================== */

as

select top 1 * from Survey where iscurrentsurvey = 1

As you can see, the level of complexity within these stored procedures is down to a minimum in this project. The simple table structure of the application is partly the reason for the ease of use and low level of design complexity.

The next procedure is used to select out all of the questions for a given survey ID: ALTER PROCEDURE dbo.sprocQuestionSelectList

/*’=============================================================== ‘ NAME: sprocQuestionSelectList

‘ DATE CREATED: October 5, 2005

‘ CREATED FOR: ASP.NET 2.0 - Instant Results

‘ FUNCTION: retrieves all questions and options for a ‘ specific survey from the database.

‘=============================================================== */

(@id int)

as

SELECT Question.SurveyID, Question.Text, Question.OptionB, Question.OptionA, Question.OptionD, Question.OptionC, Question.ID

FROM Survey INNER JOIN Question ON Survey.ID = Question.SurveyID WHERE (Survey.ID = @id)

These are the basic stored procedures used as examples, but entirely common for these types of applications.

In addition to stored procedures and tables, the Wrox Survey Engine also employs the use of views to provide visibility to somewhat complex queries used to display the percentage results of a survey’s questions. These views are as follows:

❑ viewAnswerPercentByQuestion ❑ viewAnswerSumByQuestion ❑ viewNumberResponsesBySurvey ❑ viewQuestionCountBySurvey ❑ viewResponseCountBySurvey

These are used in conjunction with one another as dependencies, where one view uses or points to the fields of another view. The end result of the views is the viewAnswerPercentByQuestion, which is used by the SurveyResults user control.

Themes and Skins

The project provides a simple way in which 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 carried out within each ASP.NET form by using the following code in each of the form’s pre-initialization events:

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

‘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. Page.Theme = Config.CurrentTheme

Page.Title = Config.PageTitle End Sub

This code accesses the configclass’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 the 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 appSettingssection of the 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.

Security Model

The project uses ASP.NET 2.0 Forms Authentication with a SQL Server Security Provider. The initial des- ignation to use this provider from within the ASP.NET Security Administration tool generates a new security database, which is included in the project and used to house all of the user account information and security settings. This security model implements Forms Authentication intrinsically within the var- ious new ASP.NET 2.0 security controls, such as those used to log in, display login status, recover your password, change your password, and create a new user.

The security model mentioned is utilized and referenced in several areas of the application. One such area is in reference to the Management folder of the site. The security model allows you to log in to the web site, and become an authenticated user. The login.aspx form is loaded automatically whenever you try to access any of the ASPX files in the Management folder without first being unauthenticated. This is a clear glimpse at the new ASP.NET 2.0 security model implemented via the Role and Membership Providers. The configuration is such that the only provision to implement such security is an instance of the ASP.NET Logincontrol, such as the following example:

<asp:Login ID=”Login1” runat=”server” />

As a practical use, this provides a clear example of a secure web site folder and the use of role-based access to pages within that folder via the ASP.NET 2.0 Configuration Tool. This tool is essentially used simply for security-rights management. The ASP.NET 2.0 Configuration Tool can be accessed within Visual Studio by clicking Website➪ASP.Net Configuration from the menu. Once the tool fully loads you’ll see a Security tab. Clicking the Security tab enables you to modify the settings of any folder within your site to allow or restrict access based on roles that you can define and assign users to. The output of this effort generates the Web.config file that lies within the folder that you specified to restrict access to. The following is an example of this Web.config file output:

<?xml version=”1.0” encoding=”utf-8”?> <configuration xmlns=”http://schemas.microsoft.com/.NetConfiguration/v2.0”> <system.web> <authorization> <deny users=”?” /> <allow roles=”Admin” /> <allow roles=”SuperAdmin” />

</authorization> </system.web>

</configuration>

This configuration file uses three main entries as the meat of the security settings. These are essentially a series of statements in XML format that define the security rights for that folder, hierarchically within the web site, overriding the web site’s root Web.config, as well as the machine.config on the server. In this file, the <deny users=”?” />phrase means that the folder should deny any unauthenticated users, denoted by the question mark. Next, the <allow roles=”Admin” />and the <allow roles=”SuperAdmin” />entries both represent the ability of the folder to allow access to Admin or Superadmin roles.

Two accounts are created for use within the Survey Engine, and two different roles that those accounts are assigned to, respectively. These are as follows:

Username Password Account Description

Admin password# This user is assigned to the Administrator role. SuperAdmin password# This user is assigned to the Super Administrator

role.

The following two roles are already in the security database and referenced within the application for certain areas of interest to remain very secure:

Role Role Description

Administrator This role has the ability to add, edit, and delete surveys and their questions.

Super Administrator This role has the same privileges as the Administrator role, but also can delete surveys and/or their individual questions from the system. Thus, you can control access to form elements and folders alike, using the ASP.NET Configuration Tool, or your own scripted logic in VB .NET.

Classes Involved

Only a few basic classes are in use for the Wrox Survey Engine, but they are intelligent classes that are designed to work in an object-friendly fashion. That is, in a typical object-oriented environment, the class structures would seem to fare well as compared to other object structures.

The SurveyBase Class

The SurveyBaseclass (see Figure 4-14) is essentially the inheritable base class to which every survey refers. It allows the derived Surveyclass objects to provide exposure to the Saveand Newmethods for consistent and convenient class management.

Figure 4-14

The following table describes the methods available to the SurveyBaseclass:

Method Return Type Description

New() n/a The constructor for the SurveyBaseclass Save() Int The savemethod used to save the derived

survey class object

In document Instant Results pdf (Page 133-141)